Skip to content

Commit

Permalink
feat: use uuids for request ids to guarantee uniqueness
Browse files Browse the repository at this point in the history
  • Loading branch information
bhearsum committed Jul 15, 2024
1 parent aa94736 commit d89c79a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 6 deletions.
18 changes: 12 additions & 6 deletions middleware.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package main

import (
"math/rand"
"net/http"
"time"

"github.com/google/uuid"
)

// Middleware wraps an http.Handler with additional functionality
Expand All @@ -27,13 +28,18 @@ func setResponseHeaders() Middleware {
func setRequestID() Middleware {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rid := make([]rune, 16)
letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
for i := range rid {
rid[i] = letters[rand.Intn(len(letters))]
// NewV7 is used instead of New because the latter will panic
// if can't generate a UUID. It's preferably for us to have
// worse request ids than panic.
uuid, err := uuid.NewV7()
var rid string
if err != nil {
rid = "-"
} else {
rid = uuid.String()
}

h.ServeHTTP(w, addToContext(r, contextKeyRequestID, string(rid)))
h.ServeHTTP(w, addToContext(r, contextKeyRequestID, rid))
})
}
}
Expand Down
30 changes: 30 additions & 0 deletions middleware_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

package main

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

"github.com/google/uuid"
)

func TestRequestIDWellFormed(t *testing.T) {
// This method of testing middleware is cribbed from
// https://stackoverflow.com/questions/51201056/testing-golang-middleware-that-modifies-the-request
nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
val := r.Context().Value(contextKeyRequestID).(string)
if uuid.Validate(val) != nil {
t.Errorf("requestID is not a valid uuid! %v", val)
}
})

handlerToTest := setRequestID()(nextHandler)

req := httptest.NewRequest("GET", "http://foo.bar/", nil)

handlerToTest.ServeHTTP(httptest.NewRecorder(), req)
}

0 comments on commit d89c79a

Please sign in to comment.