typestar

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

  1. Un handler recibe un ResponseWriter y un Request.
  2. Las comprobaciones de método rechazan el verbo incorrecto.
  3. ServeMux enruta rutas hacia handlers.

Palabras clave y builtins usados aquí

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.

Escribe este fragmento

Paso 2 de 5 en HTTP; paso 17 de 26 en Biblioteca estándar y estructura del proyecto.

← Anterior Siguiente →