package unipede import ( "bytes" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strconv" ) const unipedeURL = "https://unipede.rackspace.net/" type ( Client struct { Username *string Password *string APIKEY *string } Error struct { Created string `json:"created"` Id int `json:"id"` Job string `json:"job"` Message string `json:"message"` UpDeviceId int `json:"up_device_id"` } respErr struct { Status int `json:"status"` Method string `json:"method"` Message string `json:"message"` } Links struct { Href *string `json:"href"` Rel *string `json:"rel"` } ) func New(username, password, apiKey string) (*Client, error) { if apiKey != "" { return &Client{ APIKEY: &apiKey, }, nil } if username == "" { return nil, errors.New("username cannot be blank") } if password == "" { return nil, errors.New("password cannot be blank") } return &Client{ Username: &username, Password: &password, }, nil } func NewKeyClient(apiKey string) *Client { return &Client{ APIKEY: &apiKey, } } func (u *Client) AddAuth(req *http.Request) { if u.APIKEY != nil { req.Header.Set("jwt", *u.APIKEY) return } req.SetBasicAuth(*u.Username, *u.Password) } func (u *Client) do(req *http.Request, options *UnipedeOptions, v interface{}) (*http.Response, error) { httpClient := new(http.Client) if options.HTTPTimeout != nil { httpClient.Timeout = *options.HTTPTimeout } resp, err := httpClient.Do(req) if resp != nil { defer func() { if defErr := resp.Body.Close(); defErr != nil { err = fmt.Errorf("%s::%s", err, defErr) } }() } if err != nil { return nil, err } // Since we are doing some weird handling of the response body here, then we also need // to handle response codes from the API. if resp.StatusCode > http.StatusNoContent { codeErr := new(respErr) if err := json.NewDecoder(resp.Body).Decode(codeErr); err != nil { return nil, errors.New(resp.Status) } return nil, fmt.Errorf("%s: %s", resp.Status, codeErr.Message) } if v != nil { if w, ok := v.(io.Writer); ok { io.Copy(w, resp.Body) } else { decodeErr := json.NewDecoder(resp.Body).Decode(v) // ignore EOF errors caused by empty response body if decodeErr == io.EOF { decodeErr = nil } if decodeErr != nil { err = decodeErr } } } return resp, err } func (u *Client) newRequest(endpoint, httpMethod string, options *UnipedeOptions, body interface{}) (*http.Request, error) { var buf io.ReadWriter if body != nil { buf = new(bytes.Buffer) enc := json.NewEncoder(buf) enc.SetEscapeHTML(false) err := enc.Encode(body) if err != nil { return nil, err } } req, err := http.NewRequest(httpMethod, endpoint, buf) if err != nil { return req, err } u.AddAuth(req) params := make(url.Values) if options.Params != nil { params = *options.Params } if options.Filter != nil { params.Set("filter", *options.Filter) } if options.Refresh != nil { params.Set("age", strconv.Itoa(*options.Refresh)) } if len(params) > 0 { req.URL.RawQuery = params.Encode() } if body != nil { req.Header.Add("Content-Type", "application/json") } return req, nil }