Un handler HTTP en Go
Servir JSON con net/http y 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
}
Cómo funciona
- Un handler recibe un ResponseWriter y un Request.
- Las comprobaciones de método rechazan el verbo incorrecto.
ServeMuxenruta rutas hacia handlers.
Palabras clave y builtins usados aquí
funcifmapreturnstring
El intento, en números
- Líneas
- 14
- Caracteres a escribir
- 384
- Tokens
- 98
- Ritmo de tres estrellas
- 110 tpm
Al ritmo de tres estrellas de 110 tokens por minuto, este intento toma unos 53 segundos.
Paso 2 de 5 en HTTP; paso 17 de 26 en Biblioteca estándar y estructura del proyecto.