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>
43 lines
1.5 KiB
Markdown
43 lines
1.5 KiB
Markdown
---
|
|
name: http_json_response
|
|
kind: function
|
|
lang: go
|
|
domain: infra
|
|
version: "1.0.0"
|
|
purity: impure
|
|
signature: "func HTTPJSONResponse(w http.ResponseWriter, status int, data any)"
|
|
description: "Escribe data como JSON en el ResponseWriter con el status code dado. Setea Content-Type: application/json automaticamente."
|
|
tags: [http, json, response, server, infra]
|
|
uses_functions: []
|
|
uses_types: []
|
|
returns: []
|
|
returns_optional: false
|
|
error_type: "error_go_core"
|
|
imports: [encoding/json, net/http]
|
|
params:
|
|
- name: w
|
|
desc: "ResponseWriter donde se escribe la respuesta HTTP"
|
|
- name: status
|
|
desc: "codigo de status HTTP (ej: 200, 201, 400, 500)"
|
|
- name: data
|
|
desc: "cualquier valor serializable a JSON que se escribe como body de la respuesta"
|
|
output: "escribe la respuesta JSON directamente en w, sin valor de retorno"
|
|
tested: true
|
|
tests: ["escribe status code correcto", "setea Content-Type application/json", "serializa datos correctamente a JSON"]
|
|
test_file_path: "functions/infra/http_server_test.go"
|
|
file_path: "functions/infra/http_json_response.go"
|
|
---
|
|
|
|
## Ejemplo
|
|
|
|
```go
|
|
func getUser(w http.ResponseWriter, r *http.Request) {
|
|
user := map[string]string{"id": "1", "name": "Lucas"}
|
|
HTTPJSONResponse(w, http.StatusOK, user)
|
|
}
|
|
```
|
|
|
|
## Notas
|
|
|
|
Usa json.NewEncoder para streaming directo al ResponseWriter sin buffer intermedio. El header Content-Type debe setearse antes de WriteHeader. Errores de serializacion se propagan parcialmente al body — asegurarse de pasar tipos serializable a JSON.
|