From 0f20b19f10fda85d8d7f254d11bdce478f04b6da Mon Sep 17 00:00:00 2001 From: Umang Mundhra Date: Mon, 1 Jul 2024 17:14:34 +0530 Subject: [PATCH] Add support for profilling endpoints (#774) --- pkg/gofr/gofr.go | 6 +++++- pkg/gofr/httpServer.go | 10 ++++++++++ pkg/gofr/httpServer_test.go | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) diff --git a/pkg/gofr/gofr.go b/pkg/gofr/gofr.go index 90066cf6b..b87f28b3b 100644 --- a/pkg/gofr/gofr.go +++ b/pkg/gofr/gofr.go @@ -85,7 +85,11 @@ func New() *App { app.httpServer = newHTTPServer(app.container, port, middleware.GetConfigs(app.Config)) - // GRPC Server + if app.Config.Get("APP_ENV") == "DEBUG" { + app.httpServer.RegisterProfilingRoutes() + } + + // gRPC Server port, err = strconv.Atoi(app.Config.Get("GRPC_PORT")) if err != nil || port <= 0 { port = defaultGRPCPort diff --git a/pkg/gofr/httpServer.go b/pkg/gofr/httpServer.go index 99742bdc3..90123cd36 100644 --- a/pkg/gofr/httpServer.go +++ b/pkg/gofr/httpServer.go @@ -3,6 +3,7 @@ package gofr import ( "fmt" "net/http" + "net/http/pprof" "time" "gofr.dev/pkg/gofr/container" @@ -36,6 +37,15 @@ func newHTTPServer(c *container.Container, port int, middlewareConfigs map[strin } } +func (s *httpServer) RegisterProfilingRoutes() { + s.router.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline) + s.router.HandleFunc("/debug/pprof/profile", pprof.Profile) + s.router.HandleFunc("/debug/pprof/symbol", pprof.Symbol) + s.router.HandleFunc("/debug/pprof/trace", pprof.Trace) + + s.router.NewRoute().Methods(http.MethodGet).PathPrefix("/debug/pprof/").HandlerFunc(pprof.Index) +} + func (s *httpServer) Run(c *container.Container) { var srv *http.Server diff --git a/pkg/gofr/httpServer_test.go b/pkg/gofr/httpServer_test.go index c3b7819a7..bbb80ad32 100644 --- a/pkg/gofr/httpServer_test.go +++ b/pkg/gofr/httpServer_test.go @@ -3,6 +3,8 @@ package gofr import ( "context" "net/http" + "net/http/httptest" + "strconv" "testing" "time" @@ -51,3 +53,35 @@ func TestRun_ServerStartsListening(t *testing.T) { resp.Body.Close() } + +func TestRegisterProfillingRoutes(t *testing.T) { + c := &container.Container{ + Logger: logging.NewLogger(logging.INFO), + } + + server := &httpServer{ + router: gofrHTTP.NewRouter(), + port: 8080, + } + + server.RegisterProfilingRoutes() + + server.Run(c) + + // Test if the expected handlers are registered for the pprof endpoints + expectedRoutes := []string{ + "/debug/pprof/", + "/debug/pprof/cmdline", + "/debug/pprof/symbol", + } + + serverURL := "http://localhost:" + strconv.Itoa(8000) + + for _, route := range expectedRoutes { + r := httptest.NewRequest(http.MethodGet, serverURL+route, http.NoBody) + rr := httptest.NewRecorder() + server.router.ServeHTTP(rr, r) + + assert.Equal(t, http.StatusOK, rr.Code) + } +}