Hi,
This simple middleware consumes a lot of resources and I was wondering if there is any way to improve it so it is faster and uses less allocations. This is just an example though because all middlewares are massive bottlenecks in Go.
I vaguely remember reading something about http.Request being rebuilt each time which was deemed to be the root cause but not sure what exactly it was. Maybe someone knows.
Thanks
package main
import (
"context"
"net/http"
"net/http/httptest"
"testing"
)
type key string
const (
req key = "request-id"
trc key = "trace-id"
)
func ID(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var (
rid = "some-request-id" // These be replaced with real ones later
tid = "some-trace-id"
ctx = r.Context()
)
ctx = context.WithValue(ctx, req, rid)
ctx = context.WithValue(ctx, trc, tid)
next.ServeHTTP(w, r.WithContext(ctx))
}
}
func Benchmark_ID(b *testing.B) {
handler := func(_ http.ResponseWriter, _ *http.Request) {}
req := httptest.NewRequest(http.MethodGet, "/", nil)
res := httptest.NewRecorder()
middleware := ID(handler)
for i := 0; i < b.N; i++ {
middleware.ServeHTTP(res, req)
}
}
$ go test -v -bench=. -benchmem mid_test.go
goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i5-5257U CPU @ 2.70GHz
Benchmark_ID
Benchmark_ID-4 3922474 284.3 ns/op 448 B/op 5 allocs/op