Skip to content

Instantly share code, notes, and snippets.

@emaxerrno
Created August 29, 2013 13:54
Show Gist options
  • Select an option

  • Save emaxerrno/6378378 to your computer and use it in GitHub Desktop.

Select an option

Save emaxerrno/6378378 to your computer and use it in GitHub Desktop.
Etag.go
package main
import (
"bitbucket.org/agallego/log"
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
)
var (
IdGenerator = 0
)
func main() {
log.Info("Starting")
http.HandleFunc("/ym.jpg", func(w http.ResponseWriter, r *http.Request) {
log.Info("requesting jpg")
// log.Info("All headers %+#v", r.Header)
if len(r.Header.Get("If-None-Match")) != 0 || len(r.Header.Get("etag")) != 0 {
tag := r.Header.Get("ETag")
if len(tag) == 0 {
tag = r.Header.Get("If-None-Match")
}
log.Info("Using old etag: %s", tag)
w.Header().Set("ETag", tag)
w.WriteHeader(http.StatusNotModified)
} else {
log.Info("generating etag")
fileBytes, _ := ioutil.ReadFile("static/ym.jpg")
IdGenerator++
log.Info("Using ETag: %d", IdGenerator)
w.Header().Set("ETag", fmt.Sprintf("%d", IdGenerator))
w.Header().Set("Content-type", "image/jpeg")
w.Header().Set("Content-length", fmt.Sprintf("%d", len(fileBytes)))
w.Header().Set("If-None-Match", fmt.Sprintf("%d", IdGenerator))
io.Copy(w, bytes.NewReader(fileBytes))
}
})
http.Handle("/", http.FileServer(http.Dir("static")))
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment