github.com/antihax/goesi@v0.0.0-20240126031043-6c54d0cb7f95/meta/client.go (about)

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