Skip to content

Instantly share code, notes, and snippets.

@rahul-yr
Created May 26, 2022 07:39
Show Gist options
  • Save rahul-yr/8bb08d99d6358f814793efe8806280f8 to your computer and use it in GitHub Desktop.
Save rahul-yr/8bb08d99d6358f814793efe8806280f8 to your computer and use it in GitHub Desktop.
Go HTTP chain middlewares
package main
import (
"fmt"
"log"
"net/http"
"time"
)
type CustomMiddlewares func(http.HandlerFunc) http.HandlerFunc
func ChainMiddlewares(next http.HandlerFunc, middlewares ...CustomMiddlewares) http.HandlerFunc {
// iterate the middlewares from last to first
// to retain the order of middlewares
for i := len(middlewares) - 1; i >= 0; i-- {
next = middlewares[i](next)
}
return next
}
func LoggerMiddleware(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// log the request
log.Printf("Request[%s %s %s]", r.RemoteAddr, r.Method, r.URL)
next.ServeHTTP(w, r)
end := time.Now()
// log the response
log.Printf("Response[%s %s %s %s]", r.RemoteAddr, r.Method, r.URL, end.Sub(start))
})
}
func ping(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("pong"))
}
func main() {
port := ":8085"
host := fmt.Sprintf("localhost%s", port)
// create a new server
mux := http.NewServeMux()
//handlers
mux.HandleFunc("/pings", ChainMiddlewares(ping))
mux.HandleFunc("/ping", ChainMiddlewares(ping, LoggerMiddleware))
// start server
log.Printf("Listening on %s", port)
log.Fatal(http.ListenAndServe(host, mux))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment