Sobes.tech
Senior

¿Qué es middleware en los servidores HTTP de Go y cómo se implementa?

sobes.tech AI

Respuesta de la IA

El middleware en los servidores HTTP de Go es una función o conjunto de funciones que envuelven el manejador de solicitudes (http.Handler) para agregar lógica adicional, como registro, autenticación, manejo de errores, etc.

Se implementa como una función que recibe un http.Handler y devuelve un http.Handler. Ejemplo:

func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Printf("Request: %s %s", r.Method, r.URL.Path)
        next.ServeHTTP(w, r) // llama al siguiente manejador
    })
}

// Uso
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello"))
})

loggedMux := loggingMiddleware(mux)
http.ListenAndServe(":8080", loggedMux)

De esta forma, el middleware permite procesar las solicitudes de forma secuencial, añadiendo capas funcionales necesarias sin modificar el manejador principal.