agones.dev/agones@v1.53.0/test/sdk/restapi/alpha/swagger/client.go (about)

     1  // Copyright 2024 Google LLC All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // This code was autogenerated. Do not edit directly.
    16  /*
    17   * alpha.proto
    18   *
    19   * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
    20   *
    21   * API version: version not set
    22   * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
    23   */
    24  package swagger
    25  
    26  import (
    27  	"bytes"
    28  	"context"
    29  	"encoding/json"
    30  	"encoding/xml"
    31  	"errors"
    32  	"fmt"
    33  	"io"
    34  	"mime/multipart"
    35  	"net/http"
    36  	"net/url"
    37  	"os"
    38  	"path/filepath"
    39  	"reflect"
    40  	"regexp"
    41  	"strconv"
    42  	"strings"
    43  	"time"
    44  	"unicode/utf8"
    45  
    46  	"golang.org/x/oauth2"
    47  )
    48  
    49  var (
    50  	jsonCheck = regexp.MustCompile("(?i:[application|text]/json)")
    51  	xmlCheck  = regexp.MustCompile("(?i:[application|text]/xml)")
    52  )
    53  
    54  // APIClient manages communication with the alpha.proto API vversion not set
    55  // In most cases there should be only one, shared, APIClient.
    56  type APIClient struct {
    57  	cfg    *Configuration
    58  	common service // Reuse a single struct instead of allocating one for each service on the heap.
    59  
    60  	// API Services
    61  
    62  	SDKApi *SDKApiService
    63  }
    64  
    65  type service struct {
    66  	client *APIClient
    67  }
    68  
    69  // NewAPIClient creates a new API client. Requires a userAgent string describing your application.
    70  // optionally a custom http.Client to allow for advanced features such as caching.
    71  func NewAPIClient(cfg *Configuration) *APIClient {
    72  	if cfg.HTTPClient == nil {
    73  		cfg.HTTPClient = http.DefaultClient
    74  	}
    75  
    76  	c := &APIClient{}
    77  	c.cfg = cfg
    78  	c.common.client = c
    79  
    80  	// API Services
    81  	c.SDKApi = (*SDKApiService)(&c.common)
    82  
    83  	return c
    84  }
    85  
    86  func atoi(in string) (int, error) {
    87  	return strconv.Atoi(in)
    88  }
    89  
    90  // selectHeaderContentType select a content type from the available list.
    91  func selectHeaderContentType(contentTypes []string) string {
    92  	if len(contentTypes) == 0 {
    93  		return ""
    94  	}
    95  	if contains(contentTypes, "application/json") {
    96  		return "application/json"
    97  	}
    98  	return contentTypes[0] // use the first content type specified in 'consumes'
    99  }
   100  
   101  // selectHeaderAccept join all accept types and return
   102  func selectHeaderAccept(accepts []string) string {
   103  	if len(accepts) == 0 {
   104  		return ""
   105  	}
   106  
   107  	if contains(accepts, "application/json") {
   108  		return "application/json"
   109  	}
   110  
   111  	return strings.Join(accepts, ",")
   112  }
   113  
   114  // contains is a case insenstive match, finding needle in a haystack
   115  func contains(haystack []string, needle string) bool {
   116  	for _, a := range haystack {
   117  		if strings.ToLower(a) == strings.ToLower(needle) {
   118  			return true
   119  		}
   120  	}
   121  	return false
   122  }
   123  
   124  // Verify optional parameters are of the correct type.
   125  func typeCheckParameter(obj interface{}, expected string, name string) error {
   126  	// Make sure there is an object.
   127  	if obj == nil {
   128  		return nil
   129  	}
   130  
   131  	// Check the type is as expected.
   132  	if reflect.TypeOf(obj).String() != expected {
   133  		return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String())
   134  	}
   135  	return nil
   136  }
   137  
   138  // parameterToString convert interface{} parameters to string, using a delimiter if format is provided.
   139  func parameterToString(obj interface{}, collectionFormat string) string {
   140  	var delimiter string
   141  
   142  	switch collectionFormat {
   143  	case "pipes":
   144  		delimiter = "|"
   145  	case "ssv":
   146  		delimiter = " "
   147  	case "tsv":
   148  		delimiter = "\t"
   149  	case "csv":
   150  		delimiter = ","
   151  	}
   152  
   153  	if reflect.TypeOf(obj).Kind() == reflect.Slice {
   154  		return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]")
   155  	}
   156  
   157  	return fmt.Sprintf("%v", obj)
   158  }
   159  
   160  // callAPI do the request.
   161  func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
   162  	return c.cfg.HTTPClient.Do(request)
   163  }
   164  
   165  // Change base path to allow switching to mocks
   166  func (c *APIClient) ChangeBasePath(path string) {
   167  	c.cfg.BasePath = path
   168  }
   169  
   170  // prepareRequest build the request
   171  func (c *APIClient) prepareRequest(
   172  	ctx context.Context,
   173  	path string, method string,
   174  	postBody interface{},
   175  	headerParams map[string]string,
   176  	queryParams url.Values,
   177  	formParams url.Values,
   178  	fileName string,
   179  	fileBytes []byte) (localVarRequest *http.Request, err error) {
   180  
   181  	var body *bytes.Buffer
   182  
   183  	// Detect postBody type and post.
   184  	if postBody != nil {
   185  		contentType := headerParams["Content-Type"]
   186  		if contentType == "" {
   187  			contentType = detectContentType(postBody)
   188  			headerParams["Content-Type"] = contentType
   189  		}
   190  
   191  		body, err = setBody(postBody, contentType)
   192  		if err != nil {
   193  			return nil, err
   194  		}
   195  	}
   196  
   197  	// add form parameters and file if available.
   198  	if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") {
   199  		if body != nil {
   200  			return nil, errors.New("Cannot specify postBody and multipart form at the same time.")
   201  		}
   202  		body = &bytes.Buffer{}
   203  		w := multipart.NewWriter(body)
   204  
   205  		for k, v := range formParams {
   206  			for _, iv := range v {
   207  				if strings.HasPrefix(k, "@") { // file
   208  					err = addFile(w, k[1:], iv)
   209  					if err != nil {
   210  						return nil, err
   211  					}
   212  				} else { // form value
   213  					w.WriteField(k, iv)
   214  				}
   215  			}
   216  		}
   217  		if len(fileBytes) > 0 && fileName != "" {
   218  			w.Boundary()
   219  			//_, fileNm := filepath.Split(fileName)
   220  			part, err := w.CreateFormFile("file", filepath.Base(fileName))
   221  			if err != nil {
   222  				return nil, err
   223  			}
   224  			_, err = part.Write(fileBytes)
   225  			if err != nil {
   226  				return nil, err
   227  			}
   228  			// Set the Boundary in the Content-Type
   229  			headerParams["Content-Type"] = w.FormDataContentType()
   230  		}
   231  
   232  		// Set Content-Length
   233  		headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
   234  		w.Close()
   235  	}
   236  
   237  	if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 {
   238  		if body != nil {
   239  			return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.")
   240  		}
   241  		body = &bytes.Buffer{}
   242  		body.WriteString(formParams.Encode())
   243  		// Set Content-Length
   244  		headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
   245  	}
   246  
   247  	// Setup path and query parameters
   248  	url, err := url.Parse(path)
   249  	if err != nil {
   250  		return nil, err
   251  	}
   252  
   253  	// Adding Query Param
   254  	query := url.Query()
   255  	for k, v := range queryParams {
   256  		for _, iv := range v {
   257  			query.Add(k, iv)
   258  		}
   259  	}
   260  
   261  	// Encode the parameters.
   262  	url.RawQuery = query.Encode()
   263  
   264  	// Generate a new request
   265  	if body != nil {
   266  		localVarRequest, err = http.NewRequest(method, url.String(), body)
   267  	} else {
   268  		localVarRequest, err = http.NewRequest(method, url.String(), nil)
   269  	}
   270  	if err != nil {
   271  		return nil, err
   272  	}
   273  
   274  	// add header parameters, if any
   275  	if len(headerParams) > 0 {
   276  		headers := http.Header{}
   277  		for h, v := range headerParams {
   278  			headers.Set(h, v)
   279  		}
   280  		localVarRequest.Header = headers
   281  	}
   282  
   283  	// Override request host, if applicable
   284  	if c.cfg.Host != "" {
   285  		localVarRequest.Host = c.cfg.Host
   286  	}
   287  
   288  	// Add the user agent to the request.
   289  	localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent)
   290  
   291  	if ctx != nil {
   292  		// add context to the request
   293  		localVarRequest = localVarRequest.WithContext(ctx)
   294  
   295  		// Walk through any authentication.
   296  
   297  		// OAuth2 authentication
   298  		if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok {
   299  			// We were able to grab an oauth2 token from the context
   300  			var latestToken *oauth2.Token
   301  			if latestToken, err = tok.Token(); err != nil {
   302  				return nil, err
   303  			}
   304  
   305  			latestToken.SetAuthHeader(localVarRequest)
   306  		}
   307  
   308  		// Basic HTTP Authentication
   309  		if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok {
   310  			localVarRequest.SetBasicAuth(auth.UserName, auth.Password)
   311  		}
   312  
   313  		// AccessToken Authentication
   314  		if auth, ok := ctx.Value(ContextAccessToken).(string); ok {
   315  			localVarRequest.Header.Add("Authorization", "Bearer "+auth)
   316  		}
   317  	}
   318  
   319  	for header, value := range c.cfg.DefaultHeader {
   320  		localVarRequest.Header.Add(header, value)
   321  	}
   322  
   323  	return localVarRequest, nil
   324  }
   325  
   326  func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) {
   327  		if strings.Contains(contentType, "application/xml") {
   328  			if err = xml.Unmarshal(b, v); err != nil {
   329  				return err
   330  			}
   331  			return nil
   332  		} else if strings.Contains(contentType, "application/json") {
   333  			if err = json.Unmarshal(b, v); err != nil {
   334  				return err
   335  			}
   336  			return nil
   337  		}
   338  	return errors.New("undefined response type")
   339  }
   340  
   341  // Add a file to the multipart request
   342  func addFile(w *multipart.Writer, fieldName, path string) error {
   343  	file, err := os.Open(path)
   344  	if err != nil {
   345  		return err
   346  	}
   347  	defer file.Close()
   348  
   349  	part, err := w.CreateFormFile(fieldName, filepath.Base(path))
   350  	if err != nil {
   351  		return err
   352  	}
   353  	_, err = io.Copy(part, file)
   354  
   355  	return err
   356  }
   357  
   358  // Prevent trying to import "fmt"
   359  func reportError(format string, a ...interface{}) error {
   360  	return fmt.Errorf(format, a...)
   361  }
   362  
   363  // Set request body from an interface{}
   364  func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) {
   365  	if bodyBuf == nil {
   366  		bodyBuf = &bytes.Buffer{}
   367  	}
   368  
   369  	if reader, ok := body.(io.Reader); ok {
   370  		_, err = bodyBuf.ReadFrom(reader)
   371  	} else if b, ok := body.([]byte); ok {
   372  		_, err = bodyBuf.Write(b)
   373  	} else if s, ok := body.(string); ok {
   374  		_, err = bodyBuf.WriteString(s)
   375  	} else if s, ok := body.(*string); ok {
   376  		_, err = bodyBuf.WriteString(*s)
   377  	} else if jsonCheck.MatchString(contentType) {
   378  		err = json.NewEncoder(bodyBuf).Encode(body)
   379  	} else if xmlCheck.MatchString(contentType) {
   380  		xml.NewEncoder(bodyBuf).Encode(body)
   381  	}
   382  
   383  	if err != nil {
   384  		return nil, err
   385  	}
   386  
   387  	if bodyBuf.Len() == 0 {
   388  		err = fmt.Errorf("Invalid body type %s\n", contentType)
   389  		return nil, err
   390  	}
   391  	return bodyBuf, nil
   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  }