Skip to content

Commit f9a6e5d

Browse files
committed
update readme
1 parent edba125 commit f9a6e5d

File tree

1 file changed

+59
-2
lines changed

1 file changed

+59
-2
lines changed

README.md

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,10 @@ type Output struct {
1818
ResponseValue string `json:"responseValue"`
1919
}
2020

21-
params := Params{
21+
params := request.Params{
2222
URL: "https://example.com",
2323
Method: "POST",
24-
Headers: map[string]string{"my-header":"value", "another-header":"value2"}
24+
Headers: map[string]string{"my-header":"value", "another-header":"value2"},
2525
Body: Input{RequestValue: "someValueIn"},
2626
Query: map[string]string{"key": "value"},
2727
}
@@ -48,3 +48,60 @@ err := request.Post("http://example.com", Input{RequestValue: "someValueIn"}, re
4848
## Streaming
4949
The package allows the request body (`Body` property of `Params`) to be of type `io.Reader`. That way you can pass on request bodies to other services without parsing them.
5050

51+
## Why?
52+
To understand why this package was created have a look at the code that would be the native equivalent of the code shown in the example above.
53+
```go
54+
import (
55+
"bytes"
56+
"encoding/json"
57+
"net/http"
58+
"time"
59+
)
60+
61+
type Input struct {
62+
RequestValue string `json:"requestValue"`
63+
}
64+
65+
type Output struct {
66+
ResponseValue string `json:"responseValue"`
67+
}
68+
69+
buf := &bytes.Buffer{}
70+
err := json.NewEncoder(buf).Encode(&Input{RequestValue: "someValueIn"})
71+
if err != nil {
72+
return err
73+
}
74+
75+
req, err := http.NewRequest("POST", url, buf)
76+
if err != nil {
77+
return err
78+
}
79+
80+
req.Header.Set("Accept", "application/json")
81+
req.Header.Set("Content-Type", "application/json")
82+
req.Header.Set("my-header", "value")
83+
req.Header.Set("another-header", "value2")
84+
85+
q := req.URL.Query()
86+
q.Add("key", "value")
87+
req.URL.RawQuery = q.Encode()
88+
89+
client := &http.Client{
90+
Timeout: 30 * time.Second,
91+
CheckRedirect: func(req *http.Request, via []*http.Request) error {
92+
return http.ErrUseLastResponse
93+
},
94+
}
95+
96+
res, err := client.Do(req)
97+
if err != nil {
98+
return err
99+
}
100+
defer func() {
101+
res.Body.Close()
102+
}()
103+
104+
result := &Output{}
105+
err = json.NewDecoder(res.Body).Decode(result)
106+
```
107+
This shows the request package saves a lot of boilerplate code. instead of around 35 lines we just write the 9 lines shown in the example. That way the code is much easier to read and maintain.

0 commit comments

Comments
 (0)