An HTTP handler in Go
Serving JSON with net/http and ServeMux.
func handleHealth(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}
func routes() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("/healthz", handleHealth)
return mux
}
How it works
- A handler takes a ResponseWriter and Request.
- Method checks reject the wrong verb.
ServeMuxroutes paths to handlers.
Keywords and builtins used here
funcifmapreturnstring
The run, in numbers
- Lines
- 14
- Characters to type
- 384
- Tokens
- 98
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 53 seconds.
Step 2 of 5 in HTTP, step 17 of 26 in Standard library & project layout.