From 84215f05677486d59765cbe51e25f5cbef16e4e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9=20=D0=92=D0=BE?= =?UTF-8?q?=D0=BB=D0=B5=D0=B3=D0=BE=D0=B2?= Date: Mon, 19 Sep 2022 15:20:21 +0300 Subject: [PATCH] add more options --- go.mod | 2 +- gorocket.go | 31 ++++++++++++++++++++++++++----- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index 2f070cf..5a5baf1 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ module github.com/badkaktus/gorocket -go 1.17 +go 1.13 diff --git a/gorocket.go b/gorocket.go index adf9e54..11ff0c9 100644 --- a/gorocket.go +++ b/gorocket.go @@ -1,6 +1,7 @@ package gorocket import ( + "context" "encoding/json" "log" "net/http" @@ -13,17 +14,30 @@ type Client struct { xToken string apiVersion string HTTPClient *http.Client + + timeout time.Duration } // NewClient creates new Facest.io client with given API key -func NewClient(opts ...Option) *Client { - c := &Client{ +func NewClient(url string) *Client { + return &Client{ //userID: user, HTTPClient: &http.Client{ Timeout: 5 * time.Minute, }, //xToken: token, - // baseURL: url, + baseURL: url, + apiVersion: "api/v1", + } +} + +// NewClient creates new Facest.io client with given API key +func NewWithOptions(url string, opts ...Option) *Client { + c := &Client{ + HTTPClient: &http.Client{ + Timeout: 5 * time.Minute, + }, + baseURL: url, apiVersion: "api/v1", } @@ -36,9 +50,9 @@ func NewClient(opts ...Option) *Client { type Option func(*Client) -func WithUrl(url string) Option { +func WithTimeout(d time.Duration) Option { return func(c *Client) { - c.baseURL = url + c.timeout = d } } @@ -60,6 +74,13 @@ func (c *Client) sendRequest(req *http.Request, v interface{}) error { req.Header.Add("X-Auth-Token", c.xToken) req.Header.Add("X-User-Id", c.userID) + if c.timeout > 0 { + ctx, cancel := context.WithTimeout(req.Context(), c.timeout) + defer cancel() + + req = req.WithContext(ctx) + } + res, err := c.HTTPClient.Do(req) if err != nil { log.Println(err)