Yet another rest client (for golang)
Yarc is a Go HTTP client library for creating and sending API requests. Check usage or the examples to learn how to yarc into your API client.
- IMO Nice API
- Base/Request: Extend Yarc for different endpoints
- External cache support
- Native JSON support for sending/receiveng structs
- Access to http.Request && http.Response
- Collection of helpers for nice defaults
- Mock server for integration tests: Yams
StupidSimple cache implementation: Yasci
go get github.com/tinchogob/yarc
Read GoDoc
Yarc uses dave's cheney funcional options pattern There a number of functional option functions to customize each client/request.
The can be applied to Yarc's constructor or to Yarc's request executor.
For example, create a base Yarc client with a host and then extend this client to do a request for method+path.
client, err := Yarc.New(Host("https://api.mercadolibre.com))
if err != nil {
panic(err)
}
r, err := client.Go(
GET(),
Path("/items/1234567"),
)
r, err := client.Go(
GET(),
Header("Connection", "keep-alive"),
Path("/items/1234567"),
Query("attributes","id,permalink"),
)
While dealing with JSON requests/response APIS, Yarcs provides some nice helpers out of the box.
Define JSON tagged structs. Use JSON
to JSON encode a struct as the Body on requests.
type ItemRequest struct {
ID string `json:"id"`
Permalink string `json:"permalink"`
}
item := ItemRequest{
ID: "123",
Permalink: "http://permalink.com",
}
r, err := client.Go(
POST(),
Header("Connection", "keep-alive"),
Path("/items/1234567"),
Query("attributes","id,permalink"),
JSON(item),
)
Requests will include an application/json
Content-Type header.
Define JSON structs to decode responses. Use ToJSON(body interface{}, errBody interface{})
to decode the response body into body
if 2xx or else to errBody
.
type Item struct {
ID string `json:"id"`
Permalink string `json:"permalink"`
}
type ApiError struct {
Message string `json:"message"`
Cause string `json:"cause"`
}
item := Item{}
errB := ApiError{}
r, err := client.Go(
GET(),
Header("Connection", "keep-alive"),
Path("/items/1234567"),
Query("attributes","id,permalink"),
ToJSON(&item, &errB),
)
fmt.Println(item, errB)
Yarcs provides an extension point called With
to change/enhance each request
r, err := client.Go(
GET(),
Path("/items/1234567"),
With(func(opts Yarc.Options, req *http.Request) *http.Request {
return req.WithContext(context.Background())
})
)