diff --git a/middleware/correlation_id_test.go b/middleware/correlation_id_test.go index 0befd70..a90f9ea 100644 --- a/middleware/correlation_id_test.go +++ b/middleware/correlation_id_test.go @@ -2,7 +2,9 @@ package middleware_test import ( "fmt" + "log" "math/rand" + "net" "net/http" "net/http/httptest" "testing" @@ -44,7 +46,12 @@ func TestCorrelationId(t *testing.T) { // ===================================================================================================================== func ExampleCorrelationId() { - port := ":9103" + // Example Need a random ephemeral port (to have a free port) + ln, err := net.Listen("tcp", ":0") + if err != nil { + log.Fatal(err) + } + // we recommend to use MiddlewareStack to simplify managing all wanted middlewares // caution middleware order matters stack := httpware.MiddlewareStack( @@ -56,14 +63,16 @@ func ExampleCorrelationId() { ), ) - srv := http.NewServeMux() + srv := &http.Server{ + Handler: stack.DecorateHandler(http.NewServeMux()), + } go func() { - if err := http.ListenAndServe(port, stack.DecorateHandler(srv)); err != nil { + if err := srv.Serve(ln); err != nil { panic(err) } }() - resp, err := http.Get("http://localhost" + port) + resp, err := http.Get("http://"+ln.Addr().String()) if err != nil { fmt.Println(err) } else if resp != nil { diff --git a/middleware/enable_test.go b/middleware/enable_test.go index ba5b527..f126aca 100644 --- a/middleware/enable_test.go +++ b/middleware/enable_test.go @@ -2,6 +2,8 @@ package middleware_test import ( "fmt" + "log" + "net" "net/http" "net/http/httptest" "testing" @@ -57,7 +59,11 @@ func TestEnable(t *testing.T) { // ===================================================================================================================== func ExampleEnable() { - port := ":9104" + // Example Need a random ephemeral port (to have a free port) + ln, err := net.Listen("tcp", ":0") + if err != nil { + log.Fatal(err) + } enableDummyMiddleware := true // or false dummyMiddleware := func(next http.Handler) http.Handler { @@ -71,18 +77,18 @@ func ExampleEnable() { ) // create a server in order to show it work - srv := http.NewServeMux() - srv.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { - fmt.Println("server receive request with request:", request.Header.Get("FakeHeader")) - }) - + srv := &http.Server{ + Handler: stack.DecorateHandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + fmt.Println("server receive request with request:", request.Header.Get("FakeHeader")) + }), + } go func() { - if err := http.ListenAndServe(port, stack.DecorateHandler(srv)); err != nil { + if err := srv.Serve(ln); err != nil { panic(err) } }() - _, _ = http.Get("http://localhost" + port + "/") + _, _ = http.Get("http://" + ln.Addr().String()) // Output: //server receive request with request: this header is set when not /home url diff --git a/middleware/metrics_test.go b/middleware/metrics_test.go index 80c9e70..5be29c1 100644 --- a/middleware/metrics_test.go +++ b/middleware/metrics_test.go @@ -1,6 +1,8 @@ package middleware_test import ( + "log" + "net" "net/http" "net/http/httptest" "testing" @@ -61,7 +63,11 @@ func TestMetrics(t *testing.T) { // ===================================================================================================================== func ExampleMetrics() { - port := ":9101" + // Example Need a random ephemeral port (to have a free port) + ln, err := net.Listen("tcp", ":0") + if err != nil { + log.Fatal(err) + } recorder := prom.NewRecorder(prom.Config{}).RegisterOn(nil) @@ -73,11 +79,14 @@ func ExampleMetrics() { })), ) - srv := http.NewServeMux() - srv.Handle("/metrics", promhttp.Handler()) - + // create a server in order to show it work + mux := http.NewServeMux() + mux.Handle("/metrics", stack.DecorateHandler(promhttp.Handler())) + srv := &http.Server{ + Handler: mux, + } go func() { - if err := http.ListenAndServe(port, stack.DecorateHandler(srv)); err != nil { + if err := srv.Serve(ln); err != nil { panic(err) } }() diff --git a/middleware/rate_limit_test.go b/middleware/rate_limit_test.go index 8edb44d..0ebcccb 100644 --- a/middleware/rate_limit_test.go +++ b/middleware/rate_limit_test.go @@ -4,6 +4,8 @@ import ( "errors" "fmt" "io/ioutil" + "log" + "net" "net/http" "net/http/httptest" "testing" @@ -46,32 +48,38 @@ func TestRateLimit(t *testing.T) { // ===================================================================================================================== func ExampleRateLimit() { + // Example Need a random ephemeral port (to have a free port) + ln, err := net.Listen("tcp", ":0") + if err != nil { + log.Fatal(err) + } + limiter := rate_limit.NewTokenBucket(1*time.Second, 1) defer limiter.Stop() - port := ":9105" // we recommend to use MiddlewareStack to simplify managing all wanted middlewares // caution middleware order matters stack := httpware.MiddlewareStack( middleware.RateLimit(limiter), ) - srv := http.NewServeMux() - srv.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {}) + srv := &http.Server{ + Handler: stack.DecorateHandlerFunc(func(writer http.ResponseWriter, request *http.Request) {}), + } go func() { - if err := http.ListenAndServe(port, stack.DecorateHandler(srv)); err != nil { + if err := srv.Serve(ln); err != nil { panic(err) } }() - resp, _ := http.Get("http://localhost" + port) + resp, _ := http.Get("http://" + ln.Addr().String()) fmt.Println(resp.StatusCode) - resp, _ = http.Get("http://localhost" + port) + resp, _ = http.Get("http://" + ln.Addr().String()) fmt.Println(resp.StatusCode) time.Sleep(2 * time.Second) - resp, _ = http.Get("http://localhost" + port) + resp, _ = http.Get("http://" + ln.Addr().String()) fmt.Println(resp.StatusCode) // Output: //200 diff --git a/middleware/skip_test.go b/middleware/skip_test.go index ba52305..c5bc70b 100644 --- a/middleware/skip_test.go +++ b/middleware/skip_test.go @@ -2,6 +2,7 @@ package middleware_test import ( "fmt" + "net" "net/http" "net/http/httptest" "testing" @@ -59,7 +60,11 @@ func TestSkip(t *testing.T) { // ===================================================================================================================== func ExampleSkip() { - port := ":9102" + // Example Need a random ephemeral port (to have a free port) + ln, err := net.Listen("tcp", ":0") + if err != nil { + panic(err) + } dummyMiddleware := func(next http.Handler) http.Handler { return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { @@ -73,20 +78,19 @@ func ExampleSkip() { }, dummyMiddleware), ) - // create a server in order to show it work - srv := http.NewServeMux() - srv.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { - fmt.Printf("server receive request %s with request: %s\n", request.URL.Path, request.Header.Get("FakeHeader")) - }) - + srv := &http.Server{ + Handler: stack.DecorateHandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + fmt.Printf("server receive request %s with request: %s\n", request.URL.Path, request.Header.Get("FakeHeader")) + }), + } go func() { - if err := http.ListenAndServe(port, stack.DecorateHandler(srv)); err != nil { + if err := srv.Serve(ln); err != nil { panic(err) } }() - _, _ = http.Get("http://localhost" + port + "/") - _, _ = http.Get("http://localhost" + port + "/home") + _, _ = http.Get("http://" + ln.Addr().String()) + _, _ = http.Get("http://" + ln.Addr().String() + "/home") // Output: //server receive request / with request: this header is set when not /home url diff --git a/tripperware/correlation_id_test.go b/tripperware/correlation_id_test.go index 1eac2d6..5250cfd 100644 --- a/tripperware/correlation_id_test.go +++ b/tripperware/correlation_id_test.go @@ -3,7 +3,9 @@ package tripperware_test import ( "context" "fmt" + "log" "math/rand" + "net" "net/http" "net/http/httptest" "os" @@ -97,7 +99,11 @@ func TestCorrelationIdCustom(t *testing.T) { // ===================================================================================================================== func ExampleCorrelationId() { - port := ":9001" + // Example Need a random ephemeral port (to have a free port) + ln, err := net.Listen("tcp", ":0") + if err != nil { + log.Fatal(err) + } // create http client using the tripperwareStack as RoundTripper client := http.Client{ @@ -110,18 +116,18 @@ func ExampleCorrelationId() { } // create a server in order to show it work - srv := http.NewServeMux() - srv.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { - fmt.Println("server receive request with request id:", request.Header.Get("my-personal-header-name")) - }) - + srv := &http.Server{ + Handler: http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + fmt.Println("server receive request with request id:", request.Header.Get("my-personal-header-name")) + }), + } go func() { - if err := http.ListenAndServe(port, srv); err != nil { + if err := srv.Serve(ln); err != nil { panic(err) } }() - _, _ = client.Get("http://localhost" + port + "/") + _, _ = client.Get("http://" + ln.Addr().String()) // Output: server receive request with request id: my-fixed-request-id } diff --git a/tripperware/enable_test.go b/tripperware/enable_test.go index 95f259b..5cfc071 100644 --- a/tripperware/enable_test.go +++ b/tripperware/enable_test.go @@ -2,6 +2,8 @@ package tripperware_test import ( "fmt" + "log" + "net" "net/http" "net/http/httptest" "testing" @@ -61,7 +63,11 @@ func TestEnable(t *testing.T) { // ===================================================================================================================== func ExampleEnable() { - port := ":9003" + // Example Need a random ephemeral port (to have a free port) + ln, err := net.Listen("tcp", ":0") + if err != nil { + log.Fatal(err) + } enableDummyTripperware := true //false dummyTripperware := func(next http.RoundTripper) http.RoundTripper { @@ -77,18 +83,18 @@ func ExampleEnable() { } // create a server in order to show it work - srv := http.NewServeMux() - srv.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { - fmt.Println("server receive request with request:", request.Header.Get("FakeHeader")) - }) - + srv := &http.Server{ + Handler: http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + fmt.Println("server receive request with request:", request.Header.Get("FakeHeader")) + }), + } go func() { - if err := http.ListenAndServe(port, srv); err != nil { + if err := srv.Serve(ln); err != nil { panic(err) } }() - _, _ = client.Get("http://localhost" + port + "/") + _, _ = client.Get("http://" + ln.Addr().String()) // Output: //server receive request with request: this header is set when not /home url diff --git a/tripperware/rate_limit_test.go b/tripperware/rate_limit_test.go index d808574..ee46784 100644 --- a/tripperware/rate_limit_test.go +++ b/tripperware/rate_limit_test.go @@ -20,8 +20,8 @@ func TestRateLimit(t *testing.T) { roundTripperMock := &mocks.RoundTripper{} request := httptest.NewRequest(http.MethodGet, "http://fake-addr", nil) resp := &http.Response{ - Status: "OK", - StatusCode: http.StatusOK, + Status: "OK", + StatusCode: http.StatusOK, } roundTripperMock.On("RoundTrip", request).Times(2).Return(resp, nil) @@ -81,7 +81,7 @@ func TestConfig_Options(t *testing.T) { res, err := config.ErrorCallback(nil, nil) assert.Nil(t, res) assert.NotNil(t, err) - assert.Equal(t, "error from callback",err.Error()) + assert.Equal(t, "error from callback", err.Error()) } // ===================================================================================================================== @@ -89,35 +89,36 @@ func TestConfig_Options(t *testing.T) { // ===================================================================================================================== func ExampleRateLimit() { - rl := rate_limit.NewTokenBucket(1*time.Second, 1) - defer rl.Stop() - - client := http.Client{Transport: tripperware.RateLimit(rl)} - listener, err := net.Listen("tcp", ":0") + // Example Need a random ephemeral port (to have a free port) + ln, err := net.Listen("tcp", ":0") if err != nil { panic(err) } - addr := listener.Addr().String() - srv := http.NewServeMux() - srv.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { - fmt.Println("server receive request") - }) + rl := rate_limit.NewTokenBucket(1*time.Second, 1) + defer rl.Stop() + + client := http.Client{Transport: tripperware.RateLimit(rl)} + srv := &http.Server{ + Handler: http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + fmt.Println("server receive request") + }), + } go func() { - if err := http.Serve(listener, srv); err != nil { + if err := srv.Serve(ln); err != nil { panic(err) } }() - _, err = client.Get("http://" + addr + "/") + _, err = client.Get("http://" + ln.Addr().String()) fmt.Println(err) - _, err = client.Get("http://" + addr + "/") + _, err = client.Get("http://" + ln.Addr().String()) fmt.Println(errors.Unwrap(err)) time.Sleep(2 * time.Second) - _, err = client.Get("http://" + addr + "/") + _, err = client.Get("http://" + ln.Addr().String()) fmt.Println(err) // Output: //server receive request diff --git a/tripperware/skip_test.go b/tripperware/skip_test.go index feae214..2248bfa 100644 --- a/tripperware/skip_test.go +++ b/tripperware/skip_test.go @@ -2,6 +2,7 @@ package tripperware_test import ( "fmt" + "net" "net/http" "net/http/httptest" "testing" @@ -63,7 +64,11 @@ func TestSkip(t *testing.T) { // ===================================================================================================================== func ExampleSkip() { - port := ":9002" + // Example Need a random ephemeral port (to have a free port) + ln, err := net.Listen("tcp", ":0") + if err != nil { + panic(err) + } dummyTripperware := func(next http.RoundTripper) http.RoundTripper { return httpware.RoundTripFunc(func(request *http.Request) (*http.Response, error) { @@ -79,20 +84,19 @@ func ExampleSkip() { }, dummyTripperware), } - // create a server in order to show it work - srv := http.NewServeMux() - srv.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { - fmt.Println("server receive request with request:", request.Header.Get("FakeHeader")) - }) - + srv := &http.Server{ + Handler: http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + fmt.Println("server receive request with request:", request.Header.Get("FakeHeader")) + }), + } go func() { - if err := http.ListenAndServe(port, srv); err != nil { + if err := srv.Serve(ln); err != nil { panic(err) } }() - _, _ = client.Get("http://localhost" + port + "/") - _, _ = client.Get("http://localhost" + port + "/home") + _, _ = client.Get("http://" + ln.Addr().String()) + _, _ = client.Get("http://" + ln.Addr().String() + "/home") // Output: //server receive request with request: this header is set when not /home url