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

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