Created
May 28, 2024 01:06
-
-
Save zeroidentidad/535d6c952282f3afcca0d12f9c351f16 to your computer and use it in GitHub Desktop.
ejemplos basicos web middlewares
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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