Skip to content

Commit

Permalink
Add support for profilling endpoints (#774)
Browse files Browse the repository at this point in the history
  • Loading branch information
Umang01-hash authored Jul 1, 2024
1 parent 1b56119 commit 0f20b19
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
6 changes: 5 additions & 1 deletion pkg/gofr/gofr.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions pkg/gofr/httpServer.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gofr
import (
"fmt"
"net/http"
"net/http/pprof"
"time"

"gofr.dev/pkg/gofr/container"
Expand Down Expand Up @@ -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

Expand Down
34 changes: 34 additions & 0 deletions pkg/gofr/httpServer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package gofr
import (
"context"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"

Expand Down Expand Up @@ -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)
}
}

0 comments on commit 0f20b19

Please sign in to comment.