Skip to content

Commit

Permalink
Adds middleware to insert X-Request-Start unix millis timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
AxelTheGerman committed Nov 24, 2024
1 parent 68df02c commit 8599b24
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
28 changes: 28 additions & 0 deletions internal/server/request_start_middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package server

import (
"net/http"
"strconv"
"time"
)

const (
requestStartHeader = "X-Request-Start"
)

type RequestStartMiddleware struct {
next http.Handler
}

func WithRequestStartMiddleware(next http.Handler) http.Handler {
return &RequestStartMiddleware{
next: next,
}
}

func (h *RequestStartMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Header.Get(requestStartHeader) == "" {
r.Header.Set(requestStartHeader, strconv.FormatInt(time.Now().UnixMilli(), 10))
}
h.next.ServeHTTP(w, r)
}
38 changes: 38 additions & 0 deletions internal/server/request_start_middleware_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package server

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

"github.com/stretchr/testify/assert"
)

func TestRequestStartMiddleware_AddsUnixMilliWhenNotPresent(t *testing.T) {
handler := WithRequestStartMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
timestamp := r.Header.Get(requestStartHeader)
assert.NotEmpty(t, timestamp)
}))

r := httptest.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)

assert.Equal(t, http.StatusOK, w.Code)
}

func TestRequestStartMiddleware_PreservesExistingHeaderWhenPresent(t *testing.T) {
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
timestamp := r.Header.Get(requestStartHeader)
assert.Equal(t, "1234", timestamp)
})
handler := WithRequestStartMiddleware(next)

r := httptest.NewRequest("GET", "/", nil)
r.Header.Set(requestStartHeader, "1234")

w := httptest.NewRecorder()
handler.ServeHTTP(w, r)

assert.Equal(t, http.StatusOK, w.Code)
}
2 changes: 2 additions & 0 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,12 @@ func (s *Server) startCommandHandler() error {
func (s *Server) buildHandler() http.Handler {
var handler http.Handler

// Note: handlers are executed in the inverse order.
handler = s.router
handler, _ = WithErrorPageMiddleware(pages.DefaultErrorPages, true, handler)
handler = WithLoggingMiddleware(slog.Default(), s.config.HttpPort, s.config.HttpsPort, handler)
handler = WithRequestIDMiddleware(handler)
handler = WithRequestStartMiddleware(handler)

return handler
}

0 comments on commit 8599b24

Please sign in to comment.