Skip to content

Instantly share code, notes, and snippets.

@hotafrika
Created November 9, 2022 11:52
Show Gist options
  • Save hotafrika/308ee60ba1928403bc918e3373d5b656 to your computer and use it in GitHub Desktop.
Save hotafrika/308ee60ba1928403bc918e3373d5b656 to your computer and use it in GitHub Desktop.
medium / chi rate limiter
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