Skip to content

Instantly share code, notes, and snippets.

@Abdulsametileri
Forked from santiaago/cache.go
Created April 16, 2022 04:53
Show Gist options
  • Save Abdulsametileri/c332c498ff8c56a5649a82baf751f305 to your computer and use it in GitHub Desktop.
Save Abdulsametileri/c332c498ff8c56a5649a82baf751f305 to your computer and use it in GitHub Desktop.
Learning HTTP caching in Go
package main
import (
"bytes"
"flag"
"image"
"image/color"
"image/draw"
"image/jpeg"
"log"
"net/http"
"strconv"
"strings"
)
var root = flag.String("root", ".", "file system path")
func main() {
http.HandleFunc("/black/", blackHandler)
http.Handle("/", http.FileServer(http.Dir(*root)))
log.Println("Listening on 8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}
func blackHandler(w http.ResponseWriter, r *http.Request) {
key := "black"
e := `"` + key + `"`
w.Header().Set("Etag", e)
w.Header().Set("Cache-Control", "max-age=2592000") // 30 days
if match := r.Header.Get("If-None-Match"); match != "" {
if strings.Contains(match, e) {
w.WriteHeader(http.StatusNotModified)
return
}
}
m := image.NewRGBA(image.Rect(0, 0, 240, 240))
black := color.RGBA{0, 0, 0, 255}
draw.Draw(m, m.Bounds(), &image.Uniform{black}, image.ZP, draw.Src)
var img image.Image = m
writeImage(w, &img)
}
// writeImage encodes an image in jpeg format and writes it into ResponseWriter.
func writeImage(w http.ResponseWriter, img *image.Image) {
buffer := new(bytes.Buffer)
if err := jpeg.Encode(buffer, *img, nil); err != nil {
log.Println("unable to encode image.")
}
w.Header().Set("Content-Type", "image/jpeg")
w.Header().Set("Content-Length", strconv.Itoa(len(buffer.Bytes())))
if _, err := w.Write(buffer.Bytes()); err != nil {
log.Println("unable to write image.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment