Skip to content

Commit

Permalink
Add runtime checks to prevent wrong handling of constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
donutloop committed Jun 12, 2020
1 parent 117a06d commit 8351413
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
10 changes: 10 additions & 0 deletions xhttp/xhttp.go
@@ -1,18 +1,28 @@
package xhttp

import (
"errors"
"net/http"
)

type Middleware func(m http.RoundTripper) http.RoundTripper

// Use is wrapping up a RoundTripper with a set of middleware
func Use(client *http.Client, middlewares ...Middleware) *http.Client {
if client == nil {
panic(errors.New("client is nil"))
}
if len(middlewares) == 0 {
panic(errors.New("middlewares is nil"))
}
if client.Transport == nil {
client.Transport = http.DefaultTransport
}
current := client.Transport
for _, middleware := range middlewares {
if middleware == nil {
panic(errors.New("middleware is nil"))
}
current = middleware(current)
}
client.Transport = current
Expand Down
36 changes: 36 additions & 0 deletions xhttp/xhttp_test.go
Expand Up @@ -55,3 +55,39 @@ func TestInjectMiddlware(t *testing.T) {
log.Fatal(err)
}
}

func TestPanicNilClient(t *testing.T) {
defer func() {
v := recover()
err := v.(error)
if err.Error() != "client is nil" {
t.Errorf("error message is bad (%v)", v)
}
}()

xhttp.Use(nil, nil)
}

func TestPanicNilMiddleware(t *testing.T) {
defer func() {
v := recover()
err := v.(error)
if err.Error() != "middleware is nil" {
t.Errorf("error message is bad (%v)", v)
}
}()

xhttp.Use(new(http.Client), nil)
}

func TestPanicNilMiddlewares(t *testing.T) {
defer func() {
v := recover()
err := v.(error)
if err.Error() != "middlewares is nil" {
t.Errorf("error message is bad (%v)", v)
}
}()

xhttp.Use(new(http.Client))
}

0 comments on commit 8351413

Please sign in to comment.