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