An extended easily mockable native compatible http client
package main
import "github.com/mbirinci/easyhttp"
func main() {
client := easyhttp.Client {
&http.Client{} // pass your underlying stdlib *http.Client
}
resp, err := client.EasyGet("http://foo.bar/", &easyhttp.Options{
Header: map[string]string{
"If-Not-Now": "When",
},
})
if err != nil {
panic(err)
}
var data struct{ Foo string }
resp.JSON(&data)
// use the data
fmt.Println("%v", data)
}package application
type HttpClient interface {
EasyGet(url string, opts *easyhttp.Options) (*easyhttp.Response, error)
}
type Application struct {
httpClient HttpClient
}
func NewApp(c HttpClient) *Application {
return Application{ c }
}
type Foo struct{
Bar string
}
func (app *Application) GetFoo() Foo {
resp, err := app.httpClient.EasyGet("http://foo.bar", &easyhttp.Options{})
if err != nil {
panic(err)
}
var foo Foo
err = resp.JSON(&foo)
if err != nil {
panic(err)
}
return foo
}package application_test
type mockHttpClient struct{}
func (*mockHttpClient) EasyGet(url string, opts *easyhttp.Options) (*easyhttp.Response, error) {
return &easyhttp.Response{RawBody: []byte(`{"bar": "bar"}`)}, nil
}
func TestApp(t *testing.T) {
app := Application{HttpClient: mockHttpClient}
foo := app.GetFoo()
if foo.Bar != "bar" {
t.Fatalf("expected bar, but got %s", foo.Bar)
}
}