typestar

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

  1. A handler takes a ResponseWriter and Request.
  2. Method checks reject the wrong verb.
  3. ServeMux routes paths to handlers.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 5 in HTTP, step 17 of 26 in Standard library & project layout.

← Previous Next →