Files
egutierrez b074313c01 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>
2026-04-13 01:57:47 +02:00

38 lines
897 B
Go

package infra
import (
"context"
"fmt"
"net/http"
"time"
)
// HTTPServe arranca un servidor HTTP en addr y realiza graceful shutdown cuando ctx se cancela.
// Espera hasta 30 segundos para que las conexiones activas cierren antes de forzar el shutdown.
func HTTPServe(addr string, handler http.Handler, ctx context.Context) error {
srv := &http.Server{
Addr: addr,
Handler: handler,
}
errCh := make(chan error, 1)
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
errCh <- fmt.Errorf("http serve %s: %w", addr, err)
}
close(errCh)
}()
select {
case err := <-errCh:
return err
case <-ctx.Done():
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
return fmt.Errorf("http shutdown %s: %w", addr, err)
}
return nil
}
}