Last active
May 6, 2021 05:13
-
-
Save terinjokes/ffa4f3e6e7c89b07521ae57ec0674de2 to your computer and use it in GitHub Desktop.
Golang example of context in API Clients
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package api | |
import ( | |
"encoding/json" | |
"golang.org/x/net/context" | |
"golang.org/x/net/context/ctxhttp" | |
) | |
type Client { | |
} | |
type Response { | |
id string | |
} | |
func NewClient() *Client { | |
client := &Client{} | |
return client | |
} | |
func (c *Client) FetchResource(ctx context.Context, endpoint string) (*Response, error) { | |
res, err := ctxhttp.Get("http://api.example.com/v1/" + endpoint) | |
if err != nil { | |
return nil, err | |
} | |
defer res.Body.Close() | |
decoder := json.NewDecoder(res.Body) | |
var data Response | |
err = decoder.Decode(&data) | |
if err != nil { | |
return nil, err | |
} | |
return &data, nil | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"time" | |
"example/api" | |
"golang.org/x/net/context" | |
) | |
func fetch(ctx context.Context, client *api.Client, endpoint string) (*api.Response, error) { | |
ctx, cancel := context.WithTimeout(ctx, 5*time.Second) | |
defer cancel() | |
return client.FetchResource(endpoint) | |
} | |
func main() { | |
client := api.NewClient() | |
ctx := context.Background() | |
resp, err := fetch(ctx, client, "foobar") | |
if err != nil { | |
log.Fatal(err) // 2016/05/02 15:30:00 context deadline exceeded | |
// exit status 1 | |
} | |
fmt.Println("foobar response: %s", resp.id) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment