mirror of
https://github.com/badkaktus/gorocket.git
synced 2025-07-13 01:10:14 +02:00
add more options
This commit is contained in:
2
go.mod
2
go.mod
@ -1,3 +1,3 @@
|
|||||||
module github.com/badkaktus/gorocket
|
module github.com/badkaktus/gorocket
|
||||||
|
|
||||||
go 1.17
|
go 1.13
|
||||||
|
31
gorocket.go
31
gorocket.go
@ -1,6 +1,7 @@
|
|||||||
package gorocket
|
package gorocket
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
@ -13,17 +14,30 @@ type Client struct {
|
|||||||
xToken string
|
xToken string
|
||||||
apiVersion string
|
apiVersion string
|
||||||
HTTPClient *http.Client
|
HTTPClient *http.Client
|
||||||
|
|
||||||
|
timeout time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClient creates new Facest.io client with given API key
|
// NewClient creates new Facest.io client with given API key
|
||||||
func NewClient(opts ...Option) *Client {
|
func NewClient(url string) *Client {
|
||||||
c := &Client{
|
return &Client{
|
||||||
//userID: user,
|
//userID: user,
|
||||||
HTTPClient: &http.Client{
|
HTTPClient: &http.Client{
|
||||||
Timeout: 5 * time.Minute,
|
Timeout: 5 * time.Minute,
|
||||||
},
|
},
|
||||||
//xToken: token,
|
//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",
|
apiVersion: "api/v1",
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -36,9 +50,9 @@ func NewClient(opts ...Option) *Client {
|
|||||||
|
|
||||||
type Option func(*Client)
|
type Option func(*Client)
|
||||||
|
|
||||||
func WithUrl(url string) Option {
|
func WithTimeout(d time.Duration) Option {
|
||||||
return func(c *Client) {
|
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-Auth-Token", c.xToken)
|
||||||
req.Header.Add("X-User-Id", c.userID)
|
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)
|
res, err := c.HTTPClient.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
|
Reference in New Issue
Block a user