vendorify
diff --git a/go/vendor/github.com/go-openapi/runtime/client/auth_info.go b/go/vendor/github.com/go-openapi/runtime/client/auth_info.go
new file mode 100644
index 0000000..9e18222
--- /dev/null
+++ b/go/vendor/github.com/go-openapi/runtime/client/auth_info.go
@@ -0,0 +1,60 @@
+// Copyright 2015 go-swagger maintainers
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package client
+
+import (
+ "encoding/base64"
+
+ "github.com/go-openapi/runtime"
+ "github.com/go-openapi/strfmt"
+)
+
+// PassThroughAuth never manipulates the request
+var PassThroughAuth runtime.ClientAuthInfoWriter
+
+func init() {
+ PassThroughAuth = runtime.ClientAuthInfoWriterFunc(func(_ runtime.ClientRequest, _ strfmt.Registry) error { return nil })
+}
+
+// BasicAuth provides a basic auth info writer
+func BasicAuth(username, password string) runtime.ClientAuthInfoWriter {
+ return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
+ encoded := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
+ return r.SetHeaderParam("Authorization", "Basic "+encoded)
+ })
+}
+
+// APIKeyAuth provides an API key auth info writer
+func APIKeyAuth(name, in, value string) runtime.ClientAuthInfoWriter {
+ if in == "query" {
+ return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
+ return r.SetQueryParam(name, value)
+ })
+ }
+
+ if in == "header" {
+ return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
+ return r.SetHeaderParam(name, value)
+ })
+ }
+ return nil
+}
+
+// BearerToken provides a header based oauth2 bearer access token auth info writer
+func BearerToken(token string) runtime.ClientAuthInfoWriter {
+ return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error {
+ return r.SetHeaderParam("Authorization", "Bearer "+token)
+ })
+}
diff --git a/go/vendor/github.com/go-openapi/runtime/client/keepalive.go b/go/vendor/github.com/go-openapi/runtime/client/keepalive.go
new file mode 100644
index 0000000..f832545
--- /dev/null
+++ b/go/vendor/github.com/go-openapi/runtime/client/keepalive.go
@@ -0,0 +1,53 @@
+package client
+
+import (
+ "io"
+ "io/ioutil"
+ "net/http"
+ "sync/atomic"
+)
+
+// KeepAliveTransport drains the remaining body from a response
+// so that go will reuse the TCP connections.
+// This is not enabled by default because there are servers where
+// the response never gets closed and that would make the code hang forever.
+// So instead it's provided as a http client middleware that can be used to override
+// any request.
+func KeepAliveTransport(rt http.RoundTripper) http.RoundTripper {
+ return &keepAliveTransport{wrapped: rt}
+}
+
+type keepAliveTransport struct {
+ wrapped http.RoundTripper
+}
+
+func (k *keepAliveTransport) RoundTrip(r *http.Request) (*http.Response, error) {
+ resp, err := k.wrapped.RoundTrip(r)
+ if err != nil {
+ return resp, err
+ }
+ resp.Body = &drainingReadCloser{rdr: resp.Body}
+ return resp, nil
+}
+
+type drainingReadCloser struct {
+ rdr io.ReadCloser
+ seenEOF uint32
+}
+
+func (d *drainingReadCloser) Read(p []byte) (n int, err error) {
+ n, err = d.rdr.Read(p)
+ if err == io.EOF || n == 0 {
+ atomic.StoreUint32(&d.seenEOF, 1)
+ }
+ return
+}
+
+func (d *drainingReadCloser) Close() error {
+ // drain buffer
+ if atomic.LoadUint32(&d.seenEOF) != 1 {
+ //#nosec
+ io.Copy(ioutil.Discard, d.rdr)
+ }
+ return d.rdr.Close()
+}
diff --git a/go/vendor/github.com/go-openapi/runtime/client/request.go b/go/vendor/github.com/go-openapi/runtime/client/request.go
new file mode 100644
index 0000000..a1c1915
--- /dev/null
+++ b/go/vendor/github.com/go-openapi/runtime/client/request.go
@@ -0,0 +1,374 @@
+// Copyright 2015 go-swagger maintainers
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package client
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "io/ioutil"
+ "log"
+ "mime/multipart"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/go-openapi/runtime"
+ "github.com/go-openapi/strfmt"
+)
+
+// NewRequest creates a new swagger http client request
+func newRequest(method, pathPattern string, writer runtime.ClientRequestWriter) (*request, error) {
+ return &request{
+ pathPattern: pathPattern,
+ method: method,
+ writer: writer,
+ header: make(http.Header),
+ query: make(url.Values),
+ timeout: DefaultTimeout,
+ }, nil
+}
+
+// Request represents a swagger client request.
+//
+// This Request struct converts to a HTTP request.
+// There might be others that convert to other transports.
+// There is no error checking here, it is assumed to be used after a spec has been validated.
+// so impossible combinations should not arise (hopefully).
+//
+// The main purpose of this struct is to hide the machinery of adding params to a transport request.
+// The generated code only implements what is necessary to turn a param into a valid value for these methods.
+type request struct {
+ pathPattern string
+ method string
+ writer runtime.ClientRequestWriter
+
+ pathParams map[string]string
+ header http.Header
+ query url.Values
+ formFields url.Values
+ fileFields map[string][]runtime.NamedReadCloser
+ payload interface{}
+ timeout time.Duration
+ buf *bytes.Buffer
+}
+
+var (
+ // ensure interface compliance
+ _ runtime.ClientRequest = new(request)
+)
+
+func (r *request) isMultipart(mediaType string) bool {
+ if len(r.fileFields) > 0 {
+ return true
+ }
+
+ return runtime.MultipartFormMime == mediaType
+}
+
+// BuildHTTP creates a new http request based on the data from the params
+func (r *request) BuildHTTP(mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry) (*http.Request, error) {
+ return r.buildHTTP(mediaType, basePath, producers, registry, nil)
+}
+
+func (r *request) buildHTTP(mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry, auth runtime.ClientAuthInfoWriter) (*http.Request, error) {
+ // build the data
+ if err := r.writer.WriteToRequest(r, registry); err != nil {
+ return nil, err
+ }
+
+ if auth != nil {
+ if err := auth.AuthenticateRequest(r, registry); err != nil {
+ return nil, err
+ }
+ }
+
+ // create http request
+ var reinstateSlash bool
+ if r.pathPattern != "" && r.pathPattern != "/" && r.pathPattern[len(r.pathPattern)-1] == '/' {
+ reinstateSlash = true
+ }
+ urlPath := path.Join(basePath, r.pathPattern)
+ for k, v := range r.pathParams {
+ urlPath = strings.Replace(urlPath, "{"+k+"}", url.PathEscape(v), -1)
+ }
+ if reinstateSlash {
+ urlPath = urlPath + "/"
+ }
+
+ var body io.ReadCloser
+ var pr *io.PipeReader
+ var pw *io.PipeWriter
+
+ r.buf = bytes.NewBuffer(nil)
+ if r.payload != nil || len(r.formFields) > 0 || len(r.fileFields) > 0 {
+ body = ioutil.NopCloser(r.buf)
+ if r.isMultipart(mediaType) {
+ pr, pw = io.Pipe()
+ body = pr
+ }
+ }
+ req, err := http.NewRequest(r.method, urlPath, body)
+
+ if err != nil {
+ return nil, err
+ }
+
+ req.URL.RawQuery = r.query.Encode()
+ req.Header = r.header
+
+ // check if this is a form type request
+ if len(r.formFields) > 0 || len(r.fileFields) > 0 {
+ if !r.isMultipart(mediaType) {
+ req.Header.Set(runtime.HeaderContentType, mediaType)
+ formString := r.formFields.Encode()
+ // set content length before writing to the buffer
+ req.ContentLength = int64(len(formString))
+ // write the form values as the body
+ r.buf.WriteString(formString)
+ return req, nil
+ }
+
+ mp := multipart.NewWriter(pw)
+ req.Header.Set(runtime.HeaderContentType, mangleContentType(mediaType, mp.Boundary()))
+
+ go func() {
+ defer func() {
+ mp.Close()
+ pw.Close()
+ }()
+
+ for fn, v := range r.formFields {
+ for _, vi := range v {
+ if err := mp.WriteField(fn, vi); err != nil {
+ pw.CloseWithError(err)
+ log.Println(err)
+ }
+ }
+ }
+
+ defer func() {
+ for _, ff := range r.fileFields {
+ for _, ffi := range ff {
+ ffi.Close()
+ }
+ }
+ }()
+ for fn, f := range r.fileFields {
+ for _, fi := range f {
+ wrtr, err := mp.CreateFormFile(fn, filepath.Base(fi.Name()))
+ if err != nil {
+ pw.CloseWithError(err)
+ log.Println(err)
+ } else if _, err := io.Copy(wrtr, fi); err != nil {
+ pw.CloseWithError(err)
+ log.Println(err)
+ }
+ }
+ }
+
+ }()
+ return req, nil
+
+ }
+
+ // if there is payload, use the producer to write the payload, and then
+ // set the header to the content-type appropriate for the payload produced
+ if r.payload != nil {
+ // TODO: infer most appropriate content type based on the producer used,
+ // and the `consumers` section of the spec/operation
+ req.Header.Set(runtime.HeaderContentType, mediaType)
+ if rdr, ok := r.payload.(io.ReadCloser); ok {
+ req.Body = rdr
+
+ return req, nil
+ }
+
+ if rdr, ok := r.payload.(io.Reader); ok {
+ req.Body = ioutil.NopCloser(rdr)
+
+ return req, nil
+ }
+
+ req.GetBody = func() (io.ReadCloser, error) {
+ var b bytes.Buffer
+ producer := producers[mediaType]
+ if err := producer.Produce(&b, r.payload); err != nil {
+ return nil, err
+ }
+
+ if _, err := r.buf.Write(b.Bytes()); err != nil {
+ return nil, err
+ }
+ return ioutil.NopCloser(&b), nil
+ }
+
+ // set the content length of the request or else a chunked transfer is
+ // declared, and this corrupts outgoing JSON payloads. the content's
+ // length must be set prior to the body being written per the spec at
+ // https://golang.org/pkg/net/http
+ //
+ // If Body is present, Content-Length is <= 0 and TransferEncoding
+ // hasn't been set to "identity", Write adds
+ // "Transfer-Encoding: chunked" to the header. Body is closed
+ // after it is sent.
+ //
+ // to that end a temporary buffer, b, is created to produce the payload
+ // body, and then its size is used to set the request's content length
+ var b bytes.Buffer
+ producer := producers[mediaType]
+ if err := producer.Produce(&b, r.payload); err != nil {
+ return nil, err
+ }
+ req.ContentLength = int64(b.Len())
+ if _, err := r.buf.Write(b.Bytes()); err != nil {
+ return nil, err
+ }
+ }
+
+ if runtime.CanHaveBody(req.Method) && req.Body == nil && req.Header.Get(runtime.HeaderContentType) == "" {
+ req.Header.Set(runtime.HeaderContentType, mediaType)
+ }
+
+ return req, nil
+}
+
+func mangleContentType(mediaType, boundary string) string {
+ if strings.ToLower(mediaType) == runtime.URLencodedFormMime {
+ return fmt.Sprintf("%s; boundary=%s", mediaType, boundary)
+ }
+ return "multipart/form-data; boundary=" + boundary
+}
+
+func (r *request) GetMethod() string {
+ return r.method
+}
+
+func (r *request) GetPath() string {
+ path := r.pathPattern
+ for k, v := range r.pathParams {
+ path = strings.Replace(path, "{"+k+"}", v, -1)
+ }
+ return path
+}
+
+func (r *request) GetBody() []byte {
+ if r.buf == nil {
+ return nil
+ }
+ return r.buf.Bytes()
+}
+
+// SetHeaderParam adds a header param to the request
+// when there is only 1 value provided for the varargs, it will set it.
+// when there are several values provided for the varargs it will add it (no overriding)
+func (r *request) SetHeaderParam(name string, values ...string) error {
+ if r.header == nil {
+ r.header = make(http.Header)
+ }
+ r.header[http.CanonicalHeaderKey(name)] = values
+ return nil
+}
+
+// SetQueryParam adds a query param to the request
+// when there is only 1 value provided for the varargs, it will set it.
+// when there are several values provided for the varargs it will add it (no overriding)
+func (r *request) SetQueryParam(name string, values ...string) error {
+ if r.query == nil {
+ r.query = make(url.Values)
+ }
+ r.query[name] = values
+ return nil
+}
+
+// GetQueryParams returns a copy of all query params currently set for the request
+func (r *request) GetQueryParams() url.Values {
+ var result = make(url.Values)
+ for key, value := range r.query {
+ result[key] = append([]string{}, value...)
+ }
+ return result
+}
+
+// SetFormParam adds a forn param to the request
+// when there is only 1 value provided for the varargs, it will set it.
+// when there are several values provided for the varargs it will add it (no overriding)
+func (r *request) SetFormParam(name string, values ...string) error {
+ if r.formFields == nil {
+ r.formFields = make(url.Values)
+ }
+ r.formFields[name] = values
+ return nil
+}
+
+// SetPathParam adds a path param to the request
+func (r *request) SetPathParam(name string, value string) error {
+ if r.pathParams == nil {
+ r.pathParams = make(map[string]string)
+ }
+
+ r.pathParams[name] = value
+ return nil
+}
+
+// SetFileParam adds a file param to the request
+func (r *request) SetFileParam(name string, files ...runtime.NamedReadCloser) error {
+ for _, file := range files {
+ if actualFile, ok := file.(*os.File); ok {
+ fi, err := os.Stat(actualFile.Name())
+ if err != nil {
+ return err
+ }
+ if fi.IsDir() {
+ return fmt.Errorf("%q is a directory, only files are supported", file.Name())
+ }
+ }
+ }
+
+ if r.fileFields == nil {
+ r.fileFields = make(map[string][]runtime.NamedReadCloser)
+ }
+ if r.formFields == nil {
+ r.formFields = make(url.Values)
+ }
+
+ r.fileFields[name] = files
+ return nil
+}
+
+func (r *request) GetFileParam() map[string][]runtime.NamedReadCloser {
+ return r.fileFields
+}
+
+// SetBodyParam sets a body parameter on the request.
+// This does not yet serialze the object, this happens as late as possible.
+func (r *request) SetBodyParam(payload interface{}) error {
+ r.payload = payload
+ return nil
+}
+
+func (r *request) GetBodyParam() interface{} {
+ return r.payload
+}
+
+// SetTimeout sets the timeout for a request
+func (r *request) SetTimeout(timeout time.Duration) error {
+ r.timeout = timeout
+ return nil
+}
diff --git a/go/vendor/github.com/go-openapi/runtime/client/response.go b/go/vendor/github.com/go-openapi/runtime/client/response.go
new file mode 100644
index 0000000..bd23858
--- /dev/null
+++ b/go/vendor/github.com/go-openapi/runtime/client/response.go
@@ -0,0 +1,44 @@
+// Copyright 2015 go-swagger maintainers
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package client
+
+import (
+ "io"
+ "net/http"
+
+ "github.com/go-openapi/runtime"
+)
+
+var _ runtime.ClientResponse = response{}
+
+type response struct {
+ resp *http.Response
+}
+
+func (r response) Code() int {
+ return r.resp.StatusCode
+}
+
+func (r response) Message() string {
+ return r.resp.Status
+}
+
+func (r response) GetHeader(name string) string {
+ return r.resp.Header.Get(name)
+}
+
+func (r response) Body() io.ReadCloser {
+ return r.resp.Body
+}
diff --git a/go/vendor/github.com/go-openapi/runtime/client/runtime.go b/go/vendor/github.com/go-openapi/runtime/client/runtime.go
new file mode 100644
index 0000000..c222d94
--- /dev/null
+++ b/go/vendor/github.com/go-openapi/runtime/client/runtime.go
@@ -0,0 +1,437 @@
+// Copyright 2015 go-swagger maintainers
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package client
+
+import (
+ "context"
+ "crypto"
+ "crypto/ecdsa"
+ "crypto/rsa"
+ "crypto/tls"
+ "crypto/x509"
+ "encoding/pem"
+ "fmt"
+ "io/ioutil"
+ "mime"
+ "net/http"
+ "net/http/httputil"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/go-openapi/runtime"
+ "github.com/go-openapi/runtime/logger"
+ "github.com/go-openapi/runtime/middleware"
+ "github.com/go-openapi/strfmt"
+)
+
+// TLSClientOptions to configure client authentication with mutual TLS
+type TLSClientOptions struct {
+ // Certificate is the path to a PEM-encoded certificate to be used for
+ // client authentication. If set then Key must also be set.
+ Certificate string
+
+ // LoadedCertificate is the certificate to be used for client authentication.
+ // This field is ignored if Certificate is set. If this field is set, LoadedKey
+ // is also required.
+ LoadedCertificate *x509.Certificate
+
+ // Key is the path to an unencrypted PEM-encoded private key for client
+ // authentication. This field is required if Certificate is set.
+ Key string
+
+ // LoadedKey is the key for client authentication. This field is required if
+ // LoadedCertificate is set.
+ LoadedKey crypto.PrivateKey
+
+ // CA is a path to a PEM-encoded certificate that specifies the root certificate
+ // to use when validating the TLS certificate presented by the server. If this field
+ // (and LoadedCA) is not set, the system certificate pool is used. This field is ignored if LoadedCA
+ // is set.
+ CA string
+
+ // LoadedCA specifies the root certificate to use when validating the server's TLS certificate.
+ // If this field (and CA) is not set, the system certificate pool is used.
+ LoadedCA *x509.Certificate
+
+ // ServerName specifies the hostname to use when verifying the server certificate.
+ // If this field is set then InsecureSkipVerify will be ignored and treated as
+ // false.
+ ServerName string
+
+ // InsecureSkipVerify controls whether the certificate chain and hostname presented
+ // by the server are validated. If false, any certificate is accepted.
+ InsecureSkipVerify bool
+
+ // Prevents callers using unkeyed fields.
+ _ struct{}
+}
+
+// TLSClientAuth creates a tls.Config for mutual auth
+func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) {
+ // create client tls config
+ cfg := &tls.Config{}
+
+ // load client cert if specified
+ if opts.Certificate != "" {
+ cert, err := tls.LoadX509KeyPair(opts.Certificate, opts.Key)
+ if err != nil {
+ return nil, fmt.Errorf("tls client cert: %v", err)
+ }
+ cfg.Certificates = []tls.Certificate{cert}
+ } else if opts.LoadedCertificate != nil {
+ block := pem.Block{Type: "CERTIFICATE", Bytes: opts.LoadedCertificate.Raw}
+ certPem := pem.EncodeToMemory(&block)
+
+ var keyBytes []byte
+ switch k := opts.LoadedKey.(type) {
+ case *rsa.PrivateKey:
+ keyBytes = x509.MarshalPKCS1PrivateKey(k)
+ case *ecdsa.PrivateKey:
+ var err error
+ keyBytes, err = x509.MarshalECPrivateKey(k)
+ if err != nil {
+ return nil, fmt.Errorf("tls client priv key: %v", err)
+ }
+ default:
+ return nil, fmt.Errorf("tls client priv key: unsupported key type")
+ }
+
+ block = pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes}
+ keyPem := pem.EncodeToMemory(&block)
+
+ cert, err := tls.X509KeyPair(certPem, keyPem)
+ if err != nil {
+ return nil, fmt.Errorf("tls client cert: %v", err)
+ }
+ cfg.Certificates = []tls.Certificate{cert}
+ }
+
+ cfg.InsecureSkipVerify = opts.InsecureSkipVerify
+
+ // When no CA certificate is provided, default to the system cert pool
+ // that way when a request is made to a server known by the system trust store,
+ // the name is still verified
+ if opts.LoadedCA != nil {
+ caCertPool := x509.NewCertPool()
+ caCertPool.AddCert(opts.LoadedCA)
+ cfg.RootCAs = caCertPool
+ } else if opts.CA != "" {
+ // load ca cert
+ caCert, err := ioutil.ReadFile(opts.CA)
+ if err != nil {
+ return nil, fmt.Errorf("tls client ca: %v", err)
+ }
+ caCertPool := x509.NewCertPool()
+ caCertPool.AppendCertsFromPEM(caCert)
+ cfg.RootCAs = caCertPool
+ }
+
+ // apply servername overrride
+ if opts.ServerName != "" {
+ cfg.InsecureSkipVerify = false
+ cfg.ServerName = opts.ServerName
+ }
+
+ cfg.BuildNameToCertificate()
+
+ return cfg, nil
+}
+
+// TLSTransport creates a http client transport suitable for mutual tls auth
+func TLSTransport(opts TLSClientOptions) (http.RoundTripper, error) {
+ cfg, err := TLSClientAuth(opts)
+ if err != nil {
+ return nil, err
+ }
+
+ return &http.Transport{TLSClientConfig: cfg}, nil
+}
+
+// TLSClient creates a http.Client for mutual auth
+func TLSClient(opts TLSClientOptions) (*http.Client, error) {
+ transport, err := TLSTransport(opts)
+ if err != nil {
+ return nil, err
+ }
+ return &http.Client{Transport: transport}, nil
+}
+
+// DefaultTimeout the default request timeout
+var DefaultTimeout = 30 * time.Second
+
+// Runtime represents an API client that uses the transport
+// to make http requests based on a swagger specification.
+type Runtime struct {
+ DefaultMediaType string
+ DefaultAuthentication runtime.ClientAuthInfoWriter
+ Consumers map[string]runtime.Consumer
+ Producers map[string]runtime.Producer
+
+ Transport http.RoundTripper
+ Jar http.CookieJar
+ //Spec *spec.Document
+ Host string
+ BasePath string
+ Formats strfmt.Registry
+ Context context.Context
+
+ Debug bool
+ logger logger.Logger
+
+ clientOnce *sync.Once
+ client *http.Client
+ schemes []string
+}
+
+// New creates a new default runtime for a swagger api runtime.Client
+func New(host, basePath string, schemes []string) *Runtime {
+ var rt Runtime
+ rt.DefaultMediaType = runtime.JSONMime
+
+ // TODO: actually infer this stuff from the spec
+ rt.Consumers = map[string]runtime.Consumer{
+ runtime.JSONMime: runtime.JSONConsumer(),
+ runtime.XMLMime: runtime.XMLConsumer(),
+ runtime.TextMime: runtime.TextConsumer(),
+ runtime.HTMLMime: runtime.TextConsumer(),
+ runtime.DefaultMime: runtime.ByteStreamConsumer(),
+ }
+ rt.Producers = map[string]runtime.Producer{
+ runtime.JSONMime: runtime.JSONProducer(),
+ runtime.XMLMime: runtime.XMLProducer(),
+ runtime.TextMime: runtime.TextProducer(),
+ runtime.HTMLMime: runtime.TextProducer(),
+ runtime.DefaultMime: runtime.ByteStreamProducer(),
+ }
+ rt.Transport = http.DefaultTransport
+ rt.Jar = nil
+ rt.Host = host
+ rt.BasePath = basePath
+ rt.Context = context.Background()
+ rt.clientOnce = new(sync.Once)
+ if !strings.HasPrefix(rt.BasePath, "/") {
+ rt.BasePath = "/" + rt.BasePath
+ }
+
+ rt.Debug = logger.DebugEnabled()
+ rt.logger = logger.StandardLogger{}
+
+ if len(schemes) > 0 {
+ rt.schemes = schemes
+ }
+ return &rt
+}
+
+// NewWithClient allows you to create a new transport with a configured http.Client
+func NewWithClient(host, basePath string, schemes []string, client *http.Client) *Runtime {
+ rt := New(host, basePath, schemes)
+ if client != nil {
+ rt.clientOnce.Do(func() {
+ rt.client = client
+ })
+ }
+ return rt
+}
+
+func (r *Runtime) pickScheme(schemes []string) string {
+ if v := r.selectScheme(r.schemes); v != "" {
+ return v
+ }
+ if v := r.selectScheme(schemes); v != "" {
+ return v
+ }
+ return "http"
+}
+
+func (r *Runtime) selectScheme(schemes []string) string {
+ schLen := len(schemes)
+ if schLen == 0 {
+ return ""
+ }
+
+ scheme := schemes[0]
+ // prefer https, but skip when not possible
+ if scheme != "https" && schLen > 1 {
+ for _, sch := range schemes {
+ if sch == "https" {
+ scheme = sch
+ break
+ }
+ }
+ }
+ return scheme
+}
+func transportOrDefault(left, right http.RoundTripper) http.RoundTripper {
+ if left == nil {
+ return right
+ }
+ return left
+}
+
+// EnableConnectionReuse drains the remaining body from a response
+// so that go will reuse the TCP connections.
+//
+// This is not enabled by default because there are servers where
+// the response never gets closed and that would make the code hang forever.
+// So instead it's provided as a http client middleware that can be used to override
+// any request.
+func (r *Runtime) EnableConnectionReuse() {
+ if r.client == nil {
+ r.Transport = KeepAliveTransport(
+ transportOrDefault(r.Transport, http.DefaultTransport),
+ )
+ return
+ }
+
+ r.client.Transport = KeepAliveTransport(
+ transportOrDefault(r.client.Transport,
+ transportOrDefault(r.Transport, http.DefaultTransport),
+ ),
+ )
+}
+
+// Submit a request and when there is a body on success it will turn that into the result
+// all other things are turned into an api error for swagger which retains the status code
+func (r *Runtime) Submit(operation *runtime.ClientOperation) (interface{}, error) {
+ params, readResponse, auth := operation.Params, operation.Reader, operation.AuthInfo
+
+ request, err := newRequest(operation.Method, operation.PathPattern, params)
+ if err != nil {
+ return nil, err
+ }
+
+ var accept []string
+ accept = append(accept, operation.ProducesMediaTypes...)
+ if err = request.SetHeaderParam(runtime.HeaderAccept, accept...); err != nil {
+ return nil, err
+ }
+
+ if auth == nil && r.DefaultAuthentication != nil {
+ auth = r.DefaultAuthentication
+ }
+ //if auth != nil {
+ // if err := auth.AuthenticateRequest(request, r.Formats); err != nil {
+ // return nil, err
+ // }
+ //}
+
+ // TODO: pick appropriate media type
+ cmt := r.DefaultMediaType
+ for _, mediaType := range operation.ConsumesMediaTypes {
+ // Pick first non-empty media type
+ if mediaType != "" {
+ cmt = mediaType
+ break
+ }
+ }
+
+ if _, ok := r.Producers[cmt]; !ok && cmt != runtime.MultipartFormMime && cmt != runtime.URLencodedFormMime {
+ return nil, fmt.Errorf("none of producers: %v registered. try %s", r.Producers, cmt)
+ }
+
+ req, err := request.buildHTTP(cmt, r.BasePath, r.Producers, r.Formats, auth)
+ if err != nil {
+ return nil, err
+ }
+ req.URL.Scheme = r.pickScheme(operation.Schemes)
+ req.URL.Host = r.Host
+
+ r.clientOnce.Do(func() {
+ r.client = &http.Client{
+ Transport: r.Transport,
+ Jar: r.Jar,
+ }
+ })
+
+ if r.Debug {
+ b, err2 := httputil.DumpRequestOut(req, true)
+ if err2 != nil {
+ return nil, err2
+ }
+ r.logger.Debugf("%s\n", string(b))
+ }
+
+ var hasTimeout bool
+ pctx := operation.Context
+ if pctx == nil {
+ pctx = r.Context
+ } else {
+ hasTimeout = true
+ }
+ if pctx == nil {
+ pctx = context.Background()
+ }
+ var ctx context.Context
+ var cancel context.CancelFunc
+ if hasTimeout {
+ ctx, cancel = context.WithCancel(pctx)
+ } else {
+ ctx, cancel = context.WithTimeout(pctx, request.timeout)
+ }
+ defer cancel()
+
+ client := operation.Client
+ if client == nil {
+ client = r.client
+ }
+ req = req.WithContext(ctx)
+ res, err := client.Do(req) // make requests, by default follows 10 redirects before failing
+ if err != nil {
+ return nil, err
+ }
+ defer res.Body.Close()
+
+ if r.Debug {
+ b, err2 := httputil.DumpResponse(res, true)
+ if err2 != nil {
+ return nil, err2
+ }
+ r.logger.Debugf("%s\n", string(b))
+ }
+
+ ct := res.Header.Get(runtime.HeaderContentType)
+ if ct == "" { // this should really really never occur
+ ct = r.DefaultMediaType
+ }
+
+ mt, _, err := mime.ParseMediaType(ct)
+ if err != nil {
+ return nil, fmt.Errorf("parse content type: %s", err)
+ }
+
+ cons, ok := r.Consumers[mt]
+ if !ok {
+ if cons, ok = r.Consumers["*/*"]; !ok {
+ // scream about not knowing what to do
+ return nil, fmt.Errorf("no consumer: %q", ct)
+ }
+ }
+ return readResponse.ReadResponse(response{res}, cons)
+}
+
+// SetDebug changes the debug flag.
+// It ensures that client and middlewares have the set debug level.
+func (r *Runtime) SetDebug(debug bool) {
+ r.Debug = debug
+ middleware.Debug = debug
+}
+
+// SetLogger changes the logger stream.
+// It ensures that client and middlewares use the same logger.
+func (r *Runtime) SetLogger(logger logger.Logger) {
+ r.logger = logger
+ middleware.Logger = logger
+}