Enrutar con el mux estándar en Go
Go 1.22 le enseñó a ServeMux métodos y variables de ruta.
func newMux() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter,
r *http.Request) {
fmt.Fprint(w, "ok")
})
mux.HandleFunc("GET /tours/{slug}", func(w http.ResponseWriter,
r *http.Request) {
slug := r.PathValue("slug")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"slug": slug})
})
mux.HandleFunc("POST /results", func(w http.ResponseWriter,
r *http.Request) {
defer r.Body.Close()
w.WriteHeader(http.StatusCreated)
})
return mux
}
Cómo funciona
- El patrón puede empezar con un método: GET /tours/{slug}.
r.PathValuelee una variable de la ruta.- No hace falta un router de terceros para esta forma de API.
Palabras clave y builtins usados aquí
deferfuncmapreturnstring
El intento, en números
- Líneas
- 23
- Caracteres a escribir
- 535
- Tokens
- 149
- Ritmo de tres estrellas
- 110 tpm
Al ritmo de tres estrellas de 110 tokens por minuto, este intento toma unos 81 segundos.
Paso 1 de 5 en HTTP; paso 16 de 26 en Biblioteca estándar y estructura del proyecto.