Created
May 17, 2022 14:39
-
-
Save kittipat1413/8fb182660b42f62a5b405f4413134020 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 main | |
| import ( | |
| "encoding/json" | |
| "fmt" | |
| "net/http" | |
| ) | |
| type Middleware func(http.Handler) http.Handler | |
| func NewHandler(middlewares ...Middleware) func(http.HandlerFunc) http.HandlerFunc { | |
| return func(final http.HandlerFunc) http.HandlerFunc { | |
| handler := buildChain(handleFinal(final), middlewares...) | |
| return handler.ServeHTTP | |
| } | |
| } | |
| func buildChain(final http.HandlerFunc, middlewares ...Middleware) http.Handler { | |
| if len(middlewares) == 0 { | |
| return final | |
| } | |
| return middlewares[0](buildChain(final, middlewares[1:]...)) | |
| } | |
| func PrintMiddleware(word string) Middleware { | |
| return func(next http.Handler) http.Handler { | |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| fmt.Printf("%s %s %s \n", r.Method, r.URL.Path, word) | |
| next.ServeHTTP(w, r) | |
| }) | |
| } | |
| } | |
| func handleFinal(finalHandler http.HandlerFunc) http.HandlerFunc { | |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| finalHandler(w, r) | |
| }) | |
| } | |
| func healthCheck(w http.ResponseWriter, r *http.Request) { | |
| renderJson(w, r, map[string]string{"status": "OK"}) | |
| } | |
| func hello(w http.ResponseWriter, r *http.Request) { | |
| renderJson(w, r, map[string]string{"message": "hello"}) | |
| } | |
| func main() { | |
| router := http.NewServeMux() | |
| router.HandleFunc("/health", NewHandler( | |
| PrintMiddleware("health1"), | |
| PrintMiddleware("health2"), | |
| PrintMiddleware("health3"), | |
| )(healthCheck)) | |
| router.HandleFunc("/hello", NewHandler( | |
| PrintMiddleware("hello"), | |
| )(healthCheck)) | |
| http.ListenAndServe(":8090", router) | |
| } | |
| func renderJson(resp http.ResponseWriter, r *http.Request, obj interface{}) { | |
| resp.Header().Set("Content-Type", "application/json") | |
| resp.WriteHeader(200) | |
| if err := json.NewEncoder(resp).Encode(obj); err != nil { | |
| http.Error(resp, err.Error(), http.StatusInternalServerError) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment