Skip to content

Instantly share code, notes, and snippets.

@shibukawa
Created July 7, 2016 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shibukawa/2395dda42ab131b65916cd15303ddf77 to your computer and use it in GitHub Desktop.
Save shibukawa/2395dda42ab131b65916cd15303ddf77 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"github.com/k0kubun/pp"
"log"
"net/http"
"os"
"strconv"
"time"
)
type Cache struct {
CacheControl string
Etag string
Reject bool
Abort bool
Content string
}
var strategyId int
var cacheControls = []string{
"max-age=5",
"max-age=0",
"no-cache, max-age=5",
"no-cache, max-age=0",
"must-revalidate, max-age=5",
"must-revalidate, max-age=0",
}
func getStrategy(filename string) Cache {
id := strategyId - 1
if filename == "/" {
return Cache{
Reject: false,
Content: `<html><body><a href="/next.html">link</a></body></html>`,
}
} else if filename == "/next.html" {
return Cache{
Etag: "5678",
CacheControl: cacheControls[id%6],
Reject: false,
Abort: ((id / 6) % 2) == 1,
Content: `<html><body>hello</body></html>`,
}
}
return Cache{
Reject: true,
Content: "",
}
}
func handler(w http.ResponseWriter, r *http.Request) {
etags, ok := r.Header["If-None-Match"]
if ok {
pp.Println("request", r.Method, r.URL.String(), time.Now().Unix(), etags[0])
} else {
pp.Println("request", r.Method, r.URL.String(), time.Now().Unix())
}
strategy := getStrategy(r.URL.String())
if strategy.Reject {
// favicon.ico
fmt.Println(" Status:", http.StatusNotFound)
w.WriteHeader(http.StatusNotFound)
return
}
if ok {
if strategy.Abort {
fmt.Println(" Abort")
panic("Abort")
}
fmt.Println(" Status:", http.StatusNotModified)
w.WriteHeader(http.StatusNotModified)
return
} else {
fmt.Println(" Status:", http.StatusOK)
}
if strategy.Etag != "" {
fmt.Println(" Etag:", strategy.Etag)
w.Header().Set("Etag", strategy.Etag)
}
fmt.Println(" Cache-Control:", strategy.CacheControl)
w.Header().Set("Cache-Control", strategy.CacheControl)
fmt.Fprintf(w, strategy.Content)
}
func main() {
strategyId, _ = strconv.Atoi(os.Args[1])
if strategyId > 12 || strategyId < 1 {
log.Fatalf("wrong id: %d", strategyId)
}
var httpServer http.Server
http.HandleFunc("/", handler)
log.Println("start http listening :18888")
httpServer.Addr = ":18888"
log.Println(httpServer.ListenAndServe())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment