package migrationAPI import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "net/url" "strconv" "github.com/pkg/errors" ) const ( prodURL = "https://migration.nsi.rackspace.com" stagingURL = "https://migration-staging.nsi.rackspace.com" //sensitiveHeaders = "apikey,X-Auth-Token" ) type ( // Client is the client for clients to clientize with Client struct { Token string URL string } ) // New initializes the client for the user func New(token string, staging bool) *Client { return &Client{ Token: token, URL: func(staging bool) string { if staging { return stagingURL } return prodURL }(staging), } } // NewOptions generates a new Options struct for the user func NewOptions() *Options { return new(Options) } func (c *Client) do(req *http.Request, v interface{}, options *Options) error { httpClient := new(http.Client) if options.HTTPTimeout != nil { httpClient.Timeout = *options.HTTPTimeout } resp, err := httpClient.Do(req) if err != nil { return err } defer func() { if dErr := resp.Body.Close(); dErr != nil { err = errors.Wrap(err, dErr.Error()) } }() if resp.StatusCode > http.StatusNoContent { err = fmt.Errorf("%d:%s", resp.StatusCode, resp.Status) } if v != nil { if w, ok := v.(io.Writer); ok { if _, err = io.Copy(w, resp.Body); err != nil { return fmt.Errorf("do:io.Copy:%w", err) } } else { decodeErr := json.NewDecoder(resp.Body).Decode(v) // ignore EOF errors caused by empty response body if errors.Is(decodeErr, io.EOF) { decodeErr = nil } if decodeErr != nil { err = decodeErr } } } return err } func (c *Client) newRequest(endpoint, httpMethod string, body interface{}, options *Options) (*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.NewRequestWithContext(context.Background(), httpMethod, endpoint, buf) if err != nil { return req, err } req.Header.Add("X-Auth-Token", c.Token) if body != nil { req.Header.Add("Content-Type", "application/json") } params := make(url.Values) if options.UnipedeAge != nil { params.Set("unipedeAge", strconv.Itoa(*options.UnipedeAge)) } if options.HypMatchSource != nil { params.Set("hypMatchSource", strconv.FormatBool(*options.HypMatchSource)) } if options.Device != nil { params.Set("device", strconv.Itoa(*options.Device)) } if options.Account != nil { params.Set("account", strconv.Itoa(*options.Account)) } if options.MoveGroup != nil { params.Set("move_group", *options.MoveGroup) } if len(params) > 0 { req.URL.RawQuery = params.Encode() } return req, nil }