Skip to content

Commit

Permalink
fixup! feat(requestid): add helper package
Browse files Browse the repository at this point in the history
  • Loading branch information
olexsmir committed Sep 19, 2024
1 parent 71a54c2 commit 97e6886
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
49 changes: 49 additions & 0 deletions internal/transport/http/reqid/reqid.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// reqid provides gin-gonic/gin middleware to generate a requestid for each request
package reqid

import (
"context"

"github.com/gin-gonic/gin"
"github.com/google/uuid"
)

type RequestIDKey string

const (
RequestID RequestIDKey = "request_id"

headerRequestID = "X-Request-ID"
)

// Middleware initializes the request ID
func Middleware() gin.HandlerFunc {
return func(c *gin.Context) {
rid := c.GetHeader(headerRequestID)
if rid == "" {
rid = uuid.New().String()
c.Request.Header.Add(headerRequestID, rid)
}

// set reqeust ID request context
ctx := context.WithValue(c.Request.Context(), RequestID, rid)
c.Request = c.Request.WithContext(ctx)

// ensures that the request ID is in the response
c.Header(headerRequestID, rid)
c.Next()
}
}

// Get returns the request ID
func Get(c *gin.Context) string {
return c.GetHeader(headerRequestID)
}

func GetFromContext(ctx context.Context) string {
rid, ok := ctx.Value(RequestID).(string)
if !ok {
return ""
}
return rid
}
35 changes: 35 additions & 0 deletions internal/transport/http/reqid/reqid_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package reqid

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

//nolint:gochecknoinits
func init() {
gin.SetMode(gin.TestMode)
}

func testHandler(c *gin.Context) {
c.Status(http.StatusOK)
}

func TestMiddleware(t *testing.T) {
r := gin.New()
r.Use(Middleware())
r.GET("/", testHandler)

w := httptest.NewRecorder()
req, err := http.NewRequest(http.MethodGet, "/", nil)
require.NoError(t, err)

r.ServeHTTP(w, req)

assert.Equal(t, http.StatusOK, w.Code)
assert.NotEmpty(t, w.Header().Get(headerRequestID))
}

0 comments on commit 97e6886

Please sign in to comment.