github.com/go-swagger/go-swagger@v0.31.0/generator/templates/client/client.gotmpl (about)

     1  // Code generated by go-swagger; DO NOT EDIT.
     2  
     3  
     4  {{ if .Copyright -}}// {{ comment .Copyright -}}{{ end }}
     5  
     6  
     7  package {{ .Name }}
     8  
     9  // This file was generated by the swagger tool.
    10  // Editing this file might prove futile when you re-run the swagger generate command
    11  
    12  import (
    13    "fmt"
    14    "io"
    15    "net/http"
    16  
    17    "github.com/go-openapi/errors"
    18    "github.com/go-openapi/runtime"
    19    httptransport "github.com/go-openapi/runtime/client"
    20    "github.com/go-openapi/strfmt"
    21    "github.com/go-openapi/swag"
    22    "github.com/go-openapi/validate"
    23  
    24    {{ imports .DefaultImports }}
    25    {{ imports .Imports }}
    26  )
    27  
    28  // New creates a new {{ humanize .Name }} API client.
    29  func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService {
    30    return &Client{transport: transport, formats: formats}
    31  }
    32  
    33  // New creates a new {{ humanize .Name }} API client with basic auth credentials.
    34  // It takes the following parameters:
    35  // - host: http host (github.com).
    36  // - basePath: any base path for the API client ("/v1", "/v3").
    37  // - scheme: http scheme ("http", "https").
    38  // - user: user for basic authentication header.
    39  // - password: password for basic authentication header.
    40  func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService {
    41    transport := httptransport.New(host, basePath, []string{scheme})
    42    transport.DefaultAuthentication = httptransport.BasicAuth(user, password)
    43    return &Client{transport: transport, formats: strfmt.Default}
    44  }
    45  
    46  // New creates a new {{ humanize .Name }} API client with a bearer token for authentication.
    47  // It takes the following parameters:
    48  // - host: http host (github.com).
    49  // - basePath: any base path for the API client ("/v1", "/v3").
    50  // - scheme: http scheme ("http", "https").
    51  // - bearerToken: bearer token for Bearer authentication header.
    52  func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService {
    53    transport := httptransport.New(host, basePath, []string{scheme})
    54    transport.DefaultAuthentication = httptransport.BearerToken(bearerToken)
    55    return &Client{transport: transport, formats: strfmt.Default}
    56  }
    57  
    58  /*
    59  Client {{ if .Summary }}{{ .Summary }}{{ if .Description }}
    60  
    61  {{ blockcomment .Description }}{{ end }}{{ else if .Description}}{{ blockcomment .Description }}{{ else }}for {{ humanize .Name }} API{{ end }}
    62  */
    63  type Client struct {
    64    transport runtime.ClientTransport
    65    formats strfmt.Registry
    66  }
    67  
    68  // ClientOption may be used to customize the behavior of Client methods.
    69  type ClientOption func(*runtime.ClientOperation)
    70  
    71  {{- with .ClientOptions }}{{/* use ad'hoc function mediaGoName rather than pascalize because of patterns with * */}}
    72  
    73  // This client is generated with a few options you might find useful for your swagger spec.
    74  //
    75  // Feel free to add you own set of options.
    76    {{- if gt (len .ConsumesMediaTypes) 1 }}
    77  
    78  // WithContentType allows the client to force the Content-Type header
    79  // to negotiate a specific Consumer from the server.
    80  //
    81  // You may use this option to set arbitrary extensions to your MIME media type.
    82  func WithContentType(mime string) ClientOption {
    83  	return func(r *runtime.ClientOperation) {
    84  		r.ConsumesMediaTypes = []string{mime}
    85  	}
    86  }
    87      {{ range .ConsumesMediaTypes  }}
    88        {{- if not ( eq (mediaGoName .) ""  ) }}{{/* guard: in case garbled input produces a (conflicting) empty name */}}
    89  
    90  // WithContentType{{ mediaGoName . }} sets the Content-Type header to {{ printf "%q" . }}.
    91  func WithContentType{{ mediaGoName . }}(r *runtime.ClientOperation) {
    92  	r.ConsumesMediaTypes = []string{ {{ printf "%q" . }} }
    93  }
    94        {{- end }}
    95      {{- end }}
    96    {{- end }}
    97    {{- if gt (len .ProducesMediaTypes) 1 }}
    98  
    99  // WithAccept allows the client to force the Accept header
   100  // to negotiate a specific Producer from the server.
   101  //
   102  // You may use this option to set arbitrary extensions to your MIME media type.
   103  func WithAccept(mime string) ClientOption {
   104  	return func(r *runtime.ClientOperation) {
   105  		r.ProducesMediaTypes = []string{mime}
   106  	}
   107  }
   108      {{ range .ProducesMediaTypes  }}
   109        {{- if not ( eq (mediaGoName .) ""  ) }}{{/* guard: in case garbled input produces a (conflicting) empty name */}}
   110  
   111  // WithAccept{{ mediaGoName . }} sets the Accept header to {{ printf "%q" . }}.
   112  func WithAccept{{ mediaGoName . }}(r *runtime.ClientOperation) {
   113  	r.ProducesMediaTypes = []string{ {{ printf "%q" . }} }
   114  }
   115        {{- end }}
   116      {{- end }}
   117    {{- end }}
   118  {{- end }}
   119  
   120  // ClientService is the interface for Client methods
   121  type ClientService interface {
   122  	{{ range .Operations }}
   123  	{{ pascalize .Name }}(params *{{ pascalize .Name }}Params{{ if .Authorized }}, authInfo runtime.ClientAuthInfoWriter{{end}}{{ if .HasStreamingResponse }}, writer io.Writer{{ end }}, opts ...ClientOption) {{ if .SuccessResponse }}({{ range .SuccessResponses }}*{{ pascalize .Name }}, {{ end }}{{ end }}error{{ if .SuccessResponse }}){{ end }}
   124  	{{ end }}
   125  
   126  	SetTransport(transport runtime.ClientTransport)
   127  }
   128  
   129  {{ range .Operations }}
   130  /*
   131    {{ pascalize .Name }} {{ if .Summary }}{{ pluralizeFirstWord (humanize .Summary) }}{{ if .Description }}
   132  
   133    {{ blockcomment .Description }}{{ end }}{{ else if .Description}}{{ blockcomment .Description }}{{ else }}{{ humanize .Name }} API{{ end }}
   134  */
   135  func (a *Client) {{ pascalize .Name }}(params *{{ pascalize .Name }}Params{{ if .Authorized }}, authInfo runtime.ClientAuthInfoWriter{{end}}{{ if .HasStreamingResponse }}, writer io.Writer{{ end }}, opts ...ClientOption) {{ if .SuccessResponse }}({{ range .SuccessResponses }}*{{ pascalize .Name }}, {{ end }}{{ end }}error{{ if .SuccessResponse }}){{ end }} {
   136    // TODO: Validate the params before sending
   137    if params == nil {
   138      params = New{{ pascalize .Name }}Params()
   139    }
   140    op := &runtime.ClientOperation{
   141      ID: {{ printf "%q" .Name }},
   142      Method: {{ printf "%q" .Method }},
   143      PathPattern: {{ printf "%q" .Path }},
   144      ProducesMediaTypes: {{ printf "%#v" .ProducesMediaTypes }},
   145      ConsumesMediaTypes: {{ printf "%#v" .ConsumesMediaTypes }},
   146      Schemes: {{ printf "%#v" .Schemes }},
   147      Params: params,
   148      Reader: &{{ pascalize .Name }}Reader{formats: a.formats{{ if .HasStreamingResponse }}, writer: writer{{ end }}},{{ if .Authorized }}
   149      AuthInfo: authInfo,{{ end}}
   150      Context: params.Context,
   151      Client: params.HTTPClient,
   152    }
   153  	for _, opt := range opts {
   154  		opt(op)
   155  	}
   156    {{ $length := len .SuccessResponses }}
   157    {{ if .SuccessResponse }}result{{else}}_{{ end }}, err := a.transport.Submit(op)
   158    if err != nil {
   159      return {{ if .SuccessResponse }}{{ padSurround "nil" "nil" 0 $length }}, {{ end }}err
   160    }
   161    {{- if .SuccessResponse }}
   162      {{- if eq $length 1 }}
   163    success, ok := result.(*{{ pascalize .SuccessResponse.Name }})
   164    if ok {
   165      return success,nil
   166    }
   167    // unexpected success response
   168        {{- if .DefaultResponse }}{{/* if a default response is provided, fill this and return an error */}}
   169    unexpectedSuccess := result.(*{{ pascalize .DefaultResponse.Name }})
   170    return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code())
   171        {{- else }}
   172    // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
   173    msg := fmt.Sprintf("unexpected success response for {{ .Name }}: API contract not enforced by server. Client expected to get an error, but got: %T", result)
   174    panic(msg)
   175        {{- end }}
   176      {{- else }}{{/* several possible success responses */}}
   177    switch value := result.(type) {
   178        {{- range $i, $v := .SuccessResponses }}
   179    case *{{ pascalize $v.Name }}:
   180      return {{ padSurround "value" "nil" $i $length }}, nil
   181        {{- end }}
   182    }
   183        {{- if .DefaultResponse }}{{/* if a default response is provided, fill this and return an error */}}
   184    // unexpected success response
   185    unexpectedSuccess := result.(*{{ pascalize .DefaultResponse.Name }})
   186    return {{ padSurround "nil" "nil" 0 $length }}, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code())
   187        {{- else }}
   188    // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
   189    msg := fmt.Sprintf("unexpected success response for {{ $.Name }}: API contract not enforced by server. Client expected to get an error, but got: %T", result)
   190    panic(msg)
   191        {{- end }}
   192      {{- end }}
   193    {{- else }}
   194    return nil
   195    {{- end }}
   196  }
   197  {{- end }}
   198  
   199  // SetTransport changes the transport on the client
   200  func (a *Client) SetTransport(transport runtime.ClientTransport) {
   201    a.transport = transport
   202  }