67 lines
1.4 KiB
Go
67 lines
1.4 KiB
Go
package serverapi
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
// Client is a client aimed at a specific ServerAPI endpoint
|
|
type Client struct {
|
|
Endpoint string
|
|
Options *ClientOptions
|
|
}
|
|
|
|
// ClientOptions are options that can be set for a Client
|
|
type ClientOptions struct {
|
|
HTTP *http.Client
|
|
Password string
|
|
}
|
|
|
|
var (
|
|
// DefaultOptions are the default set of ClientOptions for a Client
|
|
DefaultOptions = &ClientOptions{
|
|
HTTP: http.DefaultClient,
|
|
}
|
|
|
|
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, options *ClientOptions) *Client {
|
|
if options == nil {
|
|
options = DefaultOptions
|
|
}
|
|
endpoint = strings.TrimSuffix(endpoint, "/")
|
|
return &Client{
|
|
Endpoint: endpoint,
|
|
Options: options,
|
|
}
|
|
}
|
|
|
|
func (c *Client) json(endpoint string, obj interface{}) error {
|
|
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
|
|
if err != nil {
|
|
return fmt.Errorf("new JSON request: %v", err)
|
|
}
|
|
req.Header = defaultHeader
|
|
req.Header.Add("X-ServerAPI-Password", c.Options.Password)
|
|
|
|
res, err := c.Options.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)
|
|
}
|