Tuesday, April 22, 2025
HomeGolangSluggish middlewares - Getting Assist

Sluggish middlewares – Getting Assist


Hello,

This easy middleware consumes lots of assets and I used to be questioning if there may be any method to enhance it so it’s quicker and makes use of much less allocations. That is simply an instance although as a result of all middlewares are huge bottlenecks in Go.

I vaguely bear in mind studying one thing about http.Request being rebuilt every time which was deemed to be the foundation trigger however undecided what precisely it was. Perhaps somebody is aware of.

Thanks

bundle foremost

import (
	"context"
	"web/http"
	"web/http/httptest"
	"testing"
)

kind key string

const (
	req key = "request-id"
	trc key = "trace-id"
)

func ID(subsequent http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var (
			rid = "some-request-id" // These get replaced with actual ones later
			tid = "some-trace-id"
			ctx = r.Context()
		)

		ctx = context.WithValue(ctx, req, rid)
		ctx = context.WithValue(ctx, trc, tid)

		subsequent.ServeHTTP(w, r.WithContext(ctx))
	}
}

func Benchmark_ID(b *testing.B) {
	handler := func(_ http.ResponseWriter, _ *http.Request) {}

	req := httptest.NewRequest(http.MethodGet, "https://discussion board.golangbridge.org/", nil)
	res := httptest.NewRecorder()

	middleware := ID(handler)

	for i := 0; i < b.N; i++ {
		middleware.ServeHTTP(res, req)
	}
}
$ go check -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

Whats up!
Your middleware in Go might be improved by reusing context values and minimizing pointless http.Request rebuilding. Replace your code to streamline these processes and doubtlessly enhance efficiency and scale back allocations. Benchmark after adjustments to confirm enhancements.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments