github.com/moov-io/imagecashletter@v0.10.1/client/client.go (about)

     1  /*
     2   * ImageCashLetter API
     3   *
     4   * Moov Image Cash Letter (ICL) implements an HTTP API for creating, parsing, and validating ImageCashLetter files.
     5   *
     6   * API version: v1
     7   * Generated by: OpenAPI Generator (https://openapi-generator.tech)
     8   */
     9  
    10  package openapi
    11  
    12  import (
    13  	"bytes"
    14  	"context"
    15  	"encoding/json"
    16  	"encoding/xml"
    17  	"errors"
    18  	"fmt"
    19  	"io"
    20  	"io/ioutil"
    21  	"log"
    22  	"mime/multipart"
    23  	"net/http"
    24  	"net/http/httputil"
    25  	"net/url"
    26  	"os"
    27  	"path/filepath"
    28  	"reflect"
    29  	"regexp"
    30  	"strconv"
    31  	"strings"
    32  	"time"
    33  	"unicode/utf8"
    34  
    35  	"golang.org/x/oauth2"
    36  )
    37  
    38  var (
    39  	jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`)
    40  	xmlCheck  = regexp.MustCompile(`(?i:(?:application|text)/xml)`)
    41  )
    42  
    43  // APIClient manages communication with the ImageCashLetter API API vv1
    44  // In most cases there should be only one, shared, APIClient.
    45  type APIClient struct {
    46  	cfg    *Configuration
    47  	common service // Reuse a single struct instead of allocating one for each service on the heap.
    48  
    49  	// API Services
    50  
    51  	ImageCashLetterFilesApi *ImageCashLetterFilesApiService
    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 *Configuration) *APIClient {
    61  	if cfg.HTTPClient == nil {
    62  		cfg.HTTPClient = http.DefaultClient
    63  	}
    64  
    65  	c := &APIClient{}
    66  	c.cfg = cfg
    67  	c.common.client = c
    68  
    69  	// API Services
    70  	c.ImageCashLetterFilesApi = (*ImageCashLetterFilesApiService)(&c.common)
    71  
    72  	return c
    73  }
    74  
    75  func atoi(in string) (int, error) {
    76  	return strconv.Atoi(in)
    77  }
    78  
    79  // selectHeaderContentType select a content type from the available list.
    80  func selectHeaderContentType(contentTypes []string) string {
    81  	if len(contentTypes) == 0 {
    82  		return ""
    83  	}
    84  	if contains(contentTypes, "application/json") {
    85  		return "application/json"
    86  	}
    87  	return contentTypes[0] // use the first content type specified in 'consumes'
    88  }
    89  
    90  // selectHeaderAccept join all accept types and return
    91  func selectHeaderAccept(accepts []string) string {
    92  	if len(accepts) == 0 {
    93  		return ""
    94  	}
    95  
    96  	if contains(accepts, "application/json") {
    97  		return "application/json"
    98  	}
    99  
   100  	return strings.Join(accepts, ",")
   101  }
   102  
   103  // contains is a case insenstive match, finding needle in a haystack
   104  func contains(haystack []string, needle string) bool {
   105  	for _, a := range haystack {
   106  		if strings.ToLower(a) == strings.ToLower(needle) {
   107  			return true
   108  		}
   109  	}
   110  	return false
   111  }
   112  
   113  // Verify optional parameters are of the correct type.
   114  func typeCheckParameter(obj interface{}, expected string, name string) error {
   115  	// Make sure there is an object.
   116  	if obj == nil {
   117  		return nil
   118  	}
   119  
   120  	// Check the type is as expected.
   121  	if reflect.TypeOf(obj).String() != expected {
   122  		return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String())
   123  	}
   124  	return nil
   125  }
   126  
   127  // parameterToString convert interface{} parameters to string, using a delimiter if format is provided.
   128  func parameterToString(obj interface{}, collectionFormat string) string {
   129  	var delimiter string
   130  
   131  	switch collectionFormat {
   132  	case "pipes":
   133  		delimiter = "|"
   134  	case "ssv":
   135  		delimiter = " "
   136  	case "tsv":
   137  		delimiter = "\t"
   138  	case "csv":
   139  		delimiter = ","
   140  	}
   141  
   142  	if reflect.TypeOf(obj).Kind() == reflect.Slice {
   143  		return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]")
   144  	} else if t, ok := obj.(time.Time); ok {
   145  		return t.Format(time.RFC3339)
   146  	}
   147  
   148  	return fmt.Sprintf("%v", obj)
   149  }
   150  
   151  // helper for converting interface{} parameters to json strings
   152  func parameterToJson(obj interface{}) (string, error) {
   153  	jsonBuf, err := json.Marshal(obj)
   154  	if err != nil {
   155  		return "", err
   156  	}
   157  	return string(jsonBuf), err
   158  }
   159  
   160  // callAPI do the request.
   161  func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
   162  	if c.cfg.Debug {
   163  		dump, err := httputil.DumpRequestOut(request, true)
   164  		if err != nil {
   165  			return nil, err
   166  		}
   167  		log.Printf("\n%s\n", string(dump))
   168  	}
   169  
   170  	resp, err := c.cfg.HTTPClient.Do(request)
   171  	if err != nil {
   172  		return resp, err
   173  	}
   174  
   175  	if c.cfg.Debug {
   176  		dump, err := httputil.DumpResponse(resp, true)
   177  		if err != nil {
   178  			return resp, err
   179  		}
   180  		log.Printf("\n%s\n", string(dump))
   181  	}
   182  
   183  	return resp, err
   184  }
   185  
   186  // ChangeBasePath changes base path to allow switching to mocks
   187  func (c *APIClient) ChangeBasePath(path string) {
   188  	c.cfg.BasePath = path
   189  }
   190  
   191  // Allow modification of underlying config for alternate implementations and testing
   192  // Caution: modifying the configuration while live can cause data races and potentially unwanted behavior
   193  func (c *APIClient) GetConfig() *Configuration {
   194  	return c.cfg
   195  }
   196  
   197  // prepareRequest build the request
   198  func (c *APIClient) prepareRequest(
   199  	ctx context.Context,
   200  	path string, method string,
   201  	postBody interface{},
   202  	headerParams map[string]string,
   203  	queryParams url.Values,
   204  	formParams url.Values,
   205  	formFileName string,
   206  	fileName string,
   207  	fileBytes []byte) (localVarRequest *http.Request, err error) {
   208  
   209  	var body *bytes.Buffer
   210  
   211  	// Detect postBody type and post.
   212  	if postBody != nil {
   213  		contentType := headerParams["Content-Type"]
   214  		if contentType == "" {
   215  			contentType = detectContentType(postBody)
   216  			headerParams["Content-Type"] = contentType
   217  		}
   218  
   219  		body, err = setBody(postBody, contentType)
   220  		if err != nil {
   221  			return nil, err
   222  		}
   223  	}
   224  
   225  	// add form parameters and file if available.
   226  	if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") {
   227  		if body != nil {
   228  			return nil, errors.New("Cannot specify postBody and multipart form at the same time.")
   229  		}
   230  		body = &bytes.Buffer{}
   231  		w := multipart.NewWriter(body)
   232  
   233  		for k, v := range formParams {
   234  			for _, iv := range v {
   235  				if strings.HasPrefix(k, "@") { // file
   236  					err = addFile(w, k[1:], iv)
   237  					if err != nil {
   238  						return nil, err
   239  					}
   240  				} else { // form value
   241  					w.WriteField(k, iv)
   242  				}
   243  			}
   244  		}
   245  		if len(fileBytes) > 0 && fileName != "" {
   246  			w.Boundary()
   247  			//_, fileNm := filepath.Split(fileName)
   248  			part, err := w.CreateFormFile(formFileName, filepath.Base(fileName))
   249  			if err != nil {
   250  				return nil, err
   251  			}
   252  			_, err = part.Write(fileBytes)
   253  			if err != nil {
   254  				return nil, err
   255  			}
   256  		}
   257  
   258  		// Set the Boundary in the Content-Type
   259  		headerParams["Content-Type"] = w.FormDataContentType()
   260  
   261  		// Set Content-Length
   262  		headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
   263  		w.Close()
   264  	}
   265  
   266  	if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 {
   267  		if body != nil {
   268  			return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.")
   269  		}
   270  		body = &bytes.Buffer{}
   271  		body.WriteString(formParams.Encode())
   272  		// Set Content-Length
   273  		headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
   274  	}
   275  
   276  	// Setup path and query parameters
   277  	url, err := url.Parse(path)
   278  	if err != nil {
   279  		return nil, err
   280  	}
   281  
   282  	// Override request host, if applicable
   283  	if c.cfg.Host != "" {
   284  		url.Host = c.cfg.Host
   285  	}
   286  
   287  	// Override request scheme, if applicable
   288  	if c.cfg.Scheme != "" {
   289  		url.Scheme = c.cfg.Scheme
   290  	}
   291  
   292  	// Adding Query Param
   293  	query := url.Query()
   294  	for k, v := range queryParams {
   295  		for _, iv := range v {
   296  			query.Add(k, iv)
   297  		}
   298  	}
   299  
   300  	// Encode the parameters.
   301  	url.RawQuery = query.Encode()
   302  
   303  	// Generate a new request
   304  	if body != nil {
   305  		localVarRequest, err = http.NewRequest(method, url.String(), body)
   306  	} else {
   307  		localVarRequest, err = http.NewRequest(method, url.String(), nil)
   308  	}
   309  	if err != nil {
   310  		return nil, err
   311  	}
   312  
   313  	// add header parameters, if any
   314  	if len(headerParams) > 0 {
   315  		headers := http.Header{}
   316  		for h, v := range headerParams {
   317  			headers.Set(h, v)
   318  		}
   319  		localVarRequest.Header = headers
   320  	}
   321  
   322  	// Add the user agent to the request.
   323  	localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent)
   324  
   325  	if ctx != nil {
   326  		// add context to the request
   327  		localVarRequest = localVarRequest.WithContext(ctx)
   328  
   329  		// Walk through any authentication.
   330  
   331  		// OAuth2 authentication
   332  		if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok {
   333  			// We were able to grab an oauth2 token from the context
   334  			var latestToken *oauth2.Token
   335  			if latestToken, err = tok.Token(); err != nil {
   336  				return nil, err
   337  			}
   338  
   339  			latestToken.SetAuthHeader(localVarRequest)
   340  		}
   341  
   342  		// Basic HTTP Authentication
   343  		if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok {
   344  			localVarRequest.SetBasicAuth(auth.UserName, auth.Password)
   345  		}
   346  
   347  		// AccessToken Authentication
   348  		if auth, ok := ctx.Value(ContextAccessToken).(string); ok {
   349  			localVarRequest.Header.Add("Authorization", "Bearer "+auth)
   350  		}
   351  
   352  	}
   353  
   354  	for header, value := range c.cfg.DefaultHeader {
   355  		localVarRequest.Header.Add(header, value)
   356  	}
   357  
   358  	return localVarRequest, nil
   359  }
   360  
   361  func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) {
   362  	if len(b) == 0 {
   363  		return nil
   364  	}
   365  	if s, ok := v.(*string); ok {
   366  		*s = string(b)
   367  		return nil
   368  	}
   369  	if f, ok := v.(**os.File); ok {
   370  		*f, err = ioutil.TempFile("", "HttpClientFile")
   371  		if err != nil {
   372  			return
   373  		}
   374  		_, err = (*f).Write(b)
   375  		_, err = (*f).Seek(0, io.SeekStart)
   376  		return
   377  	}
   378  	if xmlCheck.MatchString(contentType) {
   379  		if err = xml.Unmarshal(b, v); err != nil {
   380  			return err
   381  		}
   382  		return nil
   383  	}
   384  	if jsonCheck.MatchString(contentType) {
   385  		if err = json.Unmarshal(b, v); err != nil {
   386  			return err
   387  		}
   388  		return nil
   389  	}
   390  	return errors.New("undefined response type")
   391  }
   392  
   393  // Add a file to the multipart request
   394  func addFile(w *multipart.Writer, fieldName, path string) error {
   395  	file, err := os.Open(path)
   396  	if err != nil {
   397  		return err
   398  	}
   399  	defer file.Close()
   400  
   401  	part, err := w.CreateFormFile(fieldName, filepath.Base(path))
   402  	if err != nil {
   403  		return err
   404  	}
   405  	_, err = io.Copy(part, file)
   406  
   407  	return err
   408  }
   409  
   410  // Prevent trying to import "fmt"
   411  func reportError(format string, a ...interface{}) error {
   412  	return fmt.Errorf(format, a...)
   413  }
   414  
   415  // Set request body from an interface{}
   416  func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) {
   417  	if bodyBuf == nil {
   418  		bodyBuf = &bytes.Buffer{}
   419  	}
   420  
   421  	if reader, ok := body.(io.Reader); ok {
   422  		_, err = bodyBuf.ReadFrom(reader)
   423  	} else if b, ok := body.([]byte); ok {
   424  		_, err = bodyBuf.Write(b)
   425  	} else if s, ok := body.(string); ok {
   426  		_, err = bodyBuf.WriteString(s)
   427  	} else if s, ok := body.(*string); ok {
   428  		_, err = bodyBuf.WriteString(*s)
   429  	} else if jsonCheck.MatchString(contentType) {
   430  		err = json.NewEncoder(bodyBuf).Encode(body)
   431  	} else if xmlCheck.MatchString(contentType) {
   432  		err = xml.NewEncoder(bodyBuf).Encode(body)
   433  	}
   434  
   435  	if err != nil {
   436  		return nil, err
   437  	}
   438  
   439  	if bodyBuf.Len() == 0 {
   440  		err = fmt.Errorf("Invalid body type %s\n", contentType)
   441  		return nil, err
   442  	}
   443  	return bodyBuf, nil
   444  }
   445  
   446  // detectContentType method is used to figure out `Request.Body` content type for request header
   447  func detectContentType(body interface{}) string {
   448  	contentType := "text/plain; charset=utf-8"
   449  	kind := reflect.TypeOf(body).Kind()
   450  
   451  	switch kind {
   452  	case reflect.Struct, reflect.Map, reflect.Ptr:
   453  		contentType = "application/json; charset=utf-8"
   454  	case reflect.String:
   455  		contentType = "text/plain; charset=utf-8"
   456  	default:
   457  		if b, ok := body.([]byte); ok {
   458  			contentType = http.DetectContentType(b)
   459  		} else if kind == reflect.Slice {
   460  			contentType = "application/json; charset=utf-8"
   461  		}
   462  	}
   463  
   464  	return contentType
   465  }
   466  
   467  // Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go
   468  type cacheControl map[string]string
   469  
   470  func parseCacheControl(headers http.Header) cacheControl {
   471  	cc := cacheControl{}
   472  	ccHeader := headers.Get("Cache-Control")
   473  	for _, part := range strings.Split(ccHeader, ",") {
   474  		part = strings.Trim(part, " ")
   475  		if part == "" {
   476  			continue
   477  		}
   478  		if strings.ContainsRune(part, '=') {
   479  			keyval := strings.Split(part, "=")
   480  			cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",")
   481  		} else {
   482  			cc[part] = ""
   483  		}
   484  	}
   485  	return cc
   486  }
   487  
   488  // CacheExpires helper function to determine remaining time before repeating a request.
   489  func CacheExpires(r *http.Response) time.Time {
   490  	// Figure out when the cache expires.
   491  	var expires time.Time
   492  	now, err := time.Parse(time.RFC1123, r.Header.Get("date"))
   493  	if err != nil {
   494  		return time.Now()
   495  	}
   496  	respCacheControl := parseCacheControl(r.Header)
   497  
   498  	if maxAge, ok := respCacheControl["max-age"]; ok {
   499  		lifetime, err := time.ParseDuration(maxAge + "s")
   500  		if err != nil {
   501  			expires = now
   502  		} else {
   503  			expires = now.Add(lifetime)
   504  		}
   505  	} else {
   506  		expiresHeader := r.Header.Get("Expires")
   507  		if expiresHeader != "" {
   508  			expires, err = time.Parse(time.RFC1123, expiresHeader)
   509  			if err != nil {
   510  				expires = now
   511  			}
   512  		}
   513  	}
   514  	return expires
   515  }
   516  
   517  func strlen(s string) int {
   518  	return utf8.RuneCountInString(s)
   519  }
   520  
   521  // GenericOpenAPIError Provides access to the body, error and model on returned errors.
   522  type GenericOpenAPIError struct {
   523  	body  []byte
   524  	error string
   525  	model interface{}
   526  }
   527  
   528  // Error returns non-empty string if there was an error.
   529  func (e GenericOpenAPIError) Error() string {
   530  	return e.error
   531  }
   532  
   533  // Body returns the raw bytes of the response
   534  func (e GenericOpenAPIError) Body() []byte {
   535  	return e.body
   536  }
   537  
   538  // Model returns the unpacked model of the error
   539  func (e GenericOpenAPIError) Model() interface{} {
   540  	return e.model
   541  }