1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
|
package packngo
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"
"strings"
"time"
)
const (
packetTokenEnvVar = "PACKET_AUTH_TOKEN"
libraryVersion = "0.1.0"
baseURL = "https://api.packet.net/"
userAgent = "packngo/" + libraryVersion
mediaType = "application/json"
debugEnvVar = "PACKNGO_DEBUG"
headerRateLimit = "X-RateLimit-Limit"
headerRateRemaining = "X-RateLimit-Remaining"
headerRateReset = "X-RateLimit-Reset"
)
type GetOptions struct {
Includes []string
Excludes []string
}
// ListOptions specifies optional global API parameters
type ListOptions struct {
// for paginated result sets, page of results to retrieve
Page int `url:"page,omitempty"`
// for paginated result sets, the number of results to return per page
PerPage int `url:"per_page,omitempty"`
Includes []string
Excludes []string
}
func makeSureGetOptionsInclude(g *GetOptions, s string) *GetOptions {
if g == nil {
return &GetOptions{Includes: []string{s}}
}
if !contains(g.Includes, s) {
g.Includes = append(g.Includes, s)
}
return g
}
func makeSureListOptionsInclude(l *ListOptions, s string) *ListOptions {
if l == nil {
return &ListOptions{Includes: []string{s}}
}
if !contains(l.Includes, s) {
l.Includes = append(l.Includes, s)
}
return l
}
func createGetOptionsURL(g *GetOptions) (url string) {
if g == nil {
return ""
}
if len(g.Includes) != 0 {
url += fmt.Sprintf("include=%s", strings.Join(g.Includes, ","))
}
if len(g.Excludes) != 0 {
if url != "" {
url += "&"
}
url += fmt.Sprintf("exclude=%s", strings.Join(g.Excludes, ","))
}
return
}
func createListOptionsURL(l *ListOptions) (url string) {
if l == nil {
return ""
}
if len(l.Includes) != 0 {
url += fmt.Sprintf("include=%s", strings.Join(l.Includes, ","))
}
if len(l.Excludes) != 0 {
if url != "" {
url += "&"
}
url += fmt.Sprintf("exclude=%s", strings.Join(l.Excludes, ","))
}
if l.Page != 0 {
if url != "" {
url += "&"
}
url += fmt.Sprintf("page=%d", l.Page)
}
if l.PerPage != 0 {
if url != "" {
url += "&"
}
url += fmt.Sprintf("per_page=%d", l.PerPage)
}
return
}
// meta contains pagination information
type meta struct {
Self *Href `json:"self"`
First *Href `json:"first"`
Last *Href `json:"last"`
Previous *Href `json:"previous,omitempty"`
Next *Href `json:"next,omitempty"`
Total int `json:"total"`
CurrentPageNum int `json:"current_page"`
LastPageNum int `json:"last_page"`
}
// Response is the http response from api calls
type Response struct {
*http.Response
Rate
}
// Href is an API link
type Href struct {
Href string `json:"href"`
}
func (r *Response) populateRate() {
// parse the rate limit headers and populate Response.Rate
if limit := r.Header.Get(headerRateLimit); limit != "" {
r.Rate.RequestLimit, _ = strconv.Atoi(limit)
}
if remaining := r.Header.Get(headerRateRemaining); remaining != "" {
r.Rate.RequestsRemaining, _ = strconv.Atoi(remaining)
}
if reset := r.Header.Get(headerRateReset); reset != "" {
if v, _ := strconv.ParseInt(reset, 10, 64); v != 0 {
r.Rate.Reset = Timestamp{time.Unix(v, 0)}
}
}
}
// ErrorResponse is the http response used on errors
type ErrorResponse struct {
Response *http.Response
Errors []string `json:"errors"`
SingleError string `json:"error"`
}
func (r *ErrorResponse) Error() string {
return fmt.Sprintf("%v %v: %d %v %v",
r.Response.Request.Method, r.Response.Request.URL, r.Response.StatusCode, strings.Join(r.Errors, ", "), r.SingleError)
}
// Client is the base API Client
type Client struct {
client *http.Client
debug bool
BaseURL *url.URL
UserAgent string
ConsumerToken string
APIKey string
RateLimit Rate
// Packet Api Objects
Plans PlanService
Users UserService
Emails EmailService
SSHKeys SSHKeyService
Devices DeviceService
Projects ProjectService
Facilities FacilityService
OperatingSystems OSService
DeviceIPs DeviceIPService
DevicePorts DevicePortService
ProjectIPs ProjectIPService
ProjectVirtualNetworks ProjectVirtualNetworkService
Volumes VolumeService
VolumeAttachments VolumeAttachmentService
SpotMarket SpotMarketService
SpotMarketRequests SpotMarketRequestService
Organizations OrganizationService
BGPSessions BGPSessionService
BGPConfig BGPConfigService
CapacityService CapacityService
Batches BatchService
TwoFactorAuth TwoFactorAuthService
VPN VPNService
HardwareReservations HardwareReservationService
Events EventService
Notifications NotificationService
Connects ConnectService
}
// NewRequest inits a new http request with the proper headers
func (c *Client) NewRequest(method, path string, body interface{}) (*http.Request, error) {
// relative path to append to the endpoint url, no leading slash please
rel, err := url.Parse(path)
if err != nil {
return nil, err
}
u := c.BaseURL.ResolveReference(rel)
// json encode the request body, if any
buf := new(bytes.Buffer)
if body != nil {
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
req.Close = true
req.Header.Add("X-Auth-Token", c.APIKey)
req.Header.Add("X-Consumer-Token", c.ConsumerToken)
req.Header.Add("Content-Type", mediaType)
req.Header.Add("Accept", mediaType)
req.Header.Add("User-Agent", userAgent)
return req, nil
}
// Do executes the http request
func (c *Client) Do(req *http.Request, v interface{}) (*Response, error) {
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
response := Response{Response: resp}
response.populateRate()
if c.debug {
o, _ := httputil.DumpResponse(response.Response, true)
log.Printf("\n=======[RESPONSE]============\n%s\n\n", string(o))
}
c.RateLimit = response.Rate
err = checkResponse(resp)
// if the response is an error, return the ErrorResponse
if err != nil {
return &response, err
}
if v != nil {
// if v implements the io.Writer interface, return the raw response
if w, ok := v.(io.Writer); ok {
io.Copy(w, resp.Body)
} else {
err = json.NewDecoder(resp.Body).Decode(v)
if err != nil {
return &response, err
}
}
}
return &response, err
}
// DoRequest is a convenience method, it calls NewRequest followed by Do
// v is the interface to unmarshal the response JSON into
func (c *Client) DoRequest(method, path string, body, v interface{}) (*Response, error) {
req, err := c.NewRequest(method, path, body)
if c.debug {
o, _ := httputil.DumpRequestOut(req, true)
log.Printf("\n=======[REQUEST]=============\n%s\n", string(o))
}
if err != nil {
return nil, err
}
return c.Do(req, v)
}
// DoRequestWithHeader same as DoRequest
func (c *Client) DoRequestWithHeader(method string, headers map[string]string, path string, body, v interface{}) (*Response, error) {
req, err := c.NewRequest(method, path, body)
for k, v := range headers {
req.Header.Add(k, v)
}
if c.debug {
o, _ := httputil.DumpRequestOut(req, true)
log.Printf("\n=======[REQUEST]=============\n%s\n", string(o))
}
if err != nil {
return nil, err
}
return c.Do(req, v)
}
// NewClient initializes and returns a Client
func NewClient() (*Client, error) {
apiToken := os.Getenv(packetTokenEnvVar)
if apiToken == "" {
return nil, fmt.Errorf("you must export %s", packetTokenEnvVar)
}
c := NewClientWithAuth("packngo lib", apiToken, nil)
return c, nil
}
// NewClientWithAuth initializes and returns a Client, use this to get an API Client to operate on
// N.B.: Packet's API certificate requires Go 1.5+ to successfully parse. If you are using
// an older version of Go, pass in a custom http.Client with a custom TLS configuration
// that sets "InsecureSkipVerify" to "true"
func NewClientWithAuth(consumerToken string, apiKey string, httpClient *http.Client) *Client {
client, _ := NewClientWithBaseURL(consumerToken, apiKey, httpClient, baseURL)
return client
}
// NewClientWithBaseURL returns a Client pointing to nonstandard API URL, e.g.
// for mocking the remote API
func NewClientWithBaseURL(consumerToken string, apiKey string, httpClient *http.Client, apiBaseURL string) (*Client, error) {
if httpClient == nil {
// Don't fall back on http.DefaultClient as it's not nice to adjust state
// implicitly. If the client wants to use http.DefaultClient, they can
// pass it in explicitly.
httpClient = &http.Client{}
}
u, err := url.Parse(apiBaseURL)
if err != nil {
return nil, err
}
c := &Client{client: httpClient, BaseURL: u, UserAgent: userAgent, ConsumerToken: consumerToken, APIKey: apiKey}
c.debug = os.Getenv(debugEnvVar) != ""
c.Plans = &PlanServiceOp{client: c}
c.Organizations = &OrganizationServiceOp{client: c}
c.Users = &UserServiceOp{client: c}
c.Emails = &EmailServiceOp{client: c}
c.SSHKeys = &SSHKeyServiceOp{client: c}
c.Devices = &DeviceServiceOp{client: c}
c.Projects = &ProjectServiceOp{client: c}
c.Facilities = &FacilityServiceOp{client: c}
c.OperatingSystems = &OSServiceOp{client: c}
c.DeviceIPs = &DeviceIPServiceOp{client: c}
c.DevicePorts = &DevicePortServiceOp{client: c}
c.ProjectVirtualNetworks = &ProjectVirtualNetworkServiceOp{client: c}
c.ProjectIPs = &ProjectIPServiceOp{client: c}
c.Volumes = &VolumeServiceOp{client: c}
c.VolumeAttachments = &VolumeAttachmentServiceOp{client: c}
c.SpotMarket = &SpotMarketServiceOp{client: c}
c.BGPSessions = &BGPSessionServiceOp{client: c}
c.BGPConfig = &BGPConfigServiceOp{client: c}
c.CapacityService = &CapacityServiceOp{client: c}
c.Batches = &BatchServiceOp{client: c}
c.TwoFactorAuth = &TwoFactorAuthServiceOp{client: c}
c.VPN = &VPNServiceOp{client: c}
c.HardwareReservations = &HardwareReservationServiceOp{client: c}
c.SpotMarketRequests = &SpotMarketRequestServiceOp{client: c}
c.Events = &EventServiceOp{client: c}
c.Notifications = &NotificationServiceOp{client: c}
c.Connects = &ConnectServiceOp{client: c}
return c, nil
}
func checkResponse(r *http.Response) error {
// return if http status code is within 200 range
if c := r.StatusCode; c >= 200 && c <= 299 {
// response is good, return
return nil
}
errorResponse := &ErrorResponse{Response: r}
data, err := ioutil.ReadAll(r.Body)
// if the response has a body, populate the message in errorResponse
if err == nil && len(data) > 0 {
json.Unmarshal(data, errorResponse)
}
return errorResponse
}
|