Skip to content

Instantly share code, notes, and snippets.

@dekokun
Created March 28, 2016 07:39
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 dekokun/857caa3dcccaeaeefd60 to your computer and use it in GitHub Desktop.
Save dekokun/857caa3dcccaeaeefd60 to your computer and use it in GitHub Desktop.
http requestしたらheaderをjsonで返してくれるやつ
package main
import (
"encoding/json"
"log"
"net/http"
)
func rootHandler(w http.ResponseWriter, r *http.Request, cache bool) {
type Response struct {
Status string `json:"status"`
Data string `json:"data"`
}
headers := r.Header
headers["Host"] = []string{r.Host}
json, _ := json.Marshal(r.Header)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if cache {
w.Header().Set("Cache-Control", "max-age=2592000")
} else {
w.Header().Set("Cache-Control", "no-cache")
}
w.WriteHeader(200)
w.Write(json)
log.Print("get request")
}
func cacheHandler(w http.ResponseWriter, r *http.Request) {
rootHandler(w, r, true)
log.Print("cached")
}
func nocacheHandler(w http.ResponseWriter, r *http.Request) {
rootHandler(w, r, false)
log.Print("not cached")
}
func main() {
http.HandleFunc("/cache", cacheHandler)
http.HandleFunc("/nocache", nocacheHandler)
http.HandleFunc("/non", nocacheHandler)
log.Fatal(http.ListenAndServe("localhost:30000", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment