Skip to content

Instantly share code, notes, and snippets.

@zeroidentidad
Created May 28, 2024 01:06
Show Gist options
  • Save zeroidentidad/535d6c952282f3afcca0d12f9c351f16 to your computer and use it in GitHub Desktop.
Save zeroidentidad/535d6c952282f3afcca0d12f9c351f16 to your computer and use it in GitHub Desktop.
ejemplos basicos web middlewares
package http
import (
"context"
"log"
"net/http"
"time"
)
func JsonMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
next.ServeHTTP(w, r)
})
}
func LogMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("method:", r.Method, "|", "path:", r.URL.Path, "| handled request")
next.ServeHTTP(w, r)
})
}
func TimeoutMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment