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

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