Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement transport.If() for conditional transports (e.g. for debugging) #8

Merged
merged 2 commits into from
Aug 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ There are multiple use-cases where this pattern comes handy such as request logg

## Examples

Set up HTTP client, which sets `User-Agent`, `Authorization` and `TraceID` headers automatically :
Set up HTTP client, which sets `User-Agent`, `Authorization` and `TraceID` headers automatically:
```go
authClient := http.Client{
Transport: transport.Chain(
Expand All @@ -22,12 +22,12 @@ authClient := http.Client{

Or debug all outgoing requests globally within your application:
```go
if debugMode {
http.DefaultTransport = transport.Chain(
http.DefaultTransport,
transport.LogRequests,
)
}
debugMode := os.Getenv("DEBUG") == "true"

http.DefaultTransport = transport.Chain(
http.DefaultTransport,
transport.If(debugMode, transport.LogRequests),
)
```

# Authors
Expand Down
21 changes: 21 additions & 0 deletions if.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package transport

import (
"net/http"
)

// If sets given transport if given condition is true. Otherwise it sets nil transport, which will be ignored.
//
// Example:
//
// http.DefaultTransport = transport.Chain(
// http.DefaultTransport,
// transport.If(debugMode, transport.LogRequests),
// )
func If(condition bool, transport func(http.RoundTripper) http.RoundTripper) func(http.RoundTripper) http.RoundTripper {
if condition {
return transport
}

return nil
}
79 changes: 79 additions & 0 deletions if_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package transport_test

import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/go-chi/transport"
)

func TestIfTrue(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("debug") != "true" {
t.Error("expected debug=true")
w.WriteHeader(500)
return
}

fmt.Fprintf(w, "ok")
}))
defer server.Close()

client := &http.Client{
Timeout: 15 * time.Second,
Transport: transport.Chain(
http.DefaultTransport,
transport.If(true, transport.SetHeader("debug", "true")), // Set header.
),
}

request, err := http.NewRequest("GET", server.URL, nil)
if err != nil {
t.Fatal(err)
}
resp, err := client.Do(request)
if err != nil {
t.Fatal(err)
}

if resp.StatusCode != 200 {
t.Fatal("unexpected response")
}
}

func TestIfFalse(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("debug") != "" {
t.Error("expected no debug header")
w.WriteHeader(500)
return
}

fmt.Fprintf(w, "ok")
}))
defer server.Close()

client := &http.Client{
Timeout: 15 * time.Second,
Transport: transport.Chain(
http.DefaultTransport,
transport.If(false, transport.SetHeader("debug", "true")), // Do not set header.
),
}

request, err := http.NewRequest("GET", server.URL, nil)
if err != nil {
t.Fatal(err)
}
resp, err := client.Do(request)
if err != nil {
t.Fatal(err)
}

if resp.StatusCode != 200 {
t.Fatal("unexpected response")
}
}
12 changes: 10 additions & 2 deletions transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,22 @@ func Chain(base http.RoundTripper, mw ...func(http.RoundTripper) http.RoundTripp
base = http.DefaultTransport
}

// Filter out nil transports.
mws := []func(http.RoundTripper) http.RoundTripper{}
for _, fn := range mw {
if fn != nil {
mws = append(mws, fn)
}
}

if c, ok := base.(*chain); ok {
c.middlewares = append(c.middlewares, mw...)
c.middlewares = append(c.middlewares, mws...)
return c
}

return &chain{
baseTransport: base,
middlewares: mw,
middlewares: mws,
}
}

Expand Down
1 change: 1 addition & 0 deletions transport_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ func TestChain(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("User-Agent") != "transport-chain/v1.0.0" {
w.WriteHeader(500)
return
}

fmt.Fprintf(w, expected)
Expand Down
Loading