Skip to content

Instantly share code, notes, and snippets.

@Manzanit0
Created February 27, 2023 09:25
Show Gist options
  • Save Manzanit0/a00f5dd1408a7c7f809b9a1eec3869d7 to your computer and use it in GitHub Desktop.
Save Manzanit0/a00f5dd1408a7c7f809b9a1eec3869d7 to your computer and use it in GitHub Desktop.
Go: Wrap HTTP mux
package main
import (
"fmt"
"log"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
func main() {
// People create their own thing, as they wish, with what ever lib.
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Get("/ping", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("pong"))
})
// And they pass it down to us so we "wrap" it.
fmt.Println("Starting server on 8080")
srv := NewHTTPServer(8080, r)
if err := srv.ListenAndServe(); err != nil {
log.Printf("server ended: %s", err.Error())
}
}
func NewHTTPServer(port int, mux http.Handler) *http.Server {
// Create a root mux where we will add all the stuff we want to, such as the
// health endpoints.
rootMux := http.NewServeMux()
rootMux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
})
// We apply all the middlewares we want to the provided router.
rootMux.Handle("/", exampleMiddleware(mux))
// Return the server.
return &http.Server{Addr: fmt.Sprintf(":%d", port), Handler: rootMux}
}
func exampleMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Running before handler")
_, _ = w.Write([]byte("Hijacking Request "))
next.ServeHTTP(w, r)
fmt.Println("Running after handler")
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment