Skip to content

Instantly share code, notes, and snippets.

@jurabek
Forked from ehernandez-xk/handler.go
Created January 21, 2024 21:20
Show Gist options
  • Save jurabek/10a1f9632bca3370e92bde177f7928a1 to your computer and use it in GitHub Desktop.
Save jurabek/10a1f9632bca3370e92bde177f7928a1 to your computer and use it in GitHub Desktop.
http.HandlerFunc wrapper technique
//https://medium.com/@matryer/the-http-handler-wrapper-technique-in-golang-updated-bc7fbcffa702
//wraps the handler do do things before and/or after
func auth(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Before")
h.ServeHTTP(w, r)
fmt.Println("After")
})
}
//Checks for valid request otherwise retunr a error
func checkAPIKey(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if len(r.URL.Query().Get("key")) == 0 {
http.Error(w, "missing key", http.StatusNotFound)
return
}
h.ServeHTTP(w, r)
})
}
//Refering helps us to run even if the handler panics
func log(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("before")
defer fmt.Println("after")
h.ServeHTTP(w, r)
})
}
// To check a required paramentrs
func mustParams(h http.Handler, params ...string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
for _, param := range params {
if len(q.Get(param)) == 0 {
http.Error(w, "missing "+param, http.StatusBadRequest)
return // exit early
}
}
h.ServeHTTP(w, r) // all params present, proceed
})
}
/*
http.Handler("/user", MustParams(handleUser, "key", "auth"))
http.Handler("/group", MustParams(handleGroup, "key"))
http.Handler("/items", MustParams(handleSearch, "key", "q"))
*/
//check if the auth parameter is present
func mustAuth(h http.Handler) http.Handler {
checkauth := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := validateAuth(r.URL.Query().Get("auth"))
if err != nil {
http.Error(w, "bad auth param", http.StatusUnauthorized)
}
h.ServeHTTP(w, r)
})
return mustParams(checkauth, "auth")
}
func validateAuth(arg string) error {
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment