github.com/free5gc/openapi@v1.0.8/Npcf_UEPolicy/client.go (about)

     1  /*
     2   * Npcf_UEPolicyControl
     3   *
     4   * UE Policy Control Service API
     5   *
     6   * API version: 1.0.0
     7   * Generated by: OpenAPI Generator (https://openapi-generator.tech)
     8   */
     9  
    10  package Npcf_UEPolicy
    11  
    12  import (
    13  	"bytes"
    14  	"context"
    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/utf8"
    31  
    32  	"golang.org/x/oauth2"
    33  )
    34  
    35  var (
    36  	jsonCheck = regexp.MustCompile("(?i:[application|text]/json)")
    37  	xmlCheck  = regexp.MustCompile("(?i:[application|text]/xml)")
    38  )
    39  
    40  // APIClient manages communication with the Npcf_UEPolicyControl API v1.0.0
    41  // In most cases there should be only one, shared, APIClient.
    42  type APIClient struct {
    43  	cfg    *Configuration
    44  	common service // Reuse a single struct instead of allocating one for each service on the heap.
    45  
    46  	// API Services
    47  
    48  	DefaultApi *DefaultApiService
    49  }
    50  
    51  type service struct {
    52  	client *APIClient
    53  }
    54  
    55  // NewAPIClient creates a new API client. Requires a userAgent string describing your application.
    56  // optionally a custom http.Client to allow for advanced features such as caching.
    57  func NewAPIClient(cfg *Configuration) *APIClient {
    58  	c := &APIClient{}
    59  	c.cfg = cfg
    60  	c.common.client = c
    61  
    62  	// API Services
    63  	c.DefaultApi = (*DefaultApiService)(&c.common)
    64  
    65  	return c
    66  }
    67  
    68  func atoi(in string) (int, error) {
    69  	return strconv.Atoi(in)
    70  }
    71  
    72  // selectHeaderContentType select a content type from the available list.
    73  func selectHeaderContentType(contentTypes []string) string {
    74  	if len(contentTypes) == 0 {
    75  		return ""
    76  	}
    77  	if contains(contentTypes, "application/json") {
    78  		return "application/json"
    79  	}
    80  	return contentTypes[0] // use the first content type specified in 'consumes'
    81  }
    82  
    83  // selectHeaderAccept join all accept types and return
    84  func selectHeaderAccept(accepts []string) string {
    85  	if len(accepts) == 0 {
    86  		return ""
    87  	}
    88  
    89  	if contains(accepts, "application/json") {
    90  		return "application/json"
    91  	}
    92  
    93  	return strings.Join(accepts, ",")
    94  }
    95  
    96  // contains is a case insenstive match, finding needle in a haystack
    97  func contains(haystack []string, needle string) bool {
    98  	for _, a := range haystack {
    99  		if strings.EqualFold(a, needle) {
   100  			return true
   101  		}
   102  	}
   103  	return false
   104  }
   105  
   106  // Verify optional parameters are of the correct type.
   107  func typeCheckParameter(obj interface{}, expected string, name string) error {
   108  	// Make sure there is an object.
   109  	if obj == nil {
   110  		return nil
   111  	}
   112  
   113  	// Check the type is as expected.
   114  	if reflect.TypeOf(obj).String() != expected {
   115  		return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String())
   116  	}
   117  	return nil
   118  }
   119  
   120  // parameterToString convert interface{} parameters to string, using a delimiter if format is provided.
   121  func parameterToString(obj interface{}, collectionFormat string) string {
   122  	var delimiter string
   123  
   124  	switch collectionFormat {
   125  	case "pipes":
   126  		delimiter = "|"
   127  	case "ssv":
   128  		delimiter = " "
   129  	case "tsv":
   130  		delimiter = "\t"
   131  	case "csv":
   132  		delimiter = ","
   133  	}
   134  
   135  	if reflect.TypeOf(obj).Kind() == reflect.Slice {
   136  		return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]")
   137  	} else if t, ok := obj.(time.Time); ok {
   138  		return t.Format(time.RFC3339)
   139  	}
   140  
   141  	return fmt.Sprintf("%v", obj)
   142  }
   143  
   144  // callAPI do the request.
   145  func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
   146  	return c.cfg.httpClient.Do(request)
   147  }
   148  
   149  // Change base path to allow switching to mocks
   150  func (c *APIClient) ChangeBasePath(path string) {
   151  	c.cfg.basePath = path
   152  }
   153  
   154  // prepareRequest build the request
   155  func (c *APIClient) prepareRequest(
   156  	ctx context.Context,
   157  	path string, method string,
   158  	postBody interface{},
   159  	headerParams map[string]string,
   160  	queryParams url.Values,
   161  	formParams url.Values,
   162  	formFileName string,
   163  	fileName string,
   164  	fileBytes []byte,
   165  ) (localVarRequest *http.Request, err error) {
   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 strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && 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(formFileName, 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  	if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 {
   223  		if body != nil {
   224  			return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.")
   225  		}
   226  		body = &bytes.Buffer{}
   227  		body.WriteString(formParams.Encode())
   228  		// Set Content-Length
   229  		headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
   230  	}
   231  
   232  	// Setup path and query parameters
   233  	url, err := url.Parse(path)
   234  	if err != nil {
   235  		return nil, err
   236  	}
   237  
   238  	// Adding Query Param
   239  	query := url.Query()
   240  	for k, v := range queryParams {
   241  		for _, iv := range v {
   242  			query.Add(k, iv)
   243  		}
   244  	}
   245  
   246  	// Encode the parameters.
   247  	url.RawQuery = query.Encode()
   248  
   249  	// Generate a new request
   250  	if body != nil {
   251  		localVarRequest, err = http.NewRequest(method, url.String(), body)
   252  	} else {
   253  		localVarRequest, err = http.NewRequest(method, url.String(), nil)
   254  	}
   255  	if err != nil {
   256  		return nil, err
   257  	}
   258  
   259  	// add header parameters, if any
   260  	if len(headerParams) > 0 {
   261  		headers := http.Header{}
   262  		for h, v := range headerParams {
   263  			headers.Set(h, v)
   264  		}
   265  		localVarRequest.Header = headers
   266  	}
   267  
   268  	// Override request host, if applicable
   269  	if c.cfg.host != "" {
   270  		localVarRequest.Host = c.cfg.host
   271  	}
   272  
   273  	// Add the user agent to the request.
   274  	localVarRequest.Header.Add("User-Agent", c.cfg.userAgent)
   275  
   276  	if ctx != nil {
   277  		// add context to the request
   278  		localVarRequest = localVarRequest.WithContext(ctx)
   279  
   280  		// Walk through any authentication.
   281  
   282  		// OAuth2 authentication
   283  		if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok {
   284  			// We were able to grab an oauth2 token from the context
   285  			var latestToken *oauth2.Token
   286  			if latestToken, err = tok.Token(); err != nil {
   287  				return nil, err
   288  			}
   289  
   290  			latestToken.SetAuthHeader(localVarRequest)
   291  		}
   292  
   293  		// Basic HTTP Authentication
   294  		if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok {
   295  			localVarRequest.SetBasicAuth(auth.UserName, auth.Password)
   296  		}
   297  
   298  		// AccessToken Authentication
   299  		if auth, ok := ctx.Value(ContextAccessToken).(string); ok {
   300  			localVarRequest.Header.Add("Authorization", "Bearer "+auth)
   301  		}
   302  	}
   303  
   304  	for header, value := range c.cfg.defaultHeader {
   305  		localVarRequest.Header.Add(header, value)
   306  	}
   307  
   308  	return localVarRequest, nil
   309  }
   310  
   311  func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) {
   312  	if strings.Contains(contentType, "application/xml") {
   313  		if err = xml.Unmarshal(b, v); err != nil {
   314  			return err
   315  		}
   316  		return nil
   317  	} else if strings.Contains(contentType, "application/json") {
   318  		if err = json.Unmarshal(b, v); err != nil {
   319  			return err
   320  		}
   321  		return nil
   322  	}
   323  	return errors.New("undefined response type")
   324  }
   325  
   326  // Add a file to the multipart request
   327  func addFile(w *multipart.Writer, fieldName, path string) error {
   328  	file, err := os.Open(path)
   329  	if err != nil {
   330  		return err
   331  	}
   332  	defer file.Close()
   333  
   334  	part, err := w.CreateFormFile(fieldName, filepath.Base(path))
   335  	if err != nil {
   336  		return err
   337  	}
   338  	_, err = io.Copy(part, file)
   339  
   340  	return err
   341  }
   342  
   343  // Prevent trying to import "fmt"
   344  func reportError(format string, a ...interface{}) error {
   345  	return fmt.Errorf(format, a...)
   346  }
   347  
   348  // Set request body from an interface{}
   349  func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) {
   350  	if bodyBuf == nil {
   351  		bodyBuf = &bytes.Buffer{}
   352  	}
   353  
   354  	if reader, ok := body.(io.Reader); ok {
   355  		_, err = bodyBuf.ReadFrom(reader)
   356  	} else if b, ok := body.([]byte); ok {
   357  		_, err = bodyBuf.Write(b)
   358  	} else if s, ok := body.(string); ok {
   359  		_, err = bodyBuf.WriteString(s)
   360  	} else if s, ok := body.(*string); ok {
   361  		_, err = bodyBuf.WriteString(*s)
   362  	} else if jsonCheck.MatchString(contentType) {
   363  		err = json.NewEncoder(bodyBuf).Encode(body)
   364  	} else if xmlCheck.MatchString(contentType) {
   365  		xml.NewEncoder(bodyBuf).Encode(body)
   366  	}
   367  
   368  	if err != nil {
   369  		return nil, err
   370  	}
   371  
   372  	if bodyBuf.Len() == 0 {
   373  		err = fmt.Errorf("Invalid body type %s\n", contentType)
   374  		return nil, err
   375  	}
   376  	return bodyBuf, nil
   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  		} else {
   436  			expires = now.Add(lifetime)
   437  		}
   438  	} else {
   439  		expiresHeader := r.Header.Get("Expires")
   440  		if expiresHeader != "" {
   441  			expires, err = time.Parse(time.RFC1123, expiresHeader)
   442  			if err != nil {
   443  				expires = now
   444  			}
   445  		}
   446  	}
   447  	return expires
   448  }
   449  
   450  func strlen(s string) int {
   451  	return utf8.RuneCountInString(s)
   452  }
   453  
   454  // GenericOpenAPIError Provides access to the body, error and model on returned errors.
   455  type GenericOpenAPIError struct {
   456  	body  []byte
   457  	error string
   458  	model interface{}
   459  }
   460  
   461  // Error returns non-empty string if there was an error.
   462  func (e GenericOpenAPIError) Error() string {
   463  	return e.error
   464  }
   465  
   466  // Body returns the raw bytes of the response
   467  func (e GenericOpenAPIError) Body() []byte {
   468  	return e.body
   469  }
   470  
   471  // Model returns the unpacked model of the error
   472  func (e GenericOpenAPIError) Model() interface{} {
   473  	return e.model
   474  }