Created
August 4, 2021 02:42
-
-
Save madflojo/4b5a3752c22f4c8699fd454e7734ded0 to your computer and use it in GitHub Desktop.
httprouter Article - Registering PProf Index
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 ( | |
"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))) | |
// 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