Skip to content

Instantly share code, notes, and snippets.

@tigerwill90
Created November 26, 2024 10:41
Show Gist options
  • Select an option

  • Save tigerwill90/b4bf1e42c808ad4e6addde3a8e4f41b4 to your computer and use it in GitHub Desktop.

Select an option

Save tigerwill90/b4bf1e42c808ad4e6addde3a8e4f41b4 to your computer and use it in GitHub Desktop.
package mux
import (
"crypto/rand"
"math/big"
"net/http"
"net/http/httptest"
"testing"
)
// BenchmarkMux-16 4161063 246.0 ns/op 16 B/op 1 allocs/op
func BenchmarkMux(b *testing.B) {
mux := http.NewServeMux()
mux.Handle("GET /users/{id}/orders", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
req := httptest.NewRequest(http.MethodGet, "/users/12345/orders", nil)
w := httptest.NewRecorder()
b.ReportAllocs()
b.ResetTimer()
for range b.N {
mux.ServeHTTP(w, req)
}
}
// BenchmarkMuxAdversarialPath-16 151 7941070 ns/op 16 B/op 1 allocs/op
func BenchmarkMuxAdversarialPath(b *testing.B) {
mux := http.NewServeMux()
mux.Handle("GET /users/{id}/orders", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
target := "/users/" + GenerateRandomString(b, http.DefaultMaxHeaderBytes) + "/orders"
req := httptest.NewRequest(http.MethodGet, target, nil)
w := httptest.NewRecorder()
b.ReportAllocs()
b.ResetTimer()
for range b.N {
mux.ServeHTTP(w, req)
}
}
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
func GenerateRandomString(tb testing.TB, n int) string {
tb.Helper()
if n <= 0 {
return ""
}
result := make([]byte, n)
for i := range result {
index, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
if err != nil {
tb.Fatal(err)
}
result[i] = charset[index.Int64()]
}
return string(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment