Created
November 9, 2022 11:52
-
-
Save hotafrika/308ee60ba1928403bc918e3373d5b656 to your computer and use it in GitHub Desktop.
medium / chi rate limiter
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
func main() { | |
router := chi.NewRouter() | |
router.Get("/info", infoHandler) | |
router.Group(func(router chi.Router) { | |
router.Use(authMiddleware) | |
router.Get("/profile", profileHandler) | |
router.Get("/stat", statHandler) | |
}) | |
http.ListenAndServe(":8080", router) | |
} | |
func infoHandler(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte("info.")) | |
} | |
func profileHandler(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte("profile.")) | |
} | |
func statHandler(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte("stat.")) | |
} | |
func authMiddleware(next http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
userID := r.Header.Get("UserID") | |
if userID == "" { | |
w.WriteHeader(http.StatusUnauthorized) | |
w.Write([]byte("unauthorized")) | |
return | |
} | |
ctx := context.WithValue(r.Context(), "userID", userID) | |
r = r.WithContext(ctx) | |
next.ServeHTTP(w, r) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment