feat: funciones impuras HTTP — response, parse, logger, router, serve
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>
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
---
|
||||
name: http_error_response
|
||||
kind: function
|
||||
lang: go
|
||||
domain: infra
|
||||
version: "1.0.0"
|
||||
purity: impure
|
||||
signature: "func HTTPErrorResponse(w http.ResponseWriter, err HTTPError)"
|
||||
description: "Escribe un HTTPError como JSON en el ResponseWriter. Usa err.Status como status code HTTP y serializa los campos Code y Message en el body."
|
||||
tags: [http, error, response, json, server, infra]
|
||||
uses_functions: []
|
||||
uses_types: [HTTPError_go_infra]
|
||||
returns: []
|
||||
returns_optional: false
|
||||
error_type: "error_go_core"
|
||||
imports: [encoding/json, net/http]
|
||||
params:
|
||||
- name: w
|
||||
desc: "ResponseWriter donde se escribe la respuesta de error"
|
||||
- name: err
|
||||
desc: "HTTPError con Status (codigo HTTP), Code (identificador maquina) y Message (texto legible)"
|
||||
output: "escribe la respuesta de error JSON directamente en w, sin valor de retorno"
|
||||
tested: true
|
||||
tests: ["escribe el status code del HTTPError", "setea Content-Type application/json", "serializa Code y Message en el body JSON"]
|
||||
test_file_path: "functions/infra/http_server_test.go"
|
||||
file_path: "functions/infra/http_error_response.go"
|
||||
---
|
||||
|
||||
## Ejemplo
|
||||
|
||||
```go
|
||||
func createUser(w http.ResponseWriter, r *http.Request) {
|
||||
var user User
|
||||
if err := HTTPParseBody(r, &user, 1<<20); err != nil {
|
||||
HTTPErrorResponse(w, HTTPError{
|
||||
Status: http.StatusBadRequest,
|
||||
Code: "invalid_body",
|
||||
Message: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## Notas
|
||||
|
||||
Conveniente para APIs JSON que siempre retornan errores en formato estructurado. Se puede componer con HTTPParseBody: si el parse falla, llamar HTTPErrorResponse con 400. El body JSON tiene la forma `{"Status":400,"Code":"...","Message":"..."}`.
|
||||
Reference in New Issue
Block a user