how to implement etag in web server?

2,215 views
Skip to first unread message

thstart

unread,
Dec 14, 2012, 12:37:06 PM12/14/12
to golan...@googlegroups.com
I want to use etags to reduce bandwidth - are there build in
etags in standard web server?

minux

unread,
Dec 14, 2012, 12:39:57 PM12/14/12
to thstart, golan...@googlegroups.com
On Sat, Dec 15, 2012 at 1:37 AM, thstart <brag...@bragbuddy.com> wrote:
I want to use etags to reduce bandwidth - are there build in
etags in standard web server?
if your handle use http.ServeContent to serve content and set ETag in header
before calling that, net/http will automatically handle some ETag related stuff
for you (If-Non-Match, for example)

thstart

unread,
Dec 14, 2012, 12:51:12 PM12/14/12
to golan...@googlegroups.com, thstart
I am using following code:

  var webroot = flag.String("root", "/public", "web root directory")

  func handler(w http.ResponseWriter, r *http.Request) {
  ...
  }
   http.Handle("/images/", http.StripPrefix("", http.FileServer(http.Dir(*webroot))))
   http.HandleFunc("/", handler)
   http.ListenAndServe(listenAddr, nil)

What I need to set so the etag be computed for the static files in webroot?

Caleb Doxsey

unread,
Dec 15, 2012, 4:35:16 PM12/15/12
to golan...@googlegroups.com, thstart
You're going to have to write a custom handler instead of just using the built in FileServer. Something like:
  • Create a function to use with http.Handle("/images/", ...)
  • Make that function take the path the user sends in and translate it into the filename
  • Open the file and compute the hash of the file (might want to cache this...)
  • Add the ETag header
  • As minux said use ServeContent to send it back to the user
ETags are sub-optimal. A better approach is to set the content to never expire and use a hash in the URL.

Reply all
Reply to author
Forward
0 new messages