github.com/NaverCloudPlatform/ncloud-sdk-go-v2@v1.6.13/services/vautoscaling/api_client.go (about) 1 /* 2 * vautoscaling 3 * 4 * VPC Auto Scaling 관련 API<br/>https://ncloud.apigw.ntruss.com/vautoscaling/v2 5 * 6 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) 7 */ 8 9 package vautoscaling 10 11 import ( 12 "bytes" 13 "crypto" 14 "errors" 15 "fmt" 16 "io" 17 "mime/multipart" 18 "net/http" 19 "net/url" 20 "os" 21 "path/filepath" 22 "reflect" 23 "regexp" 24 "strconv" 25 "strings" 26 "time" 27 "unicode" 28 "unicode/utf8" 29 30 "github.com/NaverCloudPlatform/ncloud-sdk-go-v2/hmac" 31 "github.com/NaverCloudPlatform/ncloud-sdk-go-v2/ncloud" 32 ) 33 34 var ( 35 jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") 36 xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") 37 ) 38 39 // APIClient manages communication with the vautoscaling API v2021-01-21T11:15:08Z 40 // In most cases there should be only one, shared, APIClient. 41 type APIClient struct { 42 cfg *ncloud.Configuration 43 common service // Reuse a single struct instead of allocating one for each service on the heap. 44 45 // API Services 46 V2Api *V2ApiService 47 } 48 49 type service struct { 50 client *APIClient 51 } 52 53 // NewAPIClient creates a new API client. Requires a userAgent string describing your application. 54 // optionally a custom http.Client to allow for advanced features such as caching. 55 func NewAPIClient(cfg *ncloud.Configuration) *APIClient { 56 if cfg.HTTPClient == nil { 57 cfg.HTTPClient = http.DefaultClient 58 } 59 60 c := &APIClient{} 61 c.cfg = cfg 62 c.cfg.InitCredentials() 63 c.common.client = c 64 65 // API Services 66 c.V2Api = (*V2ApiService)(&c.common) 67 68 return c 69 } 70 71 func atoi(in string) (int, error) { 72 return strconv.Atoi(in) 73 } 74 75 // selectHeaderContentType select a content type from the available list. 76 func selectHeaderContentType(contentTypes []string) string { 77 if len(contentTypes) == 0 { 78 return "" 79 } 80 if contains(contentTypes, "application/json") { 81 return "application/json" 82 } 83 return contentTypes[0] // use the first content type specified in 'consumes' 84 } 85 86 // selectHeaderAccept join all accept types and return 87 func selectHeaderAccept(accepts []string) string { 88 if len(accepts) == 0 { 89 return "" 90 } 91 92 if contains(accepts, "application/json") { 93 return "application/json" 94 } 95 96 return strings.Join(accepts, ",") 97 } 98 99 // contains is a case insenstive match, finding needle in a haystack 100 func contains(haystack []string, needle string) bool { 101 for _, a := range haystack { 102 if strings.ToLower(a) == strings.ToLower(needle) { 103 return true 104 } 105 } 106 return false 107 } 108 109 // Verify optional parameters are of the correct type. 110 func typeCheckParameter(obj interface{}, expected string, name string) error { 111 // Make sure there is an object. 112 if obj == nil { 113 return nil 114 } 115 116 // Check the type is as expected. 117 if reflect.TypeOf(obj).String() != expected { 118 return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) 119 } 120 return nil 121 } 122 123 // parameterToString convert interface{} parameters to string, using a delimiter if format is provided. 124 func parameterToString(obj interface{}, collectionFormat string) string { 125 var delimiter string 126 127 switch collectionFormat { 128 case "pipes": 129 delimiter = "|" 130 case "ssv": 131 delimiter = " " 132 case "tsv": 133 delimiter = "\t" 134 case "csv": 135 delimiter = "," 136 } 137 138 if reflect.TypeOf(obj).Kind() == reflect.Slice { 139 return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") 140 } 141 142 return fmt.Sprintf("%v", obj) 143 } 144 145 // callAPI do the request. 146 func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { 147 return c.cfg.HTTPClient.Do(request) 148 } 149 150 // Change base path to allow switching to mocks 151 func (c *APIClient) ChangeBasePath(path string) { 152 c.cfg.BasePath = path 153 } 154 155 // prepareRequest build the request 156 func (c *APIClient) prepareRequest( 157 path string, 158 method string, 159 postBody interface{}, 160 headerParams map[string]string, 161 queryParams url.Values, 162 formParams url.Values, 163 fileName string, 164 fileBytes []byte) (localVarRequest *http.Request, err error) { 165 166 var body *bytes.Buffer 167 168 // Detect postBody type and post. 169 if postBody != nil { 170 contentType := headerParams["Content-Type"] 171 if contentType == "" { 172 contentType = detectContentType(postBody) 173 headerParams["Content-Type"] = contentType 174 } 175 176 body, err = setBody(postBody, contentType) 177 if err != nil { 178 return nil, err 179 } 180 } 181 182 // add form parameters and file if available. 183 if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { 184 if body != nil { 185 return nil, errors.New("Cannot specify postBody and multipart form at the same time.") 186 } 187 body = &bytes.Buffer{} 188 w := multipart.NewWriter(body) 189 190 for k, v := range formParams { 191 for _, iv := range v { 192 if strings.HasPrefix(k, "@") { // file 193 err = addFile(w, k[1:], iv) 194 if err != nil { 195 return nil, err 196 } 197 } else { // form value 198 w.WriteField(k, iv) 199 } 200 } 201 } 202 if len(fileBytes) > 0 && fileName != "" { 203 w.Boundary() 204 //_, fileNm := filepath.Split(fileName) 205 part, err := w.CreateFormFile("file", filepath.Base(fileName)) 206 if err != nil { 207 return nil, err 208 } 209 _, err = part.Write(fileBytes) 210 if err != nil { 211 return nil, err 212 } 213 // Set the Boundary in the Content-Type 214 headerParams["Content-Type"] = w.FormDataContentType() 215 } 216 217 // Set Content-Length 218 headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) 219 w.Close() 220 } 221 222 // Setup path and query parameters 223 url, err := url.Parse(path) 224 if err != nil { 225 return nil, err 226 } 227 228 // Adding Query Param 229 query := url.Query() 230 for k, v := range queryParams { 231 for _, iv := range v { 232 query.Add(k, iv) 233 } 234 } 235 236 // Encode the parameters. 237 url.RawQuery = query.Encode() 238 239 // Generate a new request 240 if body != nil { 241 localVarRequest, err = http.NewRequest(method, url.String(), body) 242 } else { 243 localVarRequest, err = http.NewRequest(method, url.String(), nil) 244 } 245 if err != nil { 246 return nil, err 247 } 248 249 // add header parameters, if any 250 if len(headerParams) > 0 { 251 headers := http.Header{} 252 for h, v := range headerParams { 253 headers.Set(h, v) 254 } 255 localVarRequest.Header = headers 256 } 257 258 // Override request host, if applicable 259 if c.cfg.Host != "" { 260 localVarRequest.Host = c.cfg.Host 261 } 262 263 // Add the user agent to the request. 264 localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) 265 266 // APIKey Authentication 267 if auth := c.cfg.GetCredentials(); auth != nil { 268 timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10) 269 signer := hmac.NewSigner(auth.SecretKey(), crypto.SHA256) 270 signature, _ := signer.Sign(method, path, auth.AccessKey(), timestamp) 271 272 localVarRequest.Header.Add("x-ncp-apigw-timestamp", timestamp) 273 localVarRequest.Header.Add("x-ncp-iam-access-key", auth.AccessKey()) 274 localVarRequest.Header.Add("x-ncp-apigw-signature-v1", signature) 275 } 276 277 for header, value := range c.cfg.DefaultHeader { 278 localVarRequest.Header.Add(header, value) 279 } 280 281 return localVarRequest, nil 282 } 283 284 // Add a file to the multipart request 285 func addFile(w *multipart.Writer, fieldName, path string) error { 286 file, err := os.Open(path) 287 if err != nil { 288 return err 289 } 290 defer file.Close() 291 292 part, err := w.CreateFormFile(fieldName, filepath.Base(path)) 293 if err != nil { 294 return err 295 } 296 _, err = io.Copy(part, file) 297 298 return err 299 } 300 301 // Prevent trying to import "fmt" 302 func reportError(format string, a ...interface{}) error { 303 return fmt.Errorf(format, a...) 304 } 305 306 func toLowerFirstChar(s string) string { 307 a := []rune(s) 308 a[0] = unicode.ToLower(a[0]) 309 return string(a) 310 } 311 312 // Set request body from an interface{} 313 func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { 314 if bodyBuf == nil { 315 bodyBuf = &bytes.Buffer{} 316 } 317 318 bodyBuf.WriteString("responseFormatType=json") 319 s := reflect.ValueOf(body).Elem() 320 bodyBuf.WriteString(buildQueryString(s, "")) 321 322 if err != nil { 323 return nil, err 324 } 325 326 if bodyBuf.Len() == 0 { 327 err = fmt.Errorf("invalid body type %s", contentType) 328 return nil, err 329 } 330 return bodyBuf, nil 331 } 332 333 func buildQueryString(s reflect.Value, prefix string) string { 334 bodyBuf := &bytes.Buffer{} 335 if s.Kind() == reflect.Struct { 336 for i := 0; i < s.NumField(); i++ { 337 f := s.Field(i) 338 if !f.IsNil() { 339 name := toLowerFirstChar(s.Type().Field(i).Name) 340 if len(prefix) > 0 { 341 bodyBuf.WriteString(buildQueryString(f, fmt.Sprintf("%s.%s", prefix, name))) 342 } else { 343 bodyBuf.WriteString(buildQueryString(f, name)) 344 } 345 } 346 } 347 } else if s.Kind() == reflect.Slice { 348 for i := 0; i < s.Len(); i++ { 349 item := s.Index(i) 350 bodyBuf.WriteString(buildQueryString(item.Elem(), fmt.Sprintf("%s.%d", prefix, i+1))) 351 } 352 } else if s.Kind() == reflect.Ptr { 353 bodyBuf.WriteString(fmt.Sprintf("&%s=%s", prefix, convertToString(s))) 354 } else if s.Kind() == reflect.String { 355 bodyBuf.WriteString(fmt.Sprintf("&%s=%s", prefix, s.Interface())) 356 } 357 358 return bodyBuf.String() 359 } 360 361 func convertToString(f reflect.Value) string { 362 switch f.Type().String() { 363 case "*string": 364 return url.QueryEscape(ncloud.StringValue(f.Interface().(*string))) 365 case "*bool": 366 return fmt.Sprintf("%t", *f.Interface().(*bool)) 367 case "*int": 368 return fmt.Sprintf("%d", *f.Interface().(*int)) 369 case "*int32": 370 return fmt.Sprintf("%d", *f.Interface().(*int32)) 371 case "*int64": 372 return fmt.Sprintf("%d", *f.Interface().(*int64)) 373 case "*float32": 374 return fmt.Sprintf("%f", *f.Interface().(*float32)) 375 } 376 return "" 377 } 378 379 // detectContentType method is used to figure out `Request.Body` content type for request header 380 func detectContentType(body interface{}) string { 381 contentType := "text/plain; charset=utf-8" 382 kind := reflect.TypeOf(body).Kind() 383 384 switch kind { 385 case reflect.Struct, reflect.Map, reflect.Ptr: 386 contentType = "application/json; charset=utf-8" 387 case reflect.String: 388 contentType = "text/plain; charset=utf-8" 389 default: 390 if b, ok := body.([]byte); ok { 391 contentType = http.DetectContentType(b) 392 } else if kind == reflect.Slice { 393 contentType = "application/json; charset=utf-8" 394 } 395 } 396 397 return contentType 398 } 399 400 // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go 401 type cacheControl map[string]string 402 403 func parseCacheControl(headers http.Header) cacheControl { 404 cc := cacheControl{} 405 ccHeader := headers.Get("Cache-Control") 406 for _, part := range strings.Split(ccHeader, ",") { 407 part = strings.Trim(part, " ") 408 if part == "" { 409 continue 410 } 411 if strings.ContainsRune(part, '=') { 412 keyval := strings.Split(part, "=") 413 cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") 414 } else { 415 cc[part] = "" 416 } 417 } 418 return cc 419 } 420 421 // CacheExpires helper function to determine remaining time before repeating a request. 422 func CacheExpires(r *http.Response) time.Time { 423 // Figure out when the cache expires. 424 var expires time.Time 425 now, err := time.Parse(time.RFC1123, r.Header.Get("date")) 426 if err != nil { 427 return time.Now() 428 } 429 respCacheControl := parseCacheControl(r.Header) 430 431 if maxAge, ok := respCacheControl["max-age"]; ok { 432 lifetime, err := time.ParseDuration(maxAge + "s") 433 if err != nil { 434 expires = now 435 } 436 expires = now.Add(lifetime) 437 } else { 438 expiresHeader := r.Header.Get("Expires") 439 if expiresHeader != "" { 440 expires, err = time.Parse(time.RFC1123, expiresHeader) 441 if err != nil { 442 expires = now 443 } 444 } 445 } 446 return expires 447 } 448 449 func strlen(s string) int { 450 return utf8.RuneCountInString(s) 451 }