typestar

Middleware en Go

Un middleware toma un handler y devuelve otro que lo envuelve.

type recorder struct {
    http.ResponseWriter
    status int
}

func (r *recorder) WriteHeader(code int) {
    r.status = code
    r.ResponseWriter.WriteHeader(code)
}

func withLogging(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        started := time.Now()
        wrapped := &recorder{ResponseWriter: w, status: http.StatusOK}
        next.ServeHTTP(wrapped, r)
        slog.Info("request", "method", r.Method, "path", r.URL.Path,
            "status", wrapped.status, "took", time.Since(started))
    })
}

func chain(handler http.Handler) http.Handler {
    return withLogging(handler)
}

Cómo funciona

  1. La firma es func(http.Handler) http.Handler.
  2. Se componen anidando, con el más externo al final.
  3. Un envoltorio de respuesta es como capturas el código de estado.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
23
Caracteres a escribir
587
Tokens
153
Ritmo de tres estrellas
110 tpm

Al ritmo de tres estrellas de 110 tokens por minuto, este intento toma unos 83 segundos.

Escribe este fragmento

Paso 3 de 5 en HTTP; paso 18 de 26 en Biblioteca estándar y estructura del proyecto.

← Anterior Siguiente →

Middleware en otros lenguajes