package serverapi import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "strings" ) // Client is a client aimed at a specific ServerAPI endpoint type Client struct { endpoint string http *http.Client token string } // ClientOption is options for a Client type ClientOption func(c *Client) var defaultHeader = http.Header{ "Content-Type": []string{"application/json; charset=utf-8"}, "Accept": []string{"application/json; charset=utf-8"}, } // NewClient returns a new Client for making ServerAPI requests func NewClient(endpoint string, opts ...ClientOption) *Client { endpoint = strings.TrimSuffix(endpoint, "/") c := &Client{ endpoint: endpoint, http: http.DefaultClient, token: "", } for _, opt := range opts { opt(c) } return c } // WithHTTP is a ClientOption for setting the http.Client of a Client func WithHTTP(http *http.Client) ClientOption { return func(c *Client) { c.http = http } } // WithToken is a ClientOption for setting the token of a Client func WithToken(token string) ClientOption { return func(c *Client) { c.token = token } } func (c *Client) jsonGET(endpoint string, obj interface{}) error { req, err := c.newRequest(endpoint, http.MethodGet, nil) if err != nil { return err } res, err := c.http.Do(req) if err != nil { return fmt.Errorf("sending request: %v", err) } body, err := ioutil.ReadAll(res.Body) if err != nil { return fmt.Errorf("reading body: %v", err) } return json.Unmarshal(body, obj) } func (c *Client) jsonPOST(endpoint string, obj interface{}) (int, error) { body, err := json.Marshal(obj) if err != nil { return -1, err } req, err := c.newRequest(endpoint, http.MethodPost, body) if err != nil { return -1, err } res, err := c.http.Do(req) if err != nil { return -1, fmt.Errorf("sending request: %v", err) } return res.StatusCode, nil } func (c *Client) newRequest(endpoint, method string, body []byte) (*http.Request, error) { req, err := http.NewRequest(method, endpoint, bytes.NewBuffer(body)) if err != nil { return nil, fmt.Errorf("new JSON request: %v", err) } req.Header = defaultHeader req.Header.Add("X-ServerAPI-Token", c.token) return req, nil }