github.com/NaverCloudPlatform/ncloud-sdk-go-v2@v1.6.13/services/vsourcepipeline/api_client.go (about)

     1  /*
     2   * vsourcepipeline
     3   *
     4   * <br/>https://vpcsourcepipeline.apigw.ntruss.com/api/v1
     5   *
     6   * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
     7   */
     8  
     9  package vsourcepipeline
    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 sourcepipeline API v2022-04-22T07:37:23Z
    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  	// APIKey Authentication
   271  	if auth := c.cfg.GetCredentials(); auth != nil {
   272  		timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
   273  		signer := hmac.NewSigner(auth.SecretKey(), crypto.SHA256)
   274  		signature, _ := signer.Sign(method, path, auth.AccessKey(), timestamp)
   275  
   276  		localVarRequest.Header.Add("x-ncp-apigw-timestamp", timestamp)
   277  		localVarRequest.Header.Add("x-ncp-iam-access-key", auth.AccessKey())
   278  		localVarRequest.Header.Add("x-ncp-apigw-signature-v1", signature)
   279  	}
   280  
   281  	if ctx != nil {
   282  		// add context to the request
   283  		localVarRequest = localVarRequest.WithContext(ctx)
   284  	}
   285  
   286  	for header, value := range c.cfg.DefaultHeader {
   287  		localVarRequest.Header.Add(header, value)
   288  	}
   289  
   290  	return localVarRequest, nil
   291  }
   292  
   293  // Add a file to the multipart request
   294  func addFile(w *multipart.Writer, fieldName, path string) error {
   295  	file, err := os.Open(path)
   296  	if err != nil {
   297  		return err
   298  	}
   299  	defer file.Close()
   300  
   301  	part, err := w.CreateFormFile(fieldName, filepath.Base(path))
   302  	if err != nil {
   303  		return err
   304  	}
   305  	_, err = io.Copy(part, file)
   306  
   307  	return err
   308  }
   309  
   310  // Prevent trying to import "fmt"
   311  func reportError(format string, a ...interface{}) error {
   312  	return fmt.Errorf(format, a...)
   313  }
   314  
   315  func toLowerFirstChar(s string) string {
   316  	a := []rune(s)
   317  	a[0] = unicode.ToLower(a[0])
   318  	return string(a)
   319  }
   320  
   321  // Set request body from an interface{}
   322  func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) {
   323  	if bodyBuf == nil {
   324  		bodyBuf = &bytes.Buffer{}
   325  	}
   326  
   327  	if reader, ok := body.(io.Reader); ok {
   328  		_, err = bodyBuf.ReadFrom(reader)
   329  	} else if b, ok := body.([]byte); ok {
   330  		_, err = bodyBuf.Write(b)
   331  	} else if s, ok := body.(string); ok {
   332  		_, err = bodyBuf.WriteString(s)
   333  	} else if s, ok := body.(*string); ok {
   334  		_, err = bodyBuf.WriteString(*s)
   335  	} else if jsonCheck.MatchString(contentType) {
   336  		err = json.NewEncoder(bodyBuf).Encode(body)
   337  	} else if xmlCheck.MatchString(contentType) {
   338  		xml.NewEncoder(bodyBuf).Encode(body)
   339  	}
   340  	if err != nil {
   341  		return nil, err
   342  	}
   343  
   344  	if bodyBuf.Len() == 0 {
   345  		err = fmt.Errorf("invalid body type %s", contentType)
   346  		return nil, err
   347  	}
   348  	return bodyBuf, nil
   349  }
   350  
   351  func buildQueryString(s reflect.Value, prefix string) string {
   352  	bodyBuf := &bytes.Buffer{}
   353  	if s.Kind() == reflect.Struct {
   354  		for i := 0; i < s.NumField(); i++ {
   355  			f := s.Field(i)
   356  			if !f.IsNil() {
   357  				name := toLowerFirstChar(s.Type().Field(i).Name)
   358  				if len(prefix) > 0 {
   359  					bodyBuf.WriteString(buildQueryString(f, fmt.Sprintf("%s.%s", prefix, name)))
   360  				} else {
   361  					bodyBuf.WriteString(buildQueryString(f, name))
   362  				}
   363  			}
   364  		}
   365  	} else if s.Kind() == reflect.Slice {
   366  		for i := 0; i < s.Len(); i++ {
   367  			item := s.Index(i)
   368  			bodyBuf.WriteString(buildQueryString(item.Elem(), fmt.Sprintf("%s.%d", prefix, i+1)))
   369  		}
   370  	} else if s.Kind() == reflect.Ptr {
   371  		bodyBuf.WriteString(fmt.Sprintf("&%s=%s", prefix, convertToString(s)))
   372  	} else if s.Kind() == reflect.String {
   373  		bodyBuf.WriteString(fmt.Sprintf("&%s=%s", prefix, s.Interface()))
   374  	}
   375  
   376  	return bodyBuf.String()
   377  }
   378  
   379  func convertToString(f reflect.Value) string {
   380  	switch f.Type().String() {
   381  	case "*string":
   382  		return url.QueryEscape(ncloud.StringValue(f.Interface().(*string)))
   383  	case "*bool":
   384  		return fmt.Sprintf("%t", *f.Interface().(*bool))
   385  	case "*int":
   386  		return fmt.Sprintf("%d", *f.Interface().(*int))
   387  	case "*int32":
   388  		return fmt.Sprintf("%d", *f.Interface().(*int32))
   389  	case "*int64":
   390  		return fmt.Sprintf("%d", *f.Interface().(*int64))
   391  	case "*float32":
   392  		return fmt.Sprintf("%f", *f.Interface().(*float32))
   393  	}
   394  	return ""
   395  }
   396  
   397  // detectContentType method is used to figure out `Request.Body` content type for request header
   398  func detectContentType(body interface{}) string {
   399  	contentType := "text/plain; charset=utf-8"
   400  	kind := reflect.TypeOf(body).Kind()
   401  
   402  	switch kind {
   403  	case reflect.Struct, reflect.Map, reflect.Ptr:
   404  		contentType = "application/json; charset=utf-8"
   405  	case reflect.String:
   406  		contentType = "text/plain; charset=utf-8"
   407  	default:
   408  		if b, ok := body.([]byte); ok {
   409  			contentType = http.DetectContentType(b)
   410  		} else if kind == reflect.Slice {
   411  			contentType = "application/json; charset=utf-8"
   412  		}
   413  	}
   414  
   415  	return contentType
   416  }
   417  
   418  // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go
   419  type cacheControl map[string]string
   420  
   421  func parseCacheControl(headers http.Header) cacheControl {
   422  	cc := cacheControl{}
   423  	ccHeader := headers.Get("Cache-Control")
   424  	for _, part := range strings.Split(ccHeader, ",") {
   425  		part = strings.Trim(part, " ")
   426  		if part == "" {
   427  			continue
   428  		}
   429  		if strings.ContainsRune(part, '=') {
   430  			keyval := strings.Split(part, "=")
   431  			cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",")
   432  		} else {
   433  			cc[part] = ""
   434  		}
   435  	}
   436  	return cc
   437  }
   438  
   439  // CacheExpires helper function to determine remaining time before repeating a request.
   440  func CacheExpires(r *http.Response) time.Time {
   441  	// Figure out when the cache expires.
   442  	var expires time.Time
   443  	now, err := time.Parse(time.RFC1123, r.Header.Get("date"))
   444  	if err != nil {
   445  		return time.Now()
   446  	}
   447  	respCacheControl := parseCacheControl(r.Header)
   448  
   449  	if maxAge, ok := respCacheControl["max-age"]; ok {
   450  		lifetime, err := time.ParseDuration(maxAge + "s")
   451  		if err != nil {
   452  			expires = now
   453  		}
   454  		expires = now.Add(lifetime)
   455  	} else {
   456  		expiresHeader := r.Header.Get("Expires")
   457  		if expiresHeader != "" {
   458  			expires, err = time.Parse(time.RFC1123, expiresHeader)
   459  			if err != nil {
   460  				expires = now
   461  			}
   462  		}
   463  	}
   464  	return expires
   465  }
   466  
   467  func strlen(s string) int {
   468  	return utf8.RuneCountInString(s)
   469  }