02226d61f6
Seis funciones de servidor HTTP con tests usando httptest: - HTTPJSONResponse: escribe JSON con Content-Type y status code - HTTPErrorResponse: escribe HTTPError como JSON estructurado - HTTPParseBody: decode JSON con limite de bytes y campos estrictos - HTTPLoggerMiddleware: loguea method/path/status/duration a io.Writer - HTTPRouter: crea ServeMux con rutas Go 1.22+ (METHOD /path) - HTTPServe: ListenAndServe con graceful shutdown por contexto 23 tests pasando, solo stdlib net/http. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
41 lines
1.5 KiB
Markdown
41 lines
1.5 KiB
Markdown
---
|
|
name: http_router
|
|
kind: function
|
|
lang: go
|
|
domain: infra
|
|
version: "1.0.0"
|
|
purity: impure
|
|
signature: "func HTTPRouter(routes []Route) *http.ServeMux"
|
|
description: "Crea un http.ServeMux y registra las rutas dadas usando la sintaxis de Go 1.22+ (METHOD /path). Retorna el mux listo para usar con http.ListenAndServe."
|
|
tags: [http, router, mux, server, routes, infra]
|
|
uses_functions: []
|
|
uses_types: [Route_go_infra]
|
|
returns: []
|
|
returns_optional: false
|
|
error_type: "error_go_core"
|
|
imports: [fmt, net/http]
|
|
params:
|
|
- name: routes
|
|
desc: "slice de Route con Method, Path y Handler a registrar en el mux"
|
|
output: "http.ServeMux configurado con todas las rutas"
|
|
tested: true
|
|
tests: ["registra una ruta y responde correctamente", "registra multiples rutas en el mismo mux", "ruta no registrada retorna 404"]
|
|
test_file_path: "functions/infra/http_server_test.go"
|
|
file_path: "functions/infra/http_router.go"
|
|
---
|
|
|
|
## Ejemplo
|
|
|
|
```go
|
|
mux := HTTPRouter([]Route{
|
|
{Method: "GET", Path: "/api/health", Handler: http.HandlerFunc(healthHandler)},
|
|
{Method: "POST", Path: "/api/users", Handler: http.HandlerFunc(createUserHandler)},
|
|
{Method: "GET", Path: "/api/users/{id}", Handler: http.HandlerFunc(getUserHandler)},
|
|
})
|
|
http.ListenAndServe(":8080", mux)
|
|
```
|
|
|
|
## Notas
|
|
|
|
Usa la sintaxis "METHOD /path" de Go 1.22+ para registrar rutas con metodo especifico. Soporta parametros de path como {id} accesibles via r.PathValue("id"). Sin rutas registradas retorna un mux vacio que responde 404 a todo.
|