1
0
mirror of https://github.com/badkaktus/gorocket.git synced 2024-12-12 11:15:05 +02:00

add more options

This commit is contained in:
Алексей Волегов 2022-09-19 15:20:21 +03:00
parent 08c7076e6b
commit 84215f0567
2 changed files with 27 additions and 6 deletions

2
go.mod
View File

@ -1,3 +1,3 @@
module github.com/badkaktus/gorocket
go 1.17
go 1.13

View File

@ -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)