Use Request.WithContext
parent
5e84b57bf3
commit
6fe43e545a
41
mastodon.go
41
mastodon.go
|
@ -24,23 +24,6 @@ type Client struct {
|
||||||
config *Config
|
config *Config
|
||||||
}
|
}
|
||||||
|
|
||||||
func httpDo(ctx context.Context, req *http.Request, f func(*http.Response, error) error) error {
|
|
||||||
tr := &http.Transport{}
|
|
||||||
client := &http.Client{Transport: tr}
|
|
||||||
c := make(chan error, 1)
|
|
||||||
go func() {
|
|
||||||
c <- f(client.Do(req))
|
|
||||||
}()
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
tr.CancelRequest(req)
|
|
||||||
<-c
|
|
||||||
return ctx.Err()
|
|
||||||
case err := <-c:
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) doAPI(ctx context.Context, method string, uri string, params url.Values, res interface{}) error {
|
func (c *Client) doAPI(ctx context.Context, method string, uri string, params url.Values, res interface{}) error {
|
||||||
u, err := url.Parse(c.config.Server)
|
u, err := url.Parse(c.config.Server)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -52,24 +35,24 @@ func (c *Client) doAPI(ctx context.Context, method string, uri string, params ur
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
req.WithContext(ctx)
|
||||||
req.Header.Set("Authorization", "Bearer "+c.config.AccessToken)
|
req.Header.Set("Authorization", "Bearer "+c.config.AccessToken)
|
||||||
if params != nil {
|
if params != nil {
|
||||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
}
|
}
|
||||||
|
|
||||||
return httpDo(ctx, req, func(resp *http.Response, err error) error {
|
resp, err := c.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
return fmt.Errorf("bad request: %v", resp.Status)
|
return fmt.Errorf("bad request: %v", resp.Status)
|
||||||
} else if res == nil {
|
} else if res == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return json.NewDecoder(resp.Body).Decode(&res)
|
return json.NewDecoder(resp.Body).Decode(&res)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClient return new mastodon API client.
|
// NewClient return new mastodon API client.
|
||||||
|
|
Loading…
Reference in New Issue