Skip to content

Instantly share code, notes, and snippets.

@ehernandez-xk
Created May 15, 2017 14:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ehernandez-xk/f6a941582a3196266a15ad4665f43a60 to your computer and use it in GitHub Desktop.
Save ehernandez-xk/f6a941582a3196266a15ad4665f43a60 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