-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
53 lines (47 loc) · 1.28 KB
/
Copy pathexample_test.go
File metadata and controls
53 lines (47 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package httpx_test
import (
"fmt"
"net/http"
"os"
"time"
"github.com/tflyons/httpx"
)
func NewClient() httpx.Client {
c := httpx.DefaultClient
// set a header to be sent on every request
c = httpx.SetHeader(c, "some-header", "1234")
// limit the total request volume to 100 per minute
c = httpx.SetRateLimit(c, 100, time.Minute)
// limit every request to 30 seconds round trip
c = httpx.SetTimeout(c, time.Second*30)
// set an initializer to load a token from a file into the header prior to doing calls
c = httpx.SetInitializer(c, func(next httpx.Client) (httpx.ClientFunc, error) {
token, err := os.ReadFile("mytoken.txt")
if err != nil {
return nil, err
}
return httpx.SetHeader(next, "SOME-TOKEN", string(token)), nil
})
return c
}
func Example() {
c := NewClient()
thing, err := GetThing(c)
if err != nil {
panic(err)
}
fmt.Println(thing)
}
type Thing struct {
Foo string `json:"foo"`
Bar int `json:"bar"`
}
func GetThing(baseClient httpx.Client) (Thing, error) {
c := httpx.SetHeader(baseClient, "ThingSpecificHeader", "abcd")
c = httpx.RequireResponseStatus(c, http.StatusOK)
var thing Thing
c = httpx.SetResponseBodyHandlerJSON(c, &thing)
c = httpx.SetRequest(c, http.MethodGet, "http://example.com/things")
_, err := c.Do(nil)
return thing, err
}