Skip to content

Instantly share code, notes, and snippets.

@madflojo
Created August 5, 2021 02:48
Show Gist options
  • Save madflojo/70425ab9ae0359086c405527585338be to your computer and use it in GitHub Desktop.
Save madflojo/70425ab9ae0359086c405527585338be to your computer and use it in GitHub Desktop.
httprouter Article - Middleware with PProf full
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"log"
"net/http"
"net/http/pprof"
)
// handler is a basic HTTP handler that prints hello world.
func handler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "Hello %s", ps.ByName("name"))
}
// middleware is used to intercept incoming HTTP calls and apply general functions upon them.
func middleware(n httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
log.Printf("HTTP request sent to %s from %s", r.URL.Path, r.RemoteAddr)
// call registered handler
n(w, r, ps)
}
}
// wrapper will wrap an http.Handler function with the middleware function.
func wrapper(h http.Handler) httprouter.Handle {
return middleware(func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
h.ServeHTTP(w, r)
})
}
func main() {
// Create Router
router := httprouter.New()
router.GET("/hello/:name", middleware(handler))
router.GET("/debug/pprof/", wrapper(http.HandlerFunc(pprof.Index)))
router.GET("/debug/pprof/cmdline", wrapper(http.HandlerFunc(pprof.Cmdline)))
router.GET("/debug/pprof/profile", wrapper(http.HandlerFunc(pprof.Profile)))
router.GET("/debug/pprof/symbol", wrapper(http.HandlerFunc(pprof.Symbol)))
router.GET("/debug/pprof/trace", wrapper(http.HandlerFunc(pprof.Trace)))
router.GET("/debug/pprof/allocs", wrapper(pprof.Handler("allocs")))
router.GET("/debug/pprof/mutex", wrapper(pprof.Handler("mutex")))
router.GET("/debug/pprof/goroutine", wrapper(pprof.Handler("goroutine")))
router.GET("/debug/pprof/heap", wrapper(pprof.Handler("heap")))
router.GET("/debug/pprof/threadcreate", wrapper(pprof.Handler("threadcreate")))
router.GET("/debug/pprof/block", wrapper(pprof.Handler("block")))
// Start HTTP Listener
err := http.ListenAndServe(":8080", router)
if err != nil {
log.Printf("HTTP Server stopped - %s", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment