Adding context and options to your Go client package

Cancelation and deadlines

func (c *Client) ListUsers(ctx context.Context) ([]User, error) { 
req, err := c.newRequest("GET", "/users", nil)
if err != nil {
return nil, err
}
var users []User
_, err = c.do(ctx, req, &users)
return users, err
}
func (c *Client) do(ctx context.Context, req *http.Request, v interface{}) (*http.Response, error) {
req = req.WithContext(ctx)
resp, err := c.httpClient.Do(req)
if err != nil {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
return nil, err
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(v)
return resp, err
}

Optional parameters

type UserListOptions struct{
Page int `url:"page"`
PerPage int `url:"per_page"`
}
func addOptions(s string, opt interface{}) (string, error) {
v := reflect.ValueOf(opt)
if v.Kind() == reflect.Ptr && v.IsNil() {
return s, nil
}
u, err := url.Parse(s)
if err != nil {
return s, err
}
vs, err := query.Values(opt)
if err != nil {
return s, err
}
u.RawQuery = vs.Encode()
return u.String(), nil
}
func (c *Client) ListUsers(ctx context.Context, opts *UserListOptions) ([]User, error) {
u, err := addOptions("/users", opts)
if err != nil {
return nil, err
}

req, err := c.newRequest("GET", u, nil)
if err != nil {
return nil, err
}
var users []User
_, err = c.do(ctx, req, &users)
return users, err
}

Putting it all to use

ctx := context.Background()ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
opt := chatsby.UserListOptions{
Page: 2,
PerPage: 10,
}
u, err := client.ListUsers(ctx, &opt)
if err != nil {
if err == context.DeadlineExceeded {
// ...
}
}

--

--

--

Developer Advocate at Grafana Labs

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Network Packet Manual Analysis

Use Azure File Share to back up your data

Vokter v0.2: Software architecture & design philosophy

You Don’t Have To Be Brilliant To Learn How To Code

Clean up your room!

Here’s who could serve in top functions in the Biden organization

A quick way to delete all rows from a table (unintentionally…)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Marcus Olsson

Marcus Olsson

Developer Advocate at Grafana Labs

More from Medium

How to upgrade Golang version in Linux?

How to Check nil Interface in Golang?

Getting started with GO Programming Language — Part Two

ELK stack in GoLang — 1