github.com/gofiber/fiber/v2@v2.47.0/middleware/pprof/pprof.go (about) 1 package pprof 2 3 import ( 4 "net/http/pprof" 5 "strings" 6 7 "github.com/gofiber/fiber/v2" 8 9 "github.com/valyala/fasthttp/fasthttpadaptor" 10 ) 11 12 // New creates a new middleware handler 13 func New(config ...Config) fiber.Handler { 14 // Set default config 15 cfg := configDefault(config...) 16 17 // Set pprof adaptors 18 var ( 19 pprofIndex = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Index) 20 pprofCmdline = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Cmdline) 21 pprofProfile = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Profile) 22 pprofSymbol = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Symbol) 23 pprofTrace = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Trace) 24 pprofAllocs = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Handler("allocs").ServeHTTP) 25 pprofBlock = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Handler("block").ServeHTTP) 26 pprofGoroutine = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Handler("goroutine").ServeHTTP) 27 pprofHeap = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Handler("heap").ServeHTTP) 28 pprofMutex = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Handler("mutex").ServeHTTP) 29 pprofThreadcreate = fasthttpadaptor.NewFastHTTPHandlerFunc(pprof.Handler("threadcreate").ServeHTTP) 30 ) 31 32 // Return new handler 33 return func(c *fiber.Ctx) error { 34 // Don't execute middleware if Next returns true 35 if cfg.Next != nil && cfg.Next(c) { 36 return c.Next() 37 } 38 39 path := c.Path() 40 // We are only interested in /debug/pprof routes 41 if len(path) < 12 || !strings.HasPrefix(path, cfg.Prefix+"/debug/pprof") { 42 return c.Next() 43 } 44 // Switch to original path without stripped slashes 45 switch path { 46 case cfg.Prefix + "/debug/pprof/": 47 pprofIndex(c.Context()) 48 case cfg.Prefix + "/debug/pprof/cmdline": 49 pprofCmdline(c.Context()) 50 case cfg.Prefix + "/debug/pprof/profile": 51 pprofProfile(c.Context()) 52 case cfg.Prefix + "/debug/pprof/symbol": 53 pprofSymbol(c.Context()) 54 case cfg.Prefix + "/debug/pprof/trace": 55 pprofTrace(c.Context()) 56 case cfg.Prefix + "/debug/pprof/allocs": 57 pprofAllocs(c.Context()) 58 case cfg.Prefix + "/debug/pprof/block": 59 pprofBlock(c.Context()) 60 case cfg.Prefix + "/debug/pprof/goroutine": 61 pprofGoroutine(c.Context()) 62 case cfg.Prefix + "/debug/pprof/heap": 63 pprofHeap(c.Context()) 64 case cfg.Prefix + "/debug/pprof/mutex": 65 pprofMutex(c.Context()) 66 case cfg.Prefix + "/debug/pprof/threadcreate": 67 pprofThreadcreate(c.Context()) 68 default: 69 // pprof index only works with trailing slash 70 if strings.HasSuffix(path, "/") { 71 path = strings.TrimRight(path, "/") 72 } else { 73 path = cfg.Prefix + "/debug/pprof/" 74 } 75 76 return c.Redirect(path, fiber.StatusFound) 77 } 78 return nil 79 } 80 }