Skip to content

Commit

Permalink
Fixup all example with a automatic free port
Browse files Browse the repository at this point in the history
  • Loading branch information
instabledesign committed Oct 22, 2020
1 parent 8b44e88 commit d26a93f
Show file tree
Hide file tree
Showing 9 changed files with 130 additions and 77 deletions.
17 changes: 13 additions & 4 deletions middleware/correlation_id_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package middleware_test

import (
"fmt"
"log"
"math/rand"
"net"
"net/http"
"net/http/httptest"
"testing"
Expand Down Expand Up @@ -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(
Expand All @@ -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 {
Expand Down
22 changes: 14 additions & 8 deletions middleware/enable_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package middleware_test

import (
"fmt"
"log"
"net"
"net/http"
"net/http/httptest"
"testing"
Expand Down Expand Up @@ -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 {
Expand All @@ -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
Expand Down
19 changes: 14 additions & 5 deletions middleware/metrics_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package middleware_test

import (
"log"
"net"
"net/http"
"net/http/httptest"
"testing"
Expand Down Expand Up @@ -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)

Expand All @@ -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)
}
}()
Expand Down
22 changes: 15 additions & 7 deletions middleware/rate_limit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httptest"
"testing"
Expand Down Expand Up @@ -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
Expand Down
24 changes: 14 additions & 10 deletions middleware/skip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package middleware_test

import (
"fmt"
"net"
"net/http"
"net/http/httptest"
"testing"
Expand Down Expand Up @@ -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) {
Expand All @@ -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
Expand Down
22 changes: 14 additions & 8 deletions tripperware/correlation_id_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package tripperware_test
import (
"context"
"fmt"
"log"
"math/rand"
"net"
"net/http"
"net/http/httptest"
"os"
Expand Down Expand Up @@ -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{
Expand All @@ -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
}
22 changes: 14 additions & 8 deletions tripperware/enable_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package tripperware_test

import (
"fmt"
"log"
"net"
"net/http"
"net/http/httptest"
"testing"
Expand Down Expand Up @@ -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 {
Expand All @@ -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
Expand Down
Loading

0 comments on commit d26a93f

Please sign in to comment.