From 0327395998fb9b446ec151ac6316079303c3b157 Mon Sep 17 00:00:00 2001 From: Fabian Ruff Date: Tue, 12 Dec 2017 00:03:06 +0100 Subject: [PATCH] Update to go-swagger 0.13 A lot of files changed but actually not much changed Fixes #92 --- Makefile | 7 +- glide.lock | 20 +- glide.yaml | 67 ++- .../operations/create_cluster_parameters.go | 10 +- .../operations/terminate_cluster_responses.go | 14 +- .../operations/update_cluster_parameters.go | 10 +- pkg/api/models/api_versions.go | 3 - pkg/api/models/credentials.go | 3 - pkg/api/models/error.go | 7 - pkg/api/models/event.go | 13 - pkg/api/models/info.go | 3 - pkg/api/models/kluster.go | 7 - pkg/api/models/kluster_info.go | 15 - pkg/api/models/kluster_phase.go | 1 - pkg/api/models/kluster_spec.go | 17 - pkg/api/models/kluster_status.go | 13 - pkg/api/models/node_pool.go | 11 - pkg/api/models/node_pool_config.go | 5 - pkg/api/models/node_pool_info.go | 11 - pkg/api/models/openstack_metadata.go | 43 -- pkg/api/models/openstack_spec.go | 9 - pkg/api/models/principal.go | 13 - .../operations/create_cluster_parameters.go | 2 +- .../get_cluster_credentials_parameters.go | 2 +- .../get_cluster_events_parameters.go | 2 +- .../operations/get_cluster_info_parameters.go | 2 +- .../get_openstack_metadata_parameters.go | 2 +- pkg/api/rest/operations/info_parameters.go | 2 +- .../list_api_versions_parameters.go | 2 +- .../operations/list_clusters_parameters.go | 2 +- .../operations/show_cluster_parameters.go | 2 +- pkg/api/rest/operations/terminate_cluster.go | 5 - .../terminate_cluster_parameters.go | 2 +- .../operations/terminate_cluster_responses.go | 23 +- .../operations/update_cluster_parameters.go | 2 +- pkg/api/spec/embedded_spec.go | 8 +- swagger.yml | 3 - vendor/github.com/go-openapi/loads/spec.go | 2 +- .../go-openapi/runtime/client/request.go | 61 +-- .../go-openapi/runtime/client/runtime.go | 17 +- .../go-openapi/runtime/client_request.go | 2 +- .../runtime/middleware/negotiate.go | 17 +- vendor/github.com/go-openapi/spec/expander.go | 24 +- vendor/github.com/go-openapi/spec/items.go | 12 +- .../github.com/go-openapi/spec/refmodifier.go | 82 ++++ vendor/github.com/go-openapi/spec/swagger.go | 2 +- vendor/github.com/go-openapi/swag/util.go | 42 +- .../go-openapi/validate/object_validator.go | 36 ++ .../github.com/go-openapi/validate/schema.go | 16 +- .../go-openapi/validate/validator.go | 5 +- .../github.com/go-openapi/validate/values.go | 6 +- vendor/github.com/gorilla/handlers/LICENSE | 22 - .../github.com/gorilla/handlers/canonical.go | 74 ---- .../github.com/gorilla/handlers/compress.go | 148 ------- vendor/github.com/gorilla/handlers/cors.go | 327 -------------- vendor/github.com/gorilla/handlers/doc.go | 9 - .../github.com/gorilla/handlers/handlers.go | 399 ------------------ .../gorilla/handlers/handlers_go18.go | 21 - .../gorilla/handlers/handlers_pre18.go | 7 - .../gorilla/handlers/proxy_headers.go | 120 ------ .../github.com/gorilla/handlers/recovery.go | 91 ---- .../mailru/easyjson/jlexer/lexer.go | 27 ++ .../mailru/easyjson/jwriter/writer.go | 7 + .../mitchellh/mapstructure/mapstructure.go | 22 +- 64 files changed, 379 insertions(+), 1582 deletions(-) create mode 100644 vendor/github.com/go-openapi/spec/refmodifier.go delete mode 100644 vendor/github.com/gorilla/handlers/LICENSE delete mode 100644 vendor/github.com/gorilla/handlers/canonical.go delete mode 100644 vendor/github.com/gorilla/handlers/compress.go delete mode 100644 vendor/github.com/gorilla/handlers/cors.go delete mode 100644 vendor/github.com/gorilla/handlers/doc.go delete mode 100644 vendor/github.com/gorilla/handlers/handlers.go delete mode 100644 vendor/github.com/gorilla/handlers/handlers_go18.go delete mode 100644 vendor/github.com/gorilla/handlers/handlers_pre18.go delete mode 100644 vendor/github.com/gorilla/handlers/proxy_headers.go delete mode 100644 vendor/github.com/gorilla/handlers/recovery.go diff --git a/Makefile b/Makefile index c4a37e73ea..de17f01b6c 100644 --- a/Makefile +++ b/Makefile @@ -18,7 +18,7 @@ endif HAS_GLIDE := $(shell command -v glide;) HAS_GLIDE_VC := $(shell command -v glide-vc;) -GO_SWAGGER_VERSION := 0.12.0 +GO_SWAGGER_VERSION := 0.13.0 SWAGGER_BIN := bin/$(GOOS)/swagger-$(GO_SWAGGER_VERSION) .PHONY: all test clean code-gen client-gen informer-gen lister-gen vendor @@ -71,7 +71,8 @@ gh-pages: pkg/api/rest/operations/kubernikus_api.go: swagger.yml ifneq (,$(wildcard $(SWAGGER_BIN))) $(SWAGGER_BIN) generate server --name kubernikus --target pkg/api --model-package models \ - --server-package rest --flag-strategy pflag --principal models.Principal --exclude-main + --server-package rest --flag-strategy pflag --principal models.Principal --exclude-main \ + --skip-flatten sed -i '' -e 's/int64 `json:"\([^,]*\),omitempty"`/int64 `json:"\1"`/' pkg/api/models/*.go sed -e's/^package.*/package spec/' pkg/api/rest/embedded_spec.go > pkg/api/spec/embedded_spec.go rm pkg/api/rest/embedded_spec.go @@ -87,7 +88,7 @@ pkg/api/client/kubernikus_client.go: swagger.yml ifneq (,$(wildcard $(SWAGGER_BIN))) $(SWAGGER_BIN) generate client --name kubernikus --target pkg/api --client-package client \ --existing-models github.com/sapcc/kubernikus/pkg/api/models \ - --default-scheme=https \ + --default-scheme=https --skip-flatten \ --principal models.Principal else $(warning WARNING: $(SWAGGER_BIN) missing. Run `make bootstrap` to fix.) diff --git a/glide.lock b/glide.lock index 28e7d1f11b..3861ec7bc6 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ -hash: deb0bca036f39bd5d24022c51416f03e7b60ce63e87c6fa540fd8e5ca4b03f58 -updated: 2017-12-01T11:25:53.43538+01:00 +hash: cc8e24ae5a8b9b242a6d595f84f409f3f01f41b447bbd0d2d88ef024d53a033d +updated: 2017-12-11T23:57:04.147704+01:00 imports: - name: github.com/ajeddeloh/yaml version: 1072abfea31191db507785e2e0c1b8d1440d35a5 @@ -93,9 +93,9 @@ imports: - name: github.com/go-openapi/jsonreference version: 36d33bfe519efae5632669801b180bf1a245da3b - name: github.com/go-openapi/loads - version: a80dea3052f00e5f032e860dd7355cd0cc67e24d + version: c3e1ca4c0b6160cac10aeef7e8b425cc95b9c820 - name: github.com/go-openapi/runtime - version: bf2ff8f7150788b1c7256abb0805ba0410cbbabb + version: 2da70401d8fa078b6fecdd7afdf3b589ae9669e4 subpackages: - client - flagext @@ -105,13 +105,13 @@ imports: - middleware/untyped - security - name: github.com/go-openapi/spec - version: 3faa0055dbbf2110abc1f3b4e3adbb22721e96e7 + version: a4fa9574c7aa73b2fc54e251eb9524d0482bb592 - name: github.com/go-openapi/strfmt version: 610b6cacdcde6852f4de68998bd20ce1dac85b22 - name: github.com/go-openapi/swag - version: f3f9494671f93fcff853e3c6e9e948b3eb71e590 + version: cf0bdb963811675a4d7e74901cefc7411a1df939 - name: github.com/go-openapi/validate - version: 8a82927c942c94794a5cd8b8b50ce2f48a955c0c + version: a52193aca9d575f354d8be388254c134765ea793 - name: github.com/go-stack/stack version: 259ab82a6cad3992b4e21ff5cac294ccb06474bc - name: github.com/gobwas/glob @@ -167,8 +167,6 @@ imports: - openstack/networking/v2/subnets - openstack/utils - pagination -- name: github.com/gorilla/handlers - version: 90663712d74cb411cbef281bc1e08c19d1a76145 - name: github.com/hashicorp/golang-lru version: a0d98a5f288019575c6d1f4bb1573fef2d1fcdc4 subpackages: @@ -194,7 +192,7 @@ imports: - name: github.com/kr/logfmt version: b84e30acd515aadc4b783ad4ff83aff3299bdfe0 - name: github.com/mailru/easyjson - version: 2a92e673c9a6302dd05c3a691ae1f24aef46457d + version: 5f62e4f3afa2f576dc86531b7df4d966b19ef8f8 subpackages: - buffer - jlexer @@ -210,7 +208,7 @@ imports: subpackages: - pbutil - name: github.com/mitchellh/mapstructure - version: d0303fe809921458f417bcf828397a65db30a7e4 + version: 06020f85339e21b2478f756a78e295255ffa4d6a - name: github.com/pkg/errors version: 645ef00459ed84a119197bfb8d8205042c6df63d - name: github.com/pmezard/go-difflib diff --git a/glide.yaml b/glide.yaml index 7bff43b567..49ea8d45ff 100644 --- a/glide.yaml +++ b/glide.yaml @@ -29,46 +29,45 @@ import: version: 0.6.0 subpackages: - log -# Dependencies extracted from go-swagger 0.12.0 -- package: github.com/databus23/guttle -- package: github.com/go-openapi/jsonpointer - version: 779f45308c19820f1a69e9a4cd965f496e0da10f -- package: github.com/go-openapi/loads - version: a80dea3052f00e5f032e860dd7355cd0cc67e24d +- package: github.com/prometheus/prometheus + version: ^2.0.0 + subpackages: + - client_go + - client_model + - common + - procfs +# Dependencies extracted from go-swagger 0.13.0 +- package: github.com/go-openapi/errors + version: 03cfca65330da08a5a440053faf994a3c682b5bf +- package: github.com/go-openapi/jsonreference + version: 36d33bfe519efae5632669801b180bf1a245da3b +- package: github.com/go-openapi/runtime + version: 2da70401d8fa078b6fecdd7afdf3b589ae9669e4 +- package: github.com/go-openapi/spec + version: a4fa9574c7aa73b2fc54e251eb9524d0482bb592 - package: gopkg.in/yaml.v2 version: eb3733d160e74a9c7e442f435eb3bea458e1d19f +- package: github.com/PuerkitoBio/purell + version: 0bcb03f4b4d0a9428594752bd2a3b9aa0a9d4bd4 - package: github.com/PuerkitoBio/urlesc version: de5bf2ad457846296e2031421a34e2568e304e35 -- package: github.com/go-openapi/analysis - version: 8ed83f2ea9f00f945516462951a288eaa68bf0d6 +- package: github.com/go-openapi/loads + version: c3e1ca4c0b6160cac10aeef7e8b425cc95b9c820 +- package: github.com/mitchellh/mapstructure + version: 06020f85339e21b2478f756a78e295255ffa4d6a +- package: github.com/go-openapi/jsonpointer + version: 779f45308c19820f1a69e9a4cd965f496e0da10f +- package: github.com/go-openapi/strfmt + version: 610b6cacdcde6852f4de68998bd20ce1dac85b22 - package: github.com/go-openapi/swag - version: f3f9494671f93fcff853e3c6e9e948b3eb71e590 -- package: github.com/mailru/easyjson - version: 2a92e673c9a6302dd05c3a691ae1f24aef46457d + version: cf0bdb963811675a4d7e74901cefc7411a1df939 - package: gopkg.in/mgo.v2 version: 3f83fa5005286a7fe593b055f0d7771a7dce4655 -- package: github.com/PuerkitoBio/purell - version: 0bcb03f4b4d0a9428594752bd2a3b9aa0a9d4bd4 -- package: github.com/go-openapi/strfmt - version: 610b6cacdcde6852f4de68998bd20ce1dac85b22 -- package: github.com/go-openapi/validate - version: 8a82927c942c94794a5cd8b8b50ce2f48a955c0c -- package: github.com/go-openapi/runtime - version: bf2ff8f7150788b1c7256abb0805ba0410cbbabb -- package: github.com/go-openapi/spec - version: 3faa0055dbbf2110abc1f3b4e3adbb22721e96e7 -- package: github.com/mitchellh/mapstructure - version: d0303fe809921458f417bcf828397a65db30a7e4 - package: github.com/asaskevich/govalidator version: 73945b6115bfbbcc57d89b7316e28109364124e1 -- package: github.com/go-openapi/errors - version: 03cfca65330da08a5a440053faf994a3c682b5bf -- package: github.com/go-openapi/jsonreference - version: 36d33bfe519efae5632669801b180bf1a245da3b -- package: github.com/prometheus/prometheus - version: ^2.0.0 - subpackages: - - client_go - - client_model - - common - - procfs +- package: github.com/go-openapi/analysis + version: 8ed83f2ea9f00f945516462951a288eaa68bf0d6 +- package: github.com/go-openapi/validate + version: a52193aca9d575f354d8be388254c134765ea793 +- package: github.com/mailru/easyjson + version: 5f62e4f3afa2f576dc86531b7df4d966b19ef8f8 diff --git a/pkg/api/client/operations/create_cluster_parameters.go b/pkg/api/client/operations/create_cluster_parameters.go index b8dc012024..881ce7eb94 100644 --- a/pkg/api/client/operations/create_cluster_parameters.go +++ b/pkg/api/client/operations/create_cluster_parameters.go @@ -124,12 +124,10 @@ func (o *CreateClusterParams) WriteToRequest(r runtime.ClientRequest, reg strfmt } var res []error - if o.Body == nil { - o.Body = new(models.Kluster) - } - - if err := r.SetBodyParam(o.Body); err != nil { - return err + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } } if len(res) > 0 { diff --git a/pkg/api/client/operations/terminate_cluster_responses.go b/pkg/api/client/operations/terminate_cluster_responses.go index 91c20dc261..5ac50ffc74 100644 --- a/pkg/api/client/operations/terminate_cluster_responses.go +++ b/pkg/api/client/operations/terminate_cluster_responses.go @@ -54,20 +54,14 @@ func NewTerminateClusterAccepted() *TerminateClusterAccepted { OK */ type TerminateClusterAccepted struct { - Payload TerminateClusterAcceptedBody } func (o *TerminateClusterAccepted) Error() string { - return fmt.Sprintf("[DELETE /api/v1/clusters/{name}][%d] terminateClusterAccepted %+v", 202, o.Payload) + return fmt.Sprintf("[DELETE /api/v1/clusters/{name}][%d] terminateClusterAccepted ", 202) } func (o *TerminateClusterAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - // response payload - if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { - return err - } - return nil } @@ -108,9 +102,3 @@ func (o *TerminateClusterDefault) readResponse(response runtime.ClientResponse, return nil } - -/*TerminateClusterAcceptedBody terminate cluster accepted body -swagger:model TerminateClusterAcceptedBody -*/ - -type TerminateClusterAcceptedBody interface{} diff --git a/pkg/api/client/operations/update_cluster_parameters.go b/pkg/api/client/operations/update_cluster_parameters.go index 234a926126..47e690434d 100644 --- a/pkg/api/client/operations/update_cluster_parameters.go +++ b/pkg/api/client/operations/update_cluster_parameters.go @@ -137,12 +137,10 @@ func (o *UpdateClusterParams) WriteToRequest(r runtime.ClientRequest, reg strfmt } var res []error - if o.Body == nil { - o.Body = new(models.Kluster) - } - - if err := r.SetBodyParam(o.Body); err != nil { - return err + if o.Body != nil { + if err := r.SetBodyParam(o.Body); err != nil { + return err + } } // path param name diff --git a/pkg/api/models/api_versions.go b/pkg/api/models/api_versions.go index 90d0c9b1d6..766acc2424 100644 --- a/pkg/api/models/api_versions.go +++ b/pkg/api/models/api_versions.go @@ -15,7 +15,6 @@ import ( // APIVersions Api versions // swagger:model ApiVersions - type APIVersions struct { // versions are the api versions that are available. @@ -23,8 +22,6 @@ type APIVersions struct { Versions []string `json:"versions"` } -/* polymorph ApiVersions versions false */ - // Validate validates this Api versions func (m *APIVersions) Validate(formats strfmt.Registry) error { var res []error diff --git a/pkg/api/models/credentials.go b/pkg/api/models/credentials.go index 34e426f6d1..2782782ef7 100644 --- a/pkg/api/models/credentials.go +++ b/pkg/api/models/credentials.go @@ -14,15 +14,12 @@ import ( // Credentials credentials // swagger:model Credentials - type Credentials struct { // kubeconfig Kubeconfig string `json:"kubeconfig,omitempty"` } -/* polymorph Credentials kubeconfig false */ - // Validate validates this credentials func (m *Credentials) Validate(formats strfmt.Registry) error { var res []error diff --git a/pkg/api/models/error.go b/pkg/api/models/error.go index 043566388c..e5f97fdd70 100644 --- a/pkg/api/models/error.go +++ b/pkg/api/models/error.go @@ -16,7 +16,6 @@ import ( // Error the error model is a model for all the error responses coming from Kubernikus // // swagger:model error - type Error struct { // The error code @@ -31,12 +30,6 @@ type Error struct { Message *string `json:"message"` } -/* polymorph error code false */ - -/* polymorph error helpUrl false */ - -/* polymorph error message false */ - // Validate validates this error func (m *Error) Validate(formats strfmt.Registry) error { var res []error diff --git a/pkg/api/models/event.go b/pkg/api/models/event.go index 02dbf27faf..a1a3e7e0c1 100644 --- a/pkg/api/models/event.go +++ b/pkg/api/models/event.go @@ -17,7 +17,6 @@ import ( // Event event // swagger:model Event - type Event struct { // The number of times this event has occurred. @@ -39,18 +38,6 @@ type Event struct { Type string `json:"type,omitempty"` } -/* polymorph Event count false */ - -/* polymorph Event firstTimestamp false */ - -/* polymorph Event lastTimestamp false */ - -/* polymorph Event message false */ - -/* polymorph Event reason false */ - -/* polymorph Event type false */ - // Validate validates this event func (m *Event) Validate(formats strfmt.Registry) error { var res []error diff --git a/pkg/api/models/info.go b/pkg/api/models/info.go index 014af180df..2559f21c15 100644 --- a/pkg/api/models/info.go +++ b/pkg/api/models/info.go @@ -14,15 +14,12 @@ import ( // Info info // swagger:model Info - type Info struct { // version Version string `json:"version,omitempty"` } -/* polymorph Info version false */ - // Validate validates this info func (m *Info) Validate(formats strfmt.Registry) error { var res []error diff --git a/pkg/api/models/kluster.go b/pkg/api/models/kluster.go index e9a7e7199e..b83e4300a7 100644 --- a/pkg/api/models/kluster.go +++ b/pkg/api/models/kluster.go @@ -15,7 +15,6 @@ import ( // Kluster kluster // swagger:model Kluster - type Kluster struct { // name of the cluster @@ -30,12 +29,6 @@ type Kluster struct { Status KlusterStatus `json:"status,omitempty"` } -/* polymorph Kluster name false */ - -/* polymorph Kluster spec false */ - -/* polymorph Kluster status false */ - // Validate validates this kluster func (m *Kluster) Validate(formats strfmt.Registry) error { var res []error diff --git a/pkg/api/models/kluster_info.go b/pkg/api/models/kluster_info.go index 5caf780a88..7f49df2293 100644 --- a/pkg/api/models/kluster_info.go +++ b/pkg/api/models/kluster_info.go @@ -14,7 +14,6 @@ import ( // KlusterInfo kluster info // swagger:model KlusterInfo - type KlusterInfo struct { // binaries @@ -24,10 +23,6 @@ type KlusterInfo struct { SetupCommand string `json:"setupCommand,omitempty"` } -/* polymorph KlusterInfo binaries false */ - -/* polymorph KlusterInfo setupCommand false */ - // Validate validates this kluster info func (m *KlusterInfo) Validate(formats strfmt.Registry) error { var res []error @@ -72,7 +67,6 @@ func (m *KlusterInfo) UnmarshalBinary(b []byte) error { // Binaries binaries // swagger:model Binaries - type Binaries struct { // links @@ -82,10 +76,6 @@ type Binaries struct { Name string `json:"name,omitempty"` } -/* polymorph Binaries links false */ - -/* polymorph Binaries name false */ - // Validate validates this binaries func (m *Binaries) Validate(formats strfmt.Registry) error { var res []error @@ -130,7 +120,6 @@ func (m *Binaries) UnmarshalBinary(b []byte) error { // Link link // swagger:model Link - type Link struct { // link @@ -140,10 +129,6 @@ type Link struct { Platform string `json:"platform,omitempty"` } -/* polymorph Link link false */ - -/* polymorph Link platform false */ - // Validate validates this link func (m *Link) Validate(formats strfmt.Registry) error { var res []error diff --git a/pkg/api/models/kluster_phase.go b/pkg/api/models/kluster_phase.go index 39d71da15e..28b4ab6427 100644 --- a/pkg/api/models/kluster_phase.go +++ b/pkg/api/models/kluster_phase.go @@ -16,7 +16,6 @@ import ( // KlusterPhase kluster phase // swagger:model KlusterPhase - type KlusterPhase string const ( diff --git a/pkg/api/models/kluster_spec.go b/pkg/api/models/kluster_spec.go index 297678a955..81425ca4a2 100644 --- a/pkg/api/models/kluster_spec.go +++ b/pkg/api/models/kluster_spec.go @@ -15,7 +15,6 @@ import ( // KlusterSpec kluster spec // swagger:model KlusterSpec - type KlusterSpec struct { // advertise address @@ -46,22 +45,6 @@ type KlusterSpec struct { ServiceCIDR string `json:"serviceCIDR,omitempty"` } -/* polymorph KlusterSpec advertiseAddress false */ - -/* polymorph KlusterSpec clusterCIDR false */ - -/* polymorph KlusterSpec dnsAddress false */ - -/* polymorph KlusterSpec dnsDomain false */ - -/* polymorph KlusterSpec name false */ - -/* polymorph KlusterSpec nodePools false */ - -/* polymorph KlusterSpec openstack false */ - -/* polymorph KlusterSpec serviceCIDR false */ - // Validate validates this kluster spec func (m *KlusterSpec) Validate(formats strfmt.Registry) error { var res []error diff --git a/pkg/api/models/kluster_status.go b/pkg/api/models/kluster_status.go index 247015a8cf..1820b6c8af 100644 --- a/pkg/api/models/kluster_status.go +++ b/pkg/api/models/kluster_status.go @@ -14,7 +14,6 @@ import ( // KlusterStatus kluster status // swagger:model KlusterStatus - type KlusterStatus struct { // apiserver @@ -36,18 +35,6 @@ type KlusterStatus struct { Wormhole string `json:"wormhole,omitempty"` } -/* polymorph KlusterStatus apiserver false */ - -/* polymorph KlusterStatus message false */ - -/* polymorph KlusterStatus nodePools false */ - -/* polymorph KlusterStatus phase false */ - -/* polymorph KlusterStatus version false */ - -/* polymorph KlusterStatus wormhole false */ - // Validate validates this kluster status func (m *KlusterStatus) Validate(formats strfmt.Registry) error { var res []error diff --git a/pkg/api/models/node_pool.go b/pkg/api/models/node_pool.go index 0795588186..786f6fd160 100644 --- a/pkg/api/models/node_pool.go +++ b/pkg/api/models/node_pool.go @@ -15,7 +15,6 @@ import ( // NodePool node pool // swagger:model NodePool - type NodePool struct { // config @@ -39,16 +38,6 @@ type NodePool struct { Size int64 `json:"size"` } -/* polymorph NodePool config false */ - -/* polymorph NodePool flavor false */ - -/* polymorph NodePool image false */ - -/* polymorph NodePool name false */ - -/* polymorph NodePool size false */ - // Validate validates this node pool func (m *NodePool) Validate(formats strfmt.Registry) error { var res []error diff --git a/pkg/api/models/node_pool_config.go b/pkg/api/models/node_pool_config.go index d54e1d4658..e37aa32d12 100644 --- a/pkg/api/models/node_pool_config.go +++ b/pkg/api/models/node_pool_config.go @@ -14,7 +14,6 @@ import ( // NodePoolConfig node pool config // swagger:model NodePoolConfig - type NodePoolConfig struct { // repair @@ -24,10 +23,6 @@ type NodePoolConfig struct { Upgrade bool `json:"upgrade,omitempty"` } -/* polymorph NodePoolConfig repair false */ - -/* polymorph NodePoolConfig upgrade false */ - // Validate validates this node pool config func (m *NodePoolConfig) Validate(formats strfmt.Registry) error { var res []error diff --git a/pkg/api/models/node_pool_info.go b/pkg/api/models/node_pool_info.go index 6f3f3c6e86..ddddb0123d 100644 --- a/pkg/api/models/node_pool_info.go +++ b/pkg/api/models/node_pool_info.go @@ -14,7 +14,6 @@ import ( // NodePoolInfo node pool info // swagger:model NodePoolInfo - type NodePoolInfo struct { // healthy @@ -33,16 +32,6 @@ type NodePoolInfo struct { Size int64 `json:"size"` } -/* polymorph NodePoolInfo healthy false */ - -/* polymorph NodePoolInfo name false */ - -/* polymorph NodePoolInfo running false */ - -/* polymorph NodePoolInfo schedulable false */ - -/* polymorph NodePoolInfo size false */ - // Validate validates this node pool info func (m *NodePoolInfo) Validate(formats strfmt.Registry) error { var res []error diff --git a/pkg/api/models/openstack_metadata.go b/pkg/api/models/openstack_metadata.go index f67f57ebe8..cbe47343f5 100644 --- a/pkg/api/models/openstack_metadata.go +++ b/pkg/api/models/openstack_metadata.go @@ -16,7 +16,6 @@ import ( // OpenstackMetadata openstack metadata // swagger:model OpenstackMetadata - type OpenstackMetadata struct { // flavors @@ -32,14 +31,6 @@ type OpenstackMetadata struct { SecurityGroups []*SecurityGroup `json:"securityGroups"` } -/* polymorph OpenstackMetadata flavors false */ - -/* polymorph OpenstackMetadata keyPairs false */ - -/* polymorph OpenstackMetadata routers false */ - -/* polymorph OpenstackMetadata securityGroups false */ - // Validate validates this openstack metadata func (m *OpenstackMetadata) Validate(formats strfmt.Registry) error { var res []error @@ -198,7 +189,6 @@ func (m *OpenstackMetadata) UnmarshalBinary(b []byte) error { // Flavor flavor // swagger:model Flavor - type Flavor struct { // id @@ -208,10 +198,6 @@ type Flavor struct { Name string `json:"name,omitempty"` } -/* polymorph Flavor id false */ - -/* polymorph Flavor name false */ - // Validate validates this flavor func (m *Flavor) Validate(formats strfmt.Registry) error { var res []error @@ -242,15 +228,12 @@ func (m *Flavor) UnmarshalBinary(b []byte) error { // KeyPair key pair // swagger:model KeyPair - type KeyPair struct { // name Name string `json:"name,omitempty"` } -/* polymorph KeyPair name false */ - // Validate validates this key pair func (m *KeyPair) Validate(formats strfmt.Registry) error { var res []error @@ -281,7 +264,6 @@ func (m *KeyPair) UnmarshalBinary(b []byte) error { // Router router // swagger:model Router - type Router struct { // id @@ -294,12 +276,6 @@ type Router struct { Networks []*Network `json:"networks"` } -/* polymorph Router id false */ - -/* polymorph Router name false */ - -/* polymorph Router networks false */ - // Validate validates this router func (m *Router) Validate(formats strfmt.Registry) error { var res []error @@ -362,7 +338,6 @@ func (m *Router) UnmarshalBinary(b []byte) error { // Network network // swagger:model Network - type Network struct { // id @@ -375,12 +350,6 @@ type Network struct { Subnets []*Subnet `json:"subnets"` } -/* polymorph Network id false */ - -/* polymorph Network name false */ - -/* polymorph Network subnets false */ - // Validate validates this network func (m *Network) Validate(formats strfmt.Registry) error { var res []error @@ -443,7 +412,6 @@ func (m *Network) UnmarshalBinary(b []byte) error { // Subnet subnet // swagger:model Subnet - type Subnet struct { // c ID r @@ -456,12 +424,6 @@ type Subnet struct { Name string `json:"name,omitempty"` } -/* polymorph Subnet CIDR false */ - -/* polymorph Subnet id false */ - -/* polymorph Subnet name false */ - // Validate validates this subnet func (m *Subnet) Validate(formats strfmt.Registry) error { var res []error @@ -492,7 +454,6 @@ func (m *Subnet) UnmarshalBinary(b []byte) error { // SecurityGroup security group // swagger:model SecurityGroup - type SecurityGroup struct { // id @@ -502,10 +463,6 @@ type SecurityGroup struct { Name string `json:"name,omitempty"` } -/* polymorph SecurityGroup id false */ - -/* polymorph SecurityGroup name false */ - // Validate validates this security group func (m *SecurityGroup) Validate(formats strfmt.Registry) error { var res []error diff --git a/pkg/api/models/openstack_spec.go b/pkg/api/models/openstack_spec.go index d4aabcde05..caedc4cb9b 100644 --- a/pkg/api/models/openstack_spec.go +++ b/pkg/api/models/openstack_spec.go @@ -14,7 +14,6 @@ import ( // OpenstackSpec openstack spec // swagger:model OpenstackSpec - type OpenstackSpec struct { // l b subnet ID @@ -30,14 +29,6 @@ type OpenstackSpec struct { RouterID string `json:"routerID,omitempty"` } -/* polymorph OpenstackSpec LBSubnetID false */ - -/* polymorph OpenstackSpec networkID false */ - -/* polymorph OpenstackSpec projectID false */ - -/* polymorph OpenstackSpec routerID false */ - // Validate validates this openstack spec func (m *OpenstackSpec) Validate(formats strfmt.Registry) error { var res []error diff --git a/pkg/api/models/principal.go b/pkg/api/models/principal.go index d456658e18..3f031edd7d 100644 --- a/pkg/api/models/principal.go +++ b/pkg/api/models/principal.go @@ -14,7 +14,6 @@ import ( // Principal principal // swagger:model Principal - type Principal struct { // account id @@ -36,18 +35,6 @@ type Principal struct { Roles []string `json:"roles"` } -/* polymorph Principal account false */ - -/* polymorph Principal authUrl false */ - -/* polymorph Principal domain false */ - -/* polymorph Principal id false */ - -/* polymorph Principal name false */ - -/* polymorph Principal roles false */ - // Validate validates this principal func (m *Principal) Validate(formats strfmt.Registry) error { var res []error diff --git a/pkg/api/rest/operations/create_cluster_parameters.go b/pkg/api/rest/operations/create_cluster_parameters.go index 664bedccb7..48d7d27a1c 100644 --- a/pkg/api/rest/operations/create_cluster_parameters.go +++ b/pkg/api/rest/operations/create_cluster_parameters.go @@ -30,7 +30,7 @@ func NewCreateClusterParams() CreateClusterParams { type CreateClusterParams struct { // HTTP Request Object - HTTPRequest *http.Request + HTTPRequest *http.Request `json:"-"` /* Required: true diff --git a/pkg/api/rest/operations/get_cluster_credentials_parameters.go b/pkg/api/rest/operations/get_cluster_credentials_parameters.go index 6f7d39d172..5c4fc100a0 100644 --- a/pkg/api/rest/operations/get_cluster_credentials_parameters.go +++ b/pkg/api/rest/operations/get_cluster_credentials_parameters.go @@ -28,7 +28,7 @@ func NewGetClusterCredentialsParams() GetClusterCredentialsParams { type GetClusterCredentialsParams struct { // HTTP Request Object - HTTPRequest *http.Request + HTTPRequest *http.Request `json:"-"` /* Required: true diff --git a/pkg/api/rest/operations/get_cluster_events_parameters.go b/pkg/api/rest/operations/get_cluster_events_parameters.go index 6a9e21e206..9412357cbe 100644 --- a/pkg/api/rest/operations/get_cluster_events_parameters.go +++ b/pkg/api/rest/operations/get_cluster_events_parameters.go @@ -28,7 +28,7 @@ func NewGetClusterEventsParams() GetClusterEventsParams { type GetClusterEventsParams struct { // HTTP Request Object - HTTPRequest *http.Request + HTTPRequest *http.Request `json:"-"` /* Required: true diff --git a/pkg/api/rest/operations/get_cluster_info_parameters.go b/pkg/api/rest/operations/get_cluster_info_parameters.go index 9e59eb018f..9385a0dc90 100644 --- a/pkg/api/rest/operations/get_cluster_info_parameters.go +++ b/pkg/api/rest/operations/get_cluster_info_parameters.go @@ -28,7 +28,7 @@ func NewGetClusterInfoParams() GetClusterInfoParams { type GetClusterInfoParams struct { // HTTP Request Object - HTTPRequest *http.Request + HTTPRequest *http.Request `json:"-"` /* Required: true diff --git a/pkg/api/rest/operations/get_openstack_metadata_parameters.go b/pkg/api/rest/operations/get_openstack_metadata_parameters.go index 06e7ccae41..f225e4fea4 100644 --- a/pkg/api/rest/operations/get_openstack_metadata_parameters.go +++ b/pkg/api/rest/operations/get_openstack_metadata_parameters.go @@ -26,7 +26,7 @@ func NewGetOpenstackMetadataParams() GetOpenstackMetadataParams { type GetOpenstackMetadataParams struct { // HTTP Request Object - HTTPRequest *http.Request + HTTPRequest *http.Request `json:"-"` } // BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface diff --git a/pkg/api/rest/operations/info_parameters.go b/pkg/api/rest/operations/info_parameters.go index 136590bd79..101f2ceb41 100644 --- a/pkg/api/rest/operations/info_parameters.go +++ b/pkg/api/rest/operations/info_parameters.go @@ -26,7 +26,7 @@ func NewInfoParams() InfoParams { type InfoParams struct { // HTTP Request Object - HTTPRequest *http.Request + HTTPRequest *http.Request `json:"-"` } // BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface diff --git a/pkg/api/rest/operations/list_api_versions_parameters.go b/pkg/api/rest/operations/list_api_versions_parameters.go index 2293563366..bd0b3bec78 100644 --- a/pkg/api/rest/operations/list_api_versions_parameters.go +++ b/pkg/api/rest/operations/list_api_versions_parameters.go @@ -26,7 +26,7 @@ func NewListAPIVersionsParams() ListAPIVersionsParams { type ListAPIVersionsParams struct { // HTTP Request Object - HTTPRequest *http.Request + HTTPRequest *http.Request `json:"-"` } // BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface diff --git a/pkg/api/rest/operations/list_clusters_parameters.go b/pkg/api/rest/operations/list_clusters_parameters.go index 706afea5d4..cff2681c6a 100644 --- a/pkg/api/rest/operations/list_clusters_parameters.go +++ b/pkg/api/rest/operations/list_clusters_parameters.go @@ -26,7 +26,7 @@ func NewListClustersParams() ListClustersParams { type ListClustersParams struct { // HTTP Request Object - HTTPRequest *http.Request + HTTPRequest *http.Request `json:"-"` } // BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface diff --git a/pkg/api/rest/operations/show_cluster_parameters.go b/pkg/api/rest/operations/show_cluster_parameters.go index defe0d9a18..8eaebac532 100644 --- a/pkg/api/rest/operations/show_cluster_parameters.go +++ b/pkg/api/rest/operations/show_cluster_parameters.go @@ -28,7 +28,7 @@ func NewShowClusterParams() ShowClusterParams { type ShowClusterParams struct { // HTTP Request Object - HTTPRequest *http.Request + HTTPRequest *http.Request `json:"-"` /* Required: true diff --git a/pkg/api/rest/operations/terminate_cluster.go b/pkg/api/rest/operations/terminate_cluster.go index 09e1aa2c29..c7be3adb87 100644 --- a/pkg/api/rest/operations/terminate_cluster.go +++ b/pkg/api/rest/operations/terminate_cluster.go @@ -71,8 +71,3 @@ func (o *TerminateCluster) ServeHTTP(rw http.ResponseWriter, r *http.Request) { o.Context.Respond(rw, r, route.Produces, route, res) } - -// TerminateClusterAcceptedBody terminate cluster accepted body -// swagger:model TerminateClusterAcceptedBody - -type TerminateClusterAcceptedBody interface{} diff --git a/pkg/api/rest/operations/terminate_cluster_parameters.go b/pkg/api/rest/operations/terminate_cluster_parameters.go index 82c3e5994e..7f3de60d26 100644 --- a/pkg/api/rest/operations/terminate_cluster_parameters.go +++ b/pkg/api/rest/operations/terminate_cluster_parameters.go @@ -28,7 +28,7 @@ func NewTerminateClusterParams() TerminateClusterParams { type TerminateClusterParams struct { // HTTP Request Object - HTTPRequest *http.Request + HTTPRequest *http.Request `json:"-"` /* Required: true diff --git a/pkg/api/rest/operations/terminate_cluster_responses.go b/pkg/api/rest/operations/terminate_cluster_responses.go index 44e522a20c..25536f7e94 100644 --- a/pkg/api/rest/operations/terminate_cluster_responses.go +++ b/pkg/api/rest/operations/terminate_cluster_responses.go @@ -21,11 +21,6 @@ const TerminateClusterAcceptedCode int = 202 swagger:response terminateClusterAccepted */ type TerminateClusterAccepted struct { - - /* - In: Body - */ - Payload TerminateClusterAcceptedBody `json:"body,omitempty"` } // NewTerminateClusterAccepted creates TerminateClusterAccepted with default headers values @@ -33,26 +28,12 @@ func NewTerminateClusterAccepted() *TerminateClusterAccepted { return &TerminateClusterAccepted{} } -// WithPayload adds the payload to the terminate cluster accepted response -func (o *TerminateClusterAccepted) WithPayload(payload TerminateClusterAcceptedBody) *TerminateClusterAccepted { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the terminate cluster accepted response -func (o *TerminateClusterAccepted) SetPayload(payload TerminateClusterAcceptedBody) { - o.Payload = payload -} - // WriteResponse to the client func (o *TerminateClusterAccepted) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - rw.WriteHeader(202) - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + rw.WriteHeader(202) } /*TerminateClusterDefault Error diff --git a/pkg/api/rest/operations/update_cluster_parameters.go b/pkg/api/rest/operations/update_cluster_parameters.go index 7c2d512313..8aecf94931 100644 --- a/pkg/api/rest/operations/update_cluster_parameters.go +++ b/pkg/api/rest/operations/update_cluster_parameters.go @@ -32,7 +32,7 @@ func NewUpdateClusterParams() UpdateClusterParams { type UpdateClusterParams struct { // HTTP Request Object - HTTPRequest *http.Request + HTTPRequest *http.Request `json:"-"` /* Required: true diff --git a/pkg/api/spec/embedded_spec.go b/pkg/api/spec/embedded_spec.go index 2254ce8bbf..dc9b68b924 100644 --- a/pkg/api/spec/embedded_spec.go +++ b/pkg/api/spec/embedded_spec.go @@ -131,10 +131,7 @@ func init() { "operationId": "TerminateCluster", "responses": { "202": { - "description": "OK", - "schema": { - "type": "object" - } + "description": "OK" }, "default": { "$ref": "#/responses/errorResponse" @@ -425,8 +422,7 @@ func init() { "type": "array", "items": { "$ref": "#/definitions/NodePool" - }, - "x-omitempty": true + } }, "openstack": { "$ref": "#/definitions/OpenstackSpec" diff --git a/swagger.yml b/swagger.yml index 4abf48119f..b606bad314 100644 --- a/swagger.yml +++ b/swagger.yml @@ -103,8 +103,6 @@ paths: responses: '202': description: OK - schema: - type: object default: $ref: '#/responses/errorResponse' put: @@ -344,7 +342,6 @@ definitions: ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$ nodePools: type: array - x-omitempty: true items: $ref: '#/definitions/NodePool' advertiseAddress: diff --git a/vendor/github.com/go-openapi/loads/spec.go b/vendor/github.com/go-openapi/loads/spec.go index 6d967389b1..2db5cb558d 100644 --- a/vendor/github.com/go-openapi/loads/spec.go +++ b/vendor/github.com/go-openapi/loads/spec.go @@ -186,7 +186,7 @@ func (d *Document) Expanded(options ...*spec.ExpandOptions) (*Document, error) { var expandOptions *spec.ExpandOptions if len(options) > 0 { - expandOptions = options[1] + expandOptions = options[0] } else { expandOptions = &spec.ExpandOptions{ RelativeBase: filepath.Dir(d.specFilePath), diff --git a/vendor/github.com/go-openapi/runtime/client/request.go b/vendor/github.com/go-openapi/runtime/client/request.go index 4b1ac0805e..0dcf08cdbd 100644 --- a/vendor/github.com/go-openapi/runtime/client/request.go +++ b/vendor/github.com/go-openapi/runtime/client/request.go @@ -62,7 +62,7 @@ type request struct { header http.Header query url.Values formFields url.Values - fileFields map[string]runtime.NamedReadCloser + fileFields map[string][]runtime.NamedReadCloser payload interface{} timeout time.Duration } @@ -91,7 +91,7 @@ func (r *request) BuildHTTP(mediaType string, producers map[string]runtime.Produ buf := bytes.NewBuffer(nil) if r.payload != nil || len(r.formFields) > 0 || len(r.fileFields) > 0 { body = ioutil.NopCloser(buf) - if r.fileFields != nil { + if (runtime.MultipartFormMime == mediaType && len(r.formFields) > 0) || r.fileFields != nil { pr, pw = io.Pipe() body = pr } @@ -106,7 +106,7 @@ func (r *request) BuildHTTP(mediaType string, producers map[string]runtime.Produ // check if this is a form type request if len(r.formFields) > 0 || len(r.fileFields) > 0 { // check if this is multipart - if len(r.fileFields) > 0 { + if runtime.MultipartFormMime == mediaType || len(r.fileFields) > 0 { mp := multipart.NewWriter(pw) req.Header.Set(runtime.HeaderContentType, mp.FormDataContentType()) @@ -117,29 +117,32 @@ func (r *request) BuildHTTP(mediaType string, producers map[string]runtime.Produ }() for fn, v := range r.formFields { - if len(v) > 0 { - if err := mp.WriteField(fn, v[0]); err != nil { + for _, vi := range v { + if err := mp.WriteField(fn, vi); err != nil { pw.CloseWithError(err) log.Println(err) } } } - for fn, f := range r.fileFields { - wrtr, err := mp.CreateFormFile(fn, filepath.Base(f.Name())) - if err != nil { - pw.CloseWithError(err) - log.Println(err) + defer func() { + for _, ff := range r.fileFields { + for _, ffi := range ff { + ffi.Close() + } } - defer func() { - for _, ff := range r.fileFields { - ff.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) + } + if _, err := io.Copy(wrtr, fi); err != nil { + pw.CloseWithError(err) + log.Println(err) } - - }() - if _, err := io.Copy(wrtr, f); err != nil { - pw.CloseWithError(err) - log.Println(err) } } @@ -246,25 +249,27 @@ func (r *request) SetPathParam(name string, value string) error { } // SetFileParam adds a file param to the request -func (r *request) SetFileParam(name string, file runtime.NamedReadCloser) error { - 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()) +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) + r.fileFields = make(map[string][]runtime.NamedReadCloser) } if r.formFields == nil { r.formFields = make(url.Values) } - r.fileFields[name] = file + r.fileFields[name] = files return nil } diff --git a/vendor/github.com/go-openapi/runtime/client/runtime.go b/vendor/github.com/go-openapi/runtime/client/runtime.go index 6ec9cb6dc4..69e33e802d 100644 --- a/vendor/github.com/go-openapi/runtime/client/runtime.go +++ b/vendor/github.com/go-openapi/runtime/client/runtime.go @@ -47,15 +47,18 @@ type TLSClientOptions struct { // TLSClientAuth creates a tls.Config for mutual auth func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) { - // load client cert - cert, err := tls.LoadX509KeyPair(opts.Certificate, opts.Key) - if err != nil { - return nil, fmt.Errorf("tls client cert: %v", err) - } - // create client tls config cfg := &tls.Config{} - cfg.Certificates = []tls.Certificate{cert} + + // 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} + } + cfg.InsecureSkipVerify = opts.InsecureSkipVerify // When no CA certificate is provided, default to the system cert pool diff --git a/vendor/github.com/go-openapi/runtime/client_request.go b/vendor/github.com/go-openapi/runtime/client_request.go index 3cf12b6c28..e3c53aa55a 100644 --- a/vendor/github.com/go-openapi/runtime/client_request.go +++ b/vendor/github.com/go-openapi/runtime/client_request.go @@ -45,7 +45,7 @@ type ClientRequest interface { SetPathParam(string, string) error - SetFileParam(string, NamedReadCloser) error + SetFileParam(string, ...NamedReadCloser) error SetBodyParam(interface{}) error diff --git a/vendor/github.com/go-openapi/runtime/middleware/negotiate.go b/vendor/github.com/go-openapi/runtime/middleware/negotiate.go index b9d32a0650..a9b6f27d3d 100644 --- a/vendor/github.com/go-openapi/runtime/middleware/negotiate.go +++ b/vendor/github.com/go-openapi/runtime/middleware/negotiate.go @@ -48,10 +48,11 @@ func NegotiateContentType(r *http.Request, offers []string, defaultOffer string) bestQ := -1.0 bestWild := 3 specs := header.ParseAccept(r.Header, "Accept") - for _, offer := range normalizeOffers(offers) { + for _, rawOffer := range offers { + offer := normalizeOffer(rawOffer) // No Accept header: just return the first offer. if len(specs) == 0 { - return offer + return rawOffer } for _, spec := range specs { switch { @@ -63,21 +64,21 @@ func NegotiateContentType(r *http.Request, offers []string, defaultOffer string) if spec.Q > bestQ || bestWild > 2 { bestQ = spec.Q bestWild = 2 - bestOffer = offer + bestOffer = rawOffer } case strings.HasSuffix(spec.Value, "/*"): if strings.HasPrefix(offer, spec.Value[:len(spec.Value)-1]) && (spec.Q > bestQ || bestWild > 1) { bestQ = spec.Q bestWild = 1 - bestOffer = offer + bestOffer = rawOffer } default: if spec.Value == offer && (spec.Q > bestQ || bestWild > 0) { bestQ = spec.Q bestWild = 0 - bestOffer = offer + bestOffer = rawOffer } } } @@ -87,7 +88,11 @@ func NegotiateContentType(r *http.Request, offers []string, defaultOffer string) func normalizeOffers(orig []string) (norm []string) { for _, o := range orig { - norm = append(norm, strings.SplitN(o, ";", 2)[0]) + norm = append(norm, normalizeOffer(o)) } return } + +func normalizeOffer(orig string) string { + return strings.SplitN(orig, ";", 2)[0] +} diff --git a/vendor/github.com/go-openapi/spec/expander.go b/vendor/github.com/go-openapi/spec/expander.go index b4429a21c8..7af80691fb 100644 --- a/vendor/github.com/go-openapi/spec/expander.go +++ b/vendor/github.com/go-openapi/spec/expander.go @@ -352,14 +352,12 @@ func normalizeFileRef(ref *Ref, relativeBase string) *Ref { } func (r *schemaLoader) resolveRef(currentRef, ref *Ref, node, target interface{}) error { - tgt := reflect.ValueOf(target) if tgt.Kind() != reflect.Ptr { return fmt.Errorf("resolve ref: target needs to be a pointer") } oldRef := currentRef - if currentRef != nil { debugLog("resolve ref current %s new %s", currentRef.String(), ref.String()) nextRef := nextRef(node, ref, currentRef.GetPointer()) @@ -467,8 +465,6 @@ func (r *schemaLoader) resolveRef(currentRef, ref *Ref, node, target interface{} return err } - r.currentRef = currentRef - return nil } @@ -645,14 +641,18 @@ func expandSchema(target Schema, parentRefs []string, resolver *schemaLoader) (* return resolver.root.(*Schema), nil } - // t is the new expanded schema var t *Schema - + var basePath string + b, _ := json.Marshal(target) + debugLog("Target is: %s", string(b)) for target.Ref.String() != "" { if swag.ContainsStringsCI(parentRefs, target.Ref.String()) { return &target, nil } - + basePath = target.Ref.RemoteURI() + debugLog("\n\n\n\n\nbasePath: %s", basePath) + b, _ := json.Marshal(target) + debugLog("calling Resolve with target: %s", string(b)) if err := resolver.Resolve(&target.Ref, &t); shouldStopOnError(err, resolver.options) { return &target, err } @@ -666,7 +666,13 @@ func expandSchema(target Schema, parentRefs []string, resolver *schemaLoader) (* target = *t } } - + if target.Ref.String() == "" { + b, _ := json.Marshal(target) + debugLog("before: %s", string(b)) + modifyRefs(&target, basePath) + b, _ = json.Marshal(target) + debugLog("after: %s", string(b)) + } t, err := expandItems(target, parentRefs, resolver) if shouldStopOnError(err, resolver.options) { return &target, err @@ -675,6 +681,8 @@ func expandSchema(target Schema, parentRefs []string, resolver *schemaLoader) (* target = *t } + resolver.reset() + for i := range target.AllOf { t, err := expandSchema(target.AllOf[i], parentRefs, resolver) if shouldStopOnError(err, resolver.options) { diff --git a/vendor/github.com/go-openapi/spec/items.go b/vendor/github.com/go-openapi/spec/items.go index 46944fb699..492423ef7f 100644 --- a/vendor/github.com/go-openapi/spec/items.go +++ b/vendor/github.com/go-openapi/spec/items.go @@ -28,6 +28,7 @@ type SimpleSchema struct { Items *Items `json:"items,omitempty"` CollectionFormat string `json:"collectionFormat,omitempty"` Default interface{} `json:"default,omitempty"` + Example interface{} `json:"example,omitempty"` } func (s *SimpleSchema) TypeName() string { @@ -178,9 +179,14 @@ func (i *Items) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &simpleSchema); err != nil { return err } + var vendorExtensible VendorExtensible + if err := json.Unmarshal(data, &vendorExtensible); err != nil { + return err + } i.Refable = ref i.CommonValidations = validations i.SimpleSchema = simpleSchema + i.VendorExtensible = vendorExtensible return nil } @@ -198,7 +204,11 @@ func (i Items) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - return swag.ConcatJSON(b3, b1, b2), nil + b4, err := json.Marshal(i.VendorExtensible) + if err != nil { + return nil, err + } + return swag.ConcatJSON(b4, b3, b1, b2), nil } // JSONLookup look up a value by the json property name diff --git a/vendor/github.com/go-openapi/spec/refmodifier.go b/vendor/github.com/go-openapi/spec/refmodifier.go new file mode 100644 index 0000000000..8482608ea7 --- /dev/null +++ b/vendor/github.com/go-openapi/spec/refmodifier.go @@ -0,0 +1,82 @@ +// Copyright 2017 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 spec + +import ( + "fmt" +) + +func modifyItemsRefs(target *Schema, basePath string) { + if target.Items != nil { + if target.Items.Schema != nil { + modifyRefs(target.Items.Schema, basePath) + } + for i := range target.Items.Schemas { + s := target.Items.Schemas[i] + modifyRefs(&s, basePath) + target.Items.Schemas[i] = s + } + } +} + +func modifyRefs(target *Schema, basePath string) { + if target.Ref.String() != "" { + if target.Ref.RemoteURI() == basePath { + return + } + newURL := fmt.Sprintf("%s%s", basePath, target.Ref.String()) + target.Ref, _ = NewRef(newURL) + } + + modifyItemsRefs(target, basePath) + for i := range target.AllOf { + modifyRefs(&target.AllOf[i], basePath) + } + for i := range target.AnyOf { + modifyRefs(&target.AnyOf[i], basePath) + } + for i := range target.OneOf { + modifyRefs(&target.OneOf[i], basePath) + } + if target.Not != nil { + modifyRefs(target.Not, basePath) + } + for k := range target.Properties { + s := target.Properties[k] + modifyRefs(&s, basePath) + target.Properties[k] = s + } + if target.AdditionalProperties != nil && target.AdditionalProperties.Schema != nil { + modifyRefs(target.AdditionalProperties.Schema, basePath) + } + for k := range target.PatternProperties { + s := target.PatternProperties[k] + modifyRefs(&s, basePath) + target.PatternProperties[k] = s + } + for k := range target.Dependencies { + if target.Dependencies[k].Schema != nil { + modifyRefs(target.Dependencies[k].Schema, basePath) + } + } + if target.AdditionalItems != nil && target.AdditionalItems.Schema != nil { + modifyRefs(target.AdditionalItems.Schema, basePath) + } + for k := range target.Definitions { + s := target.Definitions[k] + modifyRefs(&s, basePath) + target.Definitions[k] = s + } +} diff --git a/vendor/github.com/go-openapi/spec/swagger.go b/vendor/github.com/go-openapi/spec/swagger.go index 393a316778..23780c78a2 100644 --- a/vendor/github.com/go-openapi/spec/swagger.go +++ b/vendor/github.com/go-openapi/spec/swagger.go @@ -156,7 +156,7 @@ func (s SchemaOrStringArray) MarshalJSON() ([]byte, error) { if s.Schema != nil { return json.Marshal(s.Schema) } - return nil, nil + return []byte("null"), nil } // UnmarshalJSON converts this schema object or array from a JSON structure diff --git a/vendor/github.com/go-openapi/swag/util.go b/vendor/github.com/go-openapi/swag/util.go index 40751aab44..0efb41735d 100644 --- a/vendor/github.com/go-openapi/swag/util.go +++ b/vendor/github.com/go-openapi/swag/util.go @@ -40,6 +40,7 @@ var commonInitialisms = map[string]bool{ "IP": true, "JSON": true, "LHS": true, + "OAI": true, "QPS": true, "RAM": true, "RHS": true, @@ -163,8 +164,8 @@ func split(str string) (words []string) { // Split when uppercase is found (needed for Snake) str = rex1.ReplaceAllString(str, " $1") - // check if consecutive single char things make up an initialism + // check if consecutive single char things make up an initialism for _, k := range initialisms { str = strings.Replace(str, rex1.ReplaceAllString(k, " $1"), " "+k, -1) } @@ -189,10 +190,47 @@ func lower(str string) string { return strings.ToLower(trim(str)) } +// Camelize an uppercased word +func Camelize(word string) (camelized string) { + for pos, ru := range word { + if pos > 0 { + camelized += string(unicode.ToLower(ru)) + } else { + camelized += string(unicode.ToUpper(ru)) + } + } + return +} + // ToFileName lowercases and underscores a go type name func ToFileName(name string) string { var out []string - for _, w := range split(name) { + cml := trim(name) + + // Camelize any capital word preceding a reserved keyword ("initialism") + // thus, upper-cased words preceding a common initialism will get separated + // e.g: ELBHTTPLoadBalancer becomes elb_http_load_balancer + rexPrevious := regexp.MustCompile(`(?P\p{Lu}{2,})(?:HTTP|OAI)`) + cml = rexPrevious.ReplaceAllStringFunc(cml, func(match string) (replaceInMatch string) { + for _, m := range rexPrevious.FindAllStringSubmatch(match, -1) { // [ match submatch ] + if m[1] != "" { + replaceInMatch = strings.Replace(m[0], m[1], Camelize(m[1]), -1) + } + } + return + }) + + // Pre-camelize reserved keywords ("initialisms") to avoid unnecessary hyphenization + for _, k := range initialisms { + cml = strings.Replace(cml, k, Camelize(k), -1) + } + + // Camelize other capital words to avoid unnecessary hyphenization + rexCase := regexp.MustCompile(`(\p{Lu}{2,})`) + cml = rexCase.ReplaceAllStringFunc(cml, Camelize) + + // Final split with hyphens + for _, w := range split(cml) { out = append(out, lower(w)) } return strings.Join(out, "_") diff --git a/vendor/github.com/go-openapi/validate/object_validator.go b/vendor/github.com/go-openapi/validate/object_validator.go index 8169d231c5..0dd580288d 100644 --- a/vendor/github.com/go-openapi/validate/object_validator.go +++ b/vendor/github.com/go-openapi/validate/object_validator.go @@ -18,6 +18,7 @@ import ( "log" "reflect" "regexp" + "strings" "github.com/go-openapi/errors" "github.com/go-openapi/spec" @@ -52,6 +53,39 @@ func (o *objectValidator) Applies(source interface{}, kind reflect.Kind) bool { return r } +func (o *objectValidator) isPropertyName() bool { + p := strings.Split(o.Path, ".") + return p[len(p)-1] == "properties" && p[len(p)-2] != "properties" +} +func (o *objectValidator) checkArrayMustHaveItems(res *Result, val map[string]interface{}) { + if t, typeFound := val["type"]; typeFound { + if tpe, ok := t.(string); ok && tpe == "array" { + if _, itemsKeyFound := val["items"]; !itemsKeyFound { + res.AddErrors(errors.Required("items", o.Path)) + } + } + } +} + +func (o *objectValidator) checkItemsMustBeTypeArray(res *Result, val map[string]interface{}) { + if !o.isPropertyName() { + if _, itemsKeyFound := val["items"]; itemsKeyFound { + t, typeFound := val["type"] + if typeFound { + if tpe, ok := t.(string); !ok || tpe != "array" { + res.AddErrors(errors.InvalidType(o.Path, o.In, "array", nil)) + } + } else { + // there is no type + res.AddErrors(errors.Required("type", o.Path)) + } + } + } +} +func (o *objectValidator) precheck(res *Result, val map[string]interface{}) { + o.checkArrayMustHaveItems(res, val) + o.checkItemsMustBeTypeArray(res, val) +} func (o *objectValidator) Validate(data interface{}) *Result { val := data.(map[string]interface{}) numKeys := int64(len(val)) @@ -65,6 +99,8 @@ func (o *objectValidator) Validate(data interface{}) *Result { res := new(Result) + o.precheck(res, val) + if o.AdditionalProperties != nil && !o.AdditionalProperties.Allows { for k := range val { _, regularProperty := o.Properties[k] diff --git a/vendor/github.com/go-openapi/validate/schema.go b/vendor/github.com/go-openapi/validate/schema.go index 1073d8cda2..f859c6d630 100644 --- a/vendor/github.com/go-openapi/validate/schema.go +++ b/vendor/github.com/go-openapi/validate/schema.go @@ -82,12 +82,16 @@ func (s *SchemaValidator) Applies(source interface{}, kind reflect.Kind) bool { // Validate validates the data against the schema func (s *SchemaValidator) Validate(data interface{}) *Result { + result := new(Result) + if s == nil { + return result + } + if data == nil { v := s.validators[0].Validate(data) v.Merge(s.validators[6].Validate(data)) return v } - result := new(Result) tpe := reflect.TypeOf(data) kind := tpe.Kind() @@ -146,9 +150,9 @@ func (s *SchemaValidator) typeValidator() valueValidator { func (s *SchemaValidator) commonValidator() valueValidator { return &basicCommonValidator{ - Path: s.Path, - In: s.in, - Enum: s.Schema.Enum, + Path: s.Path, + In: s.in, + Enum: s.Schema.Enum, } } @@ -191,8 +195,8 @@ func (s *SchemaValidator) stringValidator() valueValidator { func (s *SchemaValidator) formatValidator() valueValidator { return &formatValidator{ - Path: s.Path, - In: s.in, + Path: s.Path, + In: s.in, Format: s.Schema.Format, KnownFormats: s.KnownFormats, } diff --git a/vendor/github.com/go-openapi/validate/validator.go b/vendor/github.com/go-openapi/validate/validator.go index 0a48956f8d..64a379fcde 100644 --- a/vendor/github.com/go-openapi/validate/validator.go +++ b/vendor/github.com/go-openapi/validate/validator.go @@ -560,7 +560,10 @@ func (s *stringValidator) Applies(source interface{}, kind reflect.Kind) bool { } func (s *stringValidator) Validate(val interface{}) *Result { - data := val.(string) + data, ok := val.(string) + if !ok { + return sErr(errors.InvalidType(s.Path, s.In, "string", val)) + } if s.Required && !s.AllowEmptyValue && (s.Default == nil || s.Default == "") { if err := RequiredString(s.Path, s.In, data); err != nil { diff --git a/vendor/github.com/go-openapi/validate/values.go b/vendor/github.com/go-openapi/validate/values.go index ab5ce8af50..67895d1ec6 100644 --- a/vendor/github.com/go-openapi/validate/values.go +++ b/vendor/github.com/go-openapi/validate/values.go @@ -196,7 +196,11 @@ func MinimumUint(path, in string, data, min uint64, exclusive bool) *errors.Vali // MultipleOf validates if the provided number is a multiple of the factor func MultipleOf(path, in string, data, factor float64) *errors.Validation { - if !swag.IsFloat64AJSONInteger(data / factor) { + mult := data / factor + if factor < 1 { + mult = 1 / factor * data + } + if !swag.IsFloat64AJSONInteger(mult) { return errors.NotMultipleOf(path, in, factor) } return nil diff --git a/vendor/github.com/gorilla/handlers/LICENSE b/vendor/github.com/gorilla/handlers/LICENSE deleted file mode 100644 index 66ea3c8ae7..0000000000 --- a/vendor/github.com/gorilla/handlers/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2013 The Gorilla Handlers Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/gorilla/handlers/canonical.go b/vendor/github.com/gorilla/handlers/canonical.go deleted file mode 100644 index 8437fefc1e..0000000000 --- a/vendor/github.com/gorilla/handlers/canonical.go +++ /dev/null @@ -1,74 +0,0 @@ -package handlers - -import ( - "net/http" - "net/url" - "strings" -) - -type canonical struct { - h http.Handler - domain string - code int -} - -// CanonicalHost is HTTP middleware that re-directs requests to the canonical -// domain. It accepts a domain and a status code (e.g. 301 or 302) and -// re-directs clients to this domain. The existing request path is maintained. -// -// Note: If the provided domain is considered invalid by url.Parse or otherwise -// returns an empty scheme or host, clients are not re-directed. -// -// Example: -// -// r := mux.NewRouter() -// canonical := handlers.CanonicalHost("http://www.gorillatoolkit.org", 302) -// r.HandleFunc("/route", YourHandler) -// -// log.Fatal(http.ListenAndServe(":7000", canonical(r))) -// -func CanonicalHost(domain string, code int) func(h http.Handler) http.Handler { - fn := func(h http.Handler) http.Handler { - return canonical{h, domain, code} - } - - return fn -} - -func (c canonical) ServeHTTP(w http.ResponseWriter, r *http.Request) { - dest, err := url.Parse(c.domain) - if err != nil { - // Call the next handler if the provided domain fails to parse. - c.h.ServeHTTP(w, r) - return - } - - if dest.Scheme == "" || dest.Host == "" { - // Call the next handler if the scheme or host are empty. - // Note that url.Parse won't fail on in this case. - c.h.ServeHTTP(w, r) - return - } - - if !strings.EqualFold(cleanHost(r.Host), dest.Host) { - // Re-build the destination URL - dest := dest.Scheme + "://" + dest.Host + r.URL.Path - if r.URL.RawQuery != "" { - dest += "?" + r.URL.RawQuery - } - http.Redirect(w, r, dest, c.code) - return - } - - c.h.ServeHTTP(w, r) -} - -// cleanHost cleans invalid Host headers by stripping anything after '/' or ' '. -// This is backported from Go 1.5 (in response to issue #11206) and attempts to -// mitigate malformed Host headers that do not match the format in RFC7230. -func cleanHost(in string) string { - if i := strings.IndexAny(in, " /"); i != -1 { - return in[:i] - } - return in -} diff --git a/vendor/github.com/gorilla/handlers/compress.go b/vendor/github.com/gorilla/handlers/compress.go deleted file mode 100644 index e8345d792a..0000000000 --- a/vendor/github.com/gorilla/handlers/compress.go +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2013 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package handlers - -import ( - "compress/flate" - "compress/gzip" - "io" - "net/http" - "strings" -) - -type compressResponseWriter struct { - io.Writer - http.ResponseWriter - http.Hijacker - http.Flusher - http.CloseNotifier -} - -func (w *compressResponseWriter) WriteHeader(c int) { - w.ResponseWriter.Header().Del("Content-Length") - w.ResponseWriter.WriteHeader(c) -} - -func (w *compressResponseWriter) Header() http.Header { - return w.ResponseWriter.Header() -} - -func (w *compressResponseWriter) Write(b []byte) (int, error) { - h := w.ResponseWriter.Header() - if h.Get("Content-Type") == "" { - h.Set("Content-Type", http.DetectContentType(b)) - } - h.Del("Content-Length") - - return w.Writer.Write(b) -} - -type flusher interface { - Flush() error -} - -func (w *compressResponseWriter) Flush() { - // Flush compressed data if compressor supports it. - if f, ok := w.Writer.(flusher); ok { - f.Flush() - } - // Flush HTTP response. - if w.Flusher != nil { - w.Flusher.Flush() - } -} - -// CompressHandler gzip compresses HTTP responses for clients that support it -// via the 'Accept-Encoding' header. -// -// Compressing TLS traffic may leak the page contents to an attacker if the -// page contains user input: http://security.stackexchange.com/a/102015/12208 -func CompressHandler(h http.Handler) http.Handler { - return CompressHandlerLevel(h, gzip.DefaultCompression) -} - -// CompressHandlerLevel gzip compresses HTTP responses with specified compression level -// for clients that support it via the 'Accept-Encoding' header. -// -// The compression level should be gzip.DefaultCompression, gzip.NoCompression, -// or any integer value between gzip.BestSpeed and gzip.BestCompression inclusive. -// gzip.DefaultCompression is used in case of invalid compression level. -func CompressHandlerLevel(h http.Handler, level int) http.Handler { - if level < gzip.DefaultCompression || level > gzip.BestCompression { - level = gzip.DefaultCompression - } - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - L: - for _, enc := range strings.Split(r.Header.Get("Accept-Encoding"), ",") { - switch strings.TrimSpace(enc) { - case "gzip": - w.Header().Set("Content-Encoding", "gzip") - w.Header().Add("Vary", "Accept-Encoding") - - gw, _ := gzip.NewWriterLevel(w, level) - defer gw.Close() - - h, hok := w.(http.Hijacker) - if !hok { /* w is not Hijacker... oh well... */ - h = nil - } - - f, fok := w.(http.Flusher) - if !fok { - f = nil - } - - cn, cnok := w.(http.CloseNotifier) - if !cnok { - cn = nil - } - - w = &compressResponseWriter{ - Writer: gw, - ResponseWriter: w, - Hijacker: h, - Flusher: f, - CloseNotifier: cn, - } - - break L - case "deflate": - w.Header().Set("Content-Encoding", "deflate") - w.Header().Add("Vary", "Accept-Encoding") - - fw, _ := flate.NewWriter(w, level) - defer fw.Close() - - h, hok := w.(http.Hijacker) - if !hok { /* w is not Hijacker... oh well... */ - h = nil - } - - f, fok := w.(http.Flusher) - if !fok { - f = nil - } - - cn, cnok := w.(http.CloseNotifier) - if !cnok { - cn = nil - } - - w = &compressResponseWriter{ - Writer: fw, - ResponseWriter: w, - Hijacker: h, - Flusher: f, - CloseNotifier: cn, - } - - break L - } - } - - h.ServeHTTP(w, r) - }) -} diff --git a/vendor/github.com/gorilla/handlers/cors.go b/vendor/github.com/gorilla/handlers/cors.go deleted file mode 100644 index 1cf7581ce9..0000000000 --- a/vendor/github.com/gorilla/handlers/cors.go +++ /dev/null @@ -1,327 +0,0 @@ -package handlers - -import ( - "net/http" - "strconv" - "strings" -) - -// CORSOption represents a functional option for configuring the CORS middleware. -type CORSOption func(*cors) error - -type cors struct { - h http.Handler - allowedHeaders []string - allowedMethods []string - allowedOrigins []string - allowedOriginValidator OriginValidator - exposedHeaders []string - maxAge int - ignoreOptions bool - allowCredentials bool -} - -// OriginValidator takes an origin string and returns whether or not that origin is allowed. -type OriginValidator func(string) bool - -var ( - defaultCorsMethods = []string{"GET", "HEAD", "POST"} - defaultCorsHeaders = []string{"Accept", "Accept-Language", "Content-Language", "Origin"} - // (WebKit/Safari v9 sends the Origin header by default in AJAX requests) -) - -const ( - corsOptionMethod string = "OPTIONS" - corsAllowOriginHeader string = "Access-Control-Allow-Origin" - corsExposeHeadersHeader string = "Access-Control-Expose-Headers" - corsMaxAgeHeader string = "Access-Control-Max-Age" - corsAllowMethodsHeader string = "Access-Control-Allow-Methods" - corsAllowHeadersHeader string = "Access-Control-Allow-Headers" - corsAllowCredentialsHeader string = "Access-Control-Allow-Credentials" - corsRequestMethodHeader string = "Access-Control-Request-Method" - corsRequestHeadersHeader string = "Access-Control-Request-Headers" - corsOriginHeader string = "Origin" - corsVaryHeader string = "Vary" - corsOriginMatchAll string = "*" -) - -func (ch *cors) ServeHTTP(w http.ResponseWriter, r *http.Request) { - origin := r.Header.Get(corsOriginHeader) - if !ch.isOriginAllowed(origin) { - ch.h.ServeHTTP(w, r) - return - } - - if r.Method == corsOptionMethod { - if ch.ignoreOptions { - ch.h.ServeHTTP(w, r) - return - } - - if _, ok := r.Header[corsRequestMethodHeader]; !ok { - w.WriteHeader(http.StatusBadRequest) - return - } - - method := r.Header.Get(corsRequestMethodHeader) - if !ch.isMatch(method, ch.allowedMethods) { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } - - requestHeaders := strings.Split(r.Header.Get(corsRequestHeadersHeader), ",") - allowedHeaders := []string{} - for _, v := range requestHeaders { - canonicalHeader := http.CanonicalHeaderKey(strings.TrimSpace(v)) - if canonicalHeader == "" || ch.isMatch(canonicalHeader, defaultCorsHeaders) { - continue - } - - if !ch.isMatch(canonicalHeader, ch.allowedHeaders) { - w.WriteHeader(http.StatusForbidden) - return - } - - allowedHeaders = append(allowedHeaders, canonicalHeader) - } - - if len(allowedHeaders) > 0 { - w.Header().Set(corsAllowHeadersHeader, strings.Join(allowedHeaders, ",")) - } - - if ch.maxAge > 0 { - w.Header().Set(corsMaxAgeHeader, strconv.Itoa(ch.maxAge)) - } - - if !ch.isMatch(method, defaultCorsMethods) { - w.Header().Set(corsAllowMethodsHeader, method) - } - } else { - if len(ch.exposedHeaders) > 0 { - w.Header().Set(corsExposeHeadersHeader, strings.Join(ch.exposedHeaders, ",")) - } - } - - if ch.allowCredentials { - w.Header().Set(corsAllowCredentialsHeader, "true") - } - - if len(ch.allowedOrigins) > 1 { - w.Header().Set(corsVaryHeader, corsOriginHeader) - } - - returnOrigin := origin - for _, o := range ch.allowedOrigins { - // A configuration of * is different than explicitly setting an allowed - // origin. Returning arbitrary origin headers an an access control allow - // origin header is unsafe and is not required by any use case. - if o == corsOriginMatchAll { - returnOrigin = "*" - break - } - } - w.Header().Set(corsAllowOriginHeader, returnOrigin) - - if r.Method == corsOptionMethod { - return - } - ch.h.ServeHTTP(w, r) -} - -// CORS provides Cross-Origin Resource Sharing middleware. -// Example: -// -// import ( -// "net/http" -// -// "github.com/gorilla/handlers" -// "github.com/gorilla/mux" -// ) -// -// func main() { -// r := mux.NewRouter() -// r.HandleFunc("/users", UserEndpoint) -// r.HandleFunc("/projects", ProjectEndpoint) -// -// // Apply the CORS middleware to our top-level router, with the defaults. -// http.ListenAndServe(":8000", handlers.CORS()(r)) -// } -// -func CORS(opts ...CORSOption) func(http.Handler) http.Handler { - return func(h http.Handler) http.Handler { - ch := parseCORSOptions(opts...) - ch.h = h - return ch - } -} - -func parseCORSOptions(opts ...CORSOption) *cors { - ch := &cors{ - allowedMethods: defaultCorsMethods, - allowedHeaders: defaultCorsHeaders, - allowedOrigins: []string{corsOriginMatchAll}, - } - - for _, option := range opts { - option(ch) - } - - return ch -} - -// -// Functional options for configuring CORS. -// - -// AllowedHeaders adds the provided headers to the list of allowed headers in a -// CORS request. -// This is an append operation so the headers Accept, Accept-Language, -// and Content-Language are always allowed. -// Content-Type must be explicitly declared if accepting Content-Types other than -// application/x-www-form-urlencoded, multipart/form-data, or text/plain. -func AllowedHeaders(headers []string) CORSOption { - return func(ch *cors) error { - for _, v := range headers { - normalizedHeader := http.CanonicalHeaderKey(strings.TrimSpace(v)) - if normalizedHeader == "" { - continue - } - - if !ch.isMatch(normalizedHeader, ch.allowedHeaders) { - ch.allowedHeaders = append(ch.allowedHeaders, normalizedHeader) - } - } - - return nil - } -} - -// AllowedMethods can be used to explicitly allow methods in the -// Access-Control-Allow-Methods header. -// This is a replacement operation so you must also -// pass GET, HEAD, and POST if you wish to support those methods. -func AllowedMethods(methods []string) CORSOption { - return func(ch *cors) error { - ch.allowedMethods = []string{} - for _, v := range methods { - normalizedMethod := strings.ToUpper(strings.TrimSpace(v)) - if normalizedMethod == "" { - continue - } - - if !ch.isMatch(normalizedMethod, ch.allowedMethods) { - ch.allowedMethods = append(ch.allowedMethods, normalizedMethod) - } - } - - return nil - } -} - -// AllowedOrigins sets the allowed origins for CORS requests, as used in the -// 'Allow-Access-Control-Origin' HTTP header. -// Note: Passing in a []string{"*"} will allow any domain. -func AllowedOrigins(origins []string) CORSOption { - return func(ch *cors) error { - for _, v := range origins { - if v == corsOriginMatchAll { - ch.allowedOrigins = []string{corsOriginMatchAll} - return nil - } - } - - ch.allowedOrigins = origins - return nil - } -} - -// AllowedOriginValidator sets a function for evaluating allowed origins in CORS requests, represented by the -// 'Allow-Access-Control-Origin' HTTP header. -func AllowedOriginValidator(fn OriginValidator) CORSOption { - return func(ch *cors) error { - ch.allowedOriginValidator = fn - return nil - } -} - -// ExposeHeaders can be used to specify headers that are available -// and will not be stripped out by the user-agent. -func ExposedHeaders(headers []string) CORSOption { - return func(ch *cors) error { - ch.exposedHeaders = []string{} - for _, v := range headers { - normalizedHeader := http.CanonicalHeaderKey(strings.TrimSpace(v)) - if normalizedHeader == "" { - continue - } - - if !ch.isMatch(normalizedHeader, ch.exposedHeaders) { - ch.exposedHeaders = append(ch.exposedHeaders, normalizedHeader) - } - } - - return nil - } -} - -// MaxAge determines the maximum age (in seconds) between preflight requests. A -// maximum of 10 minutes is allowed. An age above this value will default to 10 -// minutes. -func MaxAge(age int) CORSOption { - return func(ch *cors) error { - // Maximum of 10 minutes. - if age > 600 { - age = 600 - } - - ch.maxAge = age - return nil - } -} - -// IgnoreOptions causes the CORS middleware to ignore OPTIONS requests, instead -// passing them through to the next handler. This is useful when your application -// or framework has a pre-existing mechanism for responding to OPTIONS requests. -func IgnoreOptions() CORSOption { - return func(ch *cors) error { - ch.ignoreOptions = true - return nil - } -} - -// AllowCredentials can be used to specify that the user agent may pass -// authentication details along with the request. -func AllowCredentials() CORSOption { - return func(ch *cors) error { - ch.allowCredentials = true - return nil - } -} - -func (ch *cors) isOriginAllowed(origin string) bool { - if origin == "" { - return false - } - - if ch.allowedOriginValidator != nil { - return ch.allowedOriginValidator(origin) - } - - for _, allowedOrigin := range ch.allowedOrigins { - if allowedOrigin == origin || allowedOrigin == corsOriginMatchAll { - return true - } - } - - return false -} - -func (ch *cors) isMatch(needle string, haystack []string) bool { - for _, v := range haystack { - if v == needle { - return true - } - } - - return false -} diff --git a/vendor/github.com/gorilla/handlers/doc.go b/vendor/github.com/gorilla/handlers/doc.go deleted file mode 100644 index 944e5a8ae9..0000000000 --- a/vendor/github.com/gorilla/handlers/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -/* -Package handlers is a collection of handlers (aka "HTTP middleware") for use -with Go's net/http package (or any framework supporting http.Handler). - -The package includes handlers for logging in standardised formats, compressing -HTTP responses, validating content types and other useful tools for manipulating -requests and responses. -*/ -package handlers diff --git a/vendor/github.com/gorilla/handlers/handlers.go b/vendor/github.com/gorilla/handlers/handlers.go deleted file mode 100644 index 75db7f87b0..0000000000 --- a/vendor/github.com/gorilla/handlers/handlers.go +++ /dev/null @@ -1,399 +0,0 @@ -// Copyright 2013 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package handlers - -import ( - "bufio" - "fmt" - "io" - "net" - "net/http" - "net/url" - "sort" - "strconv" - "strings" - "time" - "unicode/utf8" -) - -// MethodHandler is an http.Handler that dispatches to a handler whose key in the -// MethodHandler's map matches the name of the HTTP request's method, eg: GET -// -// If the request's method is OPTIONS and OPTIONS is not a key in the map then -// the handler responds with a status of 200 and sets the Allow header to a -// comma-separated list of available methods. -// -// If the request's method doesn't match any of its keys the handler responds -// with a status of HTTP 405 "Method Not Allowed" and sets the Allow header to a -// comma-separated list of available methods. -type MethodHandler map[string]http.Handler - -func (h MethodHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - if handler, ok := h[req.Method]; ok { - handler.ServeHTTP(w, req) - } else { - allow := []string{} - for k := range h { - allow = append(allow, k) - } - sort.Strings(allow) - w.Header().Set("Allow", strings.Join(allow, ", ")) - if req.Method == "OPTIONS" { - w.WriteHeader(http.StatusOK) - } else { - http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) - } - } -} - -// loggingHandler is the http.Handler implementation for LoggingHandlerTo and its -// friends -type loggingHandler struct { - writer io.Writer - handler http.Handler -} - -// combinedLoggingHandler is the http.Handler implementation for LoggingHandlerTo -// and its friends -type combinedLoggingHandler struct { - writer io.Writer - handler http.Handler -} - -func (h loggingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - t := time.Now() - logger := makeLogger(w) - url := *req.URL - h.handler.ServeHTTP(logger, req) - writeLog(h.writer, req, url, t, logger.Status(), logger.Size()) -} - -func (h combinedLoggingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - t := time.Now() - logger := makeLogger(w) - url := *req.URL - h.handler.ServeHTTP(logger, req) - writeCombinedLog(h.writer, req, url, t, logger.Status(), logger.Size()) -} - -func makeLogger(w http.ResponseWriter) loggingResponseWriter { - var logger loggingResponseWriter = &responseLogger{w: w, status: http.StatusOK} - if _, ok := w.(http.Hijacker); ok { - logger = &hijackLogger{responseLogger{w: w, status: http.StatusOK}} - } - h, ok1 := logger.(http.Hijacker) - c, ok2 := w.(http.CloseNotifier) - if ok1 && ok2 { - return hijackCloseNotifier{logger, h, c} - } - if ok2 { - return &closeNotifyWriter{logger, c} - } - return logger -} - -type commonLoggingResponseWriter interface { - http.ResponseWriter - http.Flusher - Status() int - Size() int -} - -// responseLogger is wrapper of http.ResponseWriter that keeps track of its HTTP -// status code and body size -type responseLogger struct { - w http.ResponseWriter - status int - size int -} - -func (l *responseLogger) Header() http.Header { - return l.w.Header() -} - -func (l *responseLogger) Write(b []byte) (int, error) { - size, err := l.w.Write(b) - l.size += size - return size, err -} - -func (l *responseLogger) WriteHeader(s int) { - l.w.WriteHeader(s) - l.status = s -} - -func (l *responseLogger) Status() int { - return l.status -} - -func (l *responseLogger) Size() int { - return l.size -} - -func (l *responseLogger) Flush() { - f, ok := l.w.(http.Flusher) - if ok { - f.Flush() - } -} - -type hijackLogger struct { - responseLogger -} - -func (l *hijackLogger) Hijack() (net.Conn, *bufio.ReadWriter, error) { - h := l.responseLogger.w.(http.Hijacker) - conn, rw, err := h.Hijack() - if err == nil && l.responseLogger.status == 0 { - // The status will be StatusSwitchingProtocols if there was no error and - // WriteHeader has not been called yet - l.responseLogger.status = http.StatusSwitchingProtocols - } - return conn, rw, err -} - -type closeNotifyWriter struct { - loggingResponseWriter - http.CloseNotifier -} - -type hijackCloseNotifier struct { - loggingResponseWriter - http.Hijacker - http.CloseNotifier -} - -const lowerhex = "0123456789abcdef" - -func appendQuoted(buf []byte, s string) []byte { - var runeTmp [utf8.UTFMax]byte - for width := 0; len(s) > 0; s = s[width:] { - r := rune(s[0]) - width = 1 - if r >= utf8.RuneSelf { - r, width = utf8.DecodeRuneInString(s) - } - if width == 1 && r == utf8.RuneError { - buf = append(buf, `\x`...) - buf = append(buf, lowerhex[s[0]>>4]) - buf = append(buf, lowerhex[s[0]&0xF]) - continue - } - if r == rune('"') || r == '\\' { // always backslashed - buf = append(buf, '\\') - buf = append(buf, byte(r)) - continue - } - if strconv.IsPrint(r) { - n := utf8.EncodeRune(runeTmp[:], r) - buf = append(buf, runeTmp[:n]...) - continue - } - switch r { - case '\a': - buf = append(buf, `\a`...) - case '\b': - buf = append(buf, `\b`...) - case '\f': - buf = append(buf, `\f`...) - case '\n': - buf = append(buf, `\n`...) - case '\r': - buf = append(buf, `\r`...) - case '\t': - buf = append(buf, `\t`...) - case '\v': - buf = append(buf, `\v`...) - default: - switch { - case r < ' ': - buf = append(buf, `\x`...) - buf = append(buf, lowerhex[s[0]>>4]) - buf = append(buf, lowerhex[s[0]&0xF]) - case r > utf8.MaxRune: - r = 0xFFFD - fallthrough - case r < 0x10000: - buf = append(buf, `\u`...) - for s := 12; s >= 0; s -= 4 { - buf = append(buf, lowerhex[r>>uint(s)&0xF]) - } - default: - buf = append(buf, `\U`...) - for s := 28; s >= 0; s -= 4 { - buf = append(buf, lowerhex[r>>uint(s)&0xF]) - } - } - } - } - return buf - -} - -// buildCommonLogLine builds a log entry for req in Apache Common Log Format. -// ts is the timestamp with which the entry should be logged. -// status and size are used to provide the response HTTP status and size. -func buildCommonLogLine(req *http.Request, url url.URL, ts time.Time, status int, size int) []byte { - username := "-" - if url.User != nil { - if name := url.User.Username(); name != "" { - username = name - } - } - - host, _, err := net.SplitHostPort(req.RemoteAddr) - - if err != nil { - host = req.RemoteAddr - } - - uri := req.RequestURI - - // Requests using the CONNECT method over HTTP/2.0 must use - // the authority field (aka r.Host) to identify the target. - // Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT - if req.ProtoMajor == 2 && req.Method == "CONNECT" { - uri = req.Host - } - if uri == "" { - uri = url.RequestURI() - } - - buf := make([]byte, 0, 3*(len(host)+len(username)+len(req.Method)+len(uri)+len(req.Proto)+50)/2) - buf = append(buf, host...) - buf = append(buf, " - "...) - buf = append(buf, username...) - buf = append(buf, " ["...) - buf = append(buf, ts.Format("02/Jan/2006:15:04:05 -0700")...) - buf = append(buf, `] "`...) - buf = append(buf, req.Method...) - buf = append(buf, " "...) - buf = appendQuoted(buf, uri) - buf = append(buf, " "...) - buf = append(buf, req.Proto...) - buf = append(buf, `" `...) - buf = append(buf, strconv.Itoa(status)...) - buf = append(buf, " "...) - buf = append(buf, strconv.Itoa(size)...) - return buf -} - -// writeLog writes a log entry for req to w in Apache Common Log Format. -// ts is the timestamp with which the entry should be logged. -// status and size are used to provide the response HTTP status and size. -func writeLog(w io.Writer, req *http.Request, url url.URL, ts time.Time, status, size int) { - buf := buildCommonLogLine(req, url, ts, status, size) - buf = append(buf, '\n') - w.Write(buf) -} - -// writeCombinedLog writes a log entry for req to w in Apache Combined Log Format. -// ts is the timestamp with which the entry should be logged. -// status and size are used to provide the response HTTP status and size. -func writeCombinedLog(w io.Writer, req *http.Request, url url.URL, ts time.Time, status, size int) { - buf := buildCommonLogLine(req, url, ts, status, size) - buf = append(buf, ` "`...) - buf = appendQuoted(buf, req.Referer()) - buf = append(buf, `" "`...) - buf = appendQuoted(buf, req.UserAgent()) - buf = append(buf, '"', '\n') - w.Write(buf) -} - -// CombinedLoggingHandler return a http.Handler that wraps h and logs requests to out in -// Apache Combined Log Format. -// -// See http://httpd.apache.org/docs/2.2/logs.html#combined for a description of this format. -// -// LoggingHandler always sets the ident field of the log to - -func CombinedLoggingHandler(out io.Writer, h http.Handler) http.Handler { - return combinedLoggingHandler{out, h} -} - -// LoggingHandler return a http.Handler that wraps h and logs requests to out in -// Apache Common Log Format (CLF). -// -// See http://httpd.apache.org/docs/2.2/logs.html#common for a description of this format. -// -// LoggingHandler always sets the ident field of the log to - -// -// Example: -// -// r := mux.NewRouter() -// r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { -// w.Write([]byte("This is a catch-all route")) -// }) -// loggedRouter := handlers.LoggingHandler(os.Stdout, r) -// http.ListenAndServe(":1123", loggedRouter) -// -func LoggingHandler(out io.Writer, h http.Handler) http.Handler { - return loggingHandler{out, h} -} - -// isContentType validates the Content-Type header matches the supplied -// contentType. That is, its type and subtype match. -func isContentType(h http.Header, contentType string) bool { - ct := h.Get("Content-Type") - if i := strings.IndexRune(ct, ';'); i != -1 { - ct = ct[0:i] - } - return ct == contentType -} - -// ContentTypeHandler wraps and returns a http.Handler, validating the request -// content type is compatible with the contentTypes list. It writes a HTTP 415 -// error if that fails. -// -// Only PUT, POST, and PATCH requests are considered. -func ContentTypeHandler(h http.Handler, contentTypes ...string) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !(r.Method == "PUT" || r.Method == "POST" || r.Method == "PATCH") { - h.ServeHTTP(w, r) - return - } - - for _, ct := range contentTypes { - if isContentType(r.Header, ct) { - h.ServeHTTP(w, r) - return - } - } - http.Error(w, fmt.Sprintf("Unsupported content type %q; expected one of %q", r.Header.Get("Content-Type"), contentTypes), http.StatusUnsupportedMediaType) - }) -} - -const ( - // HTTPMethodOverrideHeader is a commonly used - // http header to override a request method. - HTTPMethodOverrideHeader = "X-HTTP-Method-Override" - // HTTPMethodOverrideFormKey is a commonly used - // HTML form key to override a request method. - HTTPMethodOverrideFormKey = "_method" -) - -// HTTPMethodOverrideHandler wraps and returns a http.Handler which checks for -// the X-HTTP-Method-Override header or the _method form key, and overrides (if -// valid) request.Method with its value. -// -// This is especially useful for HTTP clients that don't support many http verbs. -// It isn't secure to override e.g a GET to a POST, so only POST requests are -// considered. Likewise, the override method can only be a "write" method: PUT, -// PATCH or DELETE. -// -// Form method takes precedence over header method. -func HTTPMethodOverrideHandler(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method == "POST" { - om := r.FormValue(HTTPMethodOverrideFormKey) - if om == "" { - om = r.Header.Get(HTTPMethodOverrideHeader) - } - if om == "PUT" || om == "PATCH" || om == "DELETE" { - r.Method = om - } - } - h.ServeHTTP(w, r) - }) -} diff --git a/vendor/github.com/gorilla/handlers/handlers_go18.go b/vendor/github.com/gorilla/handlers/handlers_go18.go deleted file mode 100644 index 35eb8d4f54..0000000000 --- a/vendor/github.com/gorilla/handlers/handlers_go18.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build go1.8 - -package handlers - -import ( - "fmt" - "net/http" -) - -type loggingResponseWriter interface { - commonLoggingResponseWriter - http.Pusher -} - -func (l *responseLogger) Push(target string, opts *http.PushOptions) error { - p, ok := l.w.(http.Pusher) - if !ok { - return fmt.Errorf("responseLogger does not implement http.Pusher") - } - return p.Push(target, opts) -} diff --git a/vendor/github.com/gorilla/handlers/handlers_pre18.go b/vendor/github.com/gorilla/handlers/handlers_pre18.go deleted file mode 100644 index 197836abba..0000000000 --- a/vendor/github.com/gorilla/handlers/handlers_pre18.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build !go1.8 - -package handlers - -type loggingResponseWriter interface { - commonLoggingResponseWriter -} diff --git a/vendor/github.com/gorilla/handlers/proxy_headers.go b/vendor/github.com/gorilla/handlers/proxy_headers.go deleted file mode 100644 index 0be750fd7b..0000000000 --- a/vendor/github.com/gorilla/handlers/proxy_headers.go +++ /dev/null @@ -1,120 +0,0 @@ -package handlers - -import ( - "net/http" - "regexp" - "strings" -) - -var ( - // De-facto standard header keys. - xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For") - xForwardedHost = http.CanonicalHeaderKey("X-Forwarded-Host") - xForwardedProto = http.CanonicalHeaderKey("X-Forwarded-Proto") - xForwardedScheme = http.CanonicalHeaderKey("X-Forwarded-Scheme") - xRealIP = http.CanonicalHeaderKey("X-Real-IP") -) - -var ( - // RFC7239 defines a new "Forwarded: " header designed to replace the - // existing use of X-Forwarded-* headers. - // e.g. Forwarded: for=192.0.2.60;proto=https;by=203.0.113.43 - forwarded = http.CanonicalHeaderKey("Forwarded") - // Allows for a sub-match of the first value after 'for=' to the next - // comma, semi-colon or space. The match is case-insensitive. - forRegex = regexp.MustCompile(`(?i)(?:for=)([^(;|,| )]+)`) - // Allows for a sub-match for the first instance of scheme (http|https) - // prefixed by 'proto='. The match is case-insensitive. - protoRegex = regexp.MustCompile(`(?i)(?:proto=)(https|http)`) -) - -// ProxyHeaders inspects common reverse proxy headers and sets the corresponding -// fields in the HTTP request struct. These are X-Forwarded-For and X-Real-IP -// for the remote (client) IP address, X-Forwarded-Proto or X-Forwarded-Scheme -// for the scheme (http|https) and the RFC7239 Forwarded header, which may -// include both client IPs and schemes. -// -// NOTE: This middleware should only be used when behind a reverse -// proxy like nginx, HAProxy or Apache. Reverse proxies that don't (or are -// configured not to) strip these headers from client requests, or where these -// headers are accepted "as is" from a remote client (e.g. when Go is not behind -// a proxy), can manifest as a vulnerability if your application uses these -// headers for validating the 'trustworthiness' of a request. -func ProxyHeaders(h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - // Set the remote IP with the value passed from the proxy. - if fwd := getIP(r); fwd != "" { - r.RemoteAddr = fwd - } - - // Set the scheme (proto) with the value passed from the proxy. - if scheme := getScheme(r); scheme != "" { - r.URL.Scheme = scheme - } - // Set the host with the value passed by the proxy - if r.Header.Get(xForwardedHost) != "" { - r.Host = r.Header.Get(xForwardedHost) - } - // Call the next handler in the chain. - h.ServeHTTP(w, r) - } - - return http.HandlerFunc(fn) -} - -// getIP retrieves the IP from the X-Forwarded-For, X-Real-IP and RFC7239 -// Forwarded headers (in that order). -func getIP(r *http.Request) string { - var addr string - - if fwd := r.Header.Get(xForwardedFor); fwd != "" { - // Only grab the first (client) address. Note that '192.168.0.1, - // 10.1.1.1' is a valid key for X-Forwarded-For where addresses after - // the first may represent forwarding proxies earlier in the chain. - s := strings.Index(fwd, ", ") - if s == -1 { - s = len(fwd) - } - addr = fwd[:s] - } else if fwd := r.Header.Get(xRealIP); fwd != "" { - // X-Real-IP should only contain one IP address (the client making the - // request). - addr = fwd - } else if fwd := r.Header.Get(forwarded); fwd != "" { - // match should contain at least two elements if the protocol was - // specified in the Forwarded header. The first element will always be - // the 'for=' capture, which we ignore. In the case of multiple IP - // addresses (for=8.8.8.8, 8.8.4.4,172.16.1.20 is valid) we only - // extract the first, which should be the client IP. - if match := forRegex.FindStringSubmatch(fwd); len(match) > 1 { - // IPv6 addresses in Forwarded headers are quoted-strings. We strip - // these quotes. - addr = strings.Trim(match[1], `"`) - } - } - - return addr -} - -// getScheme retrieves the scheme from the X-Forwarded-Proto and RFC7239 -// Forwarded headers (in that order). -func getScheme(r *http.Request) string { - var scheme string - - // Retrieve the scheme from X-Forwarded-Proto. - if proto := r.Header.Get(xForwardedProto); proto != "" { - scheme = strings.ToLower(proto) - } else if proto = r.Header.Get(xForwardedScheme); proto != "" { - scheme = strings.ToLower(proto) - } else if proto = r.Header.Get(forwarded); proto != "" { - // match should contain at least two elements if the protocol was - // specified in the Forwarded header. The first element will always be - // the 'proto=' capture, which we ignore. In the case of multiple proto - // parameters (invalid) we only extract the first. - if match := protoRegex.FindStringSubmatch(proto); len(match) > 1 { - scheme = strings.ToLower(match[1]) - } - } - - return scheme -} diff --git a/vendor/github.com/gorilla/handlers/recovery.go b/vendor/github.com/gorilla/handlers/recovery.go deleted file mode 100644 index b1be9dc83e..0000000000 --- a/vendor/github.com/gorilla/handlers/recovery.go +++ /dev/null @@ -1,91 +0,0 @@ -package handlers - -import ( - "log" - "net/http" - "runtime/debug" -) - -// RecoveryHandlerLogger is an interface used by the recovering handler to print logs. -type RecoveryHandlerLogger interface { - Println(...interface{}) -} - -type recoveryHandler struct { - handler http.Handler - logger RecoveryHandlerLogger - printStack bool -} - -// RecoveryOption provides a functional approach to define -// configuration for a handler; such as setting the logging -// whether or not to print strack traces on panic. -type RecoveryOption func(http.Handler) - -func parseRecoveryOptions(h http.Handler, opts ...RecoveryOption) http.Handler { - for _, option := range opts { - option(h) - } - - return h -} - -// RecoveryHandler is HTTP middleware that recovers from a panic, -// logs the panic, writes http.StatusInternalServerError, and -// continues to the next handler. -// -// Example: -// -// r := mux.NewRouter() -// r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { -// panic("Unexpected error!") -// }) -// -// http.ListenAndServe(":1123", handlers.RecoveryHandler()(r)) -func RecoveryHandler(opts ...RecoveryOption) func(h http.Handler) http.Handler { - return func(h http.Handler) http.Handler { - r := &recoveryHandler{handler: h} - return parseRecoveryOptions(r, opts...) - } -} - -// RecoveryLogger is a functional option to override -// the default logger -func RecoveryLogger(logger RecoveryHandlerLogger) RecoveryOption { - return func(h http.Handler) { - r := h.(*recoveryHandler) - r.logger = logger - } -} - -// PrintRecoveryStack is a functional option to enable -// or disable printing stack traces on panic. -func PrintRecoveryStack(print bool) RecoveryOption { - return func(h http.Handler) { - r := h.(*recoveryHandler) - r.printStack = print - } -} - -func (h recoveryHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - defer func() { - if err := recover(); err != nil { - w.WriteHeader(http.StatusInternalServerError) - h.log(err) - } - }() - - h.handler.ServeHTTP(w, req) -} - -func (h recoveryHandler) log(v ...interface{}) { - if h.logger != nil { - h.logger.Println(v...) - } else { - log.Println(v...) - } - - if h.printStack { - debug.PrintStack() - } -} diff --git a/vendor/github.com/mailru/easyjson/jlexer/lexer.go b/vendor/github.com/mailru/easyjson/jlexer/lexer.go index e81f1031b0..e5558ae39c 100644 --- a/vendor/github.com/mailru/easyjson/jlexer/lexer.go +++ b/vendor/github.com/mailru/easyjson/jlexer/lexer.go @@ -6,6 +6,7 @@ package jlexer import ( "encoding/base64" + "encoding/json" "errors" "fmt" "io" @@ -903,6 +904,10 @@ func (r *Lexer) UintStr() uint { return uint(r.Uint64Str()) } +func (r *Lexer) UintptrStr() uintptr { + return uintptr(r.Uint64Str()) +} + func (r *Lexer) Int8Str() int8 { s, b := r.unsafeString() if !r.Ok() { @@ -1043,6 +1048,28 @@ func (r *Lexer) GetNonFatalErrors() []*LexerError { return r.multipleErrors } +// JsonNumber fetches and json.Number from 'encoding/json' package. +// Both int, float or string, contains them are valid values +func (r *Lexer) JsonNumber() json.Number { + if r.token.kind == tokenUndef && r.Ok() { + r.FetchToken() + } + if !r.Ok() { + r.errInvalidToken("json.Number") + return json.Number("0") + } + + switch r.token.kind { + case tokenString: + return json.Number(r.String()) + case tokenNumber: + return json.Number(r.Raw()) + default: + r.errSyntax() + return json.Number("0") + } +} + // Interface fetches an interface{} analogous to the 'encoding/json' package. func (r *Lexer) Interface() interface{} { if r.token.kind == tokenUndef && r.Ok() { diff --git a/vendor/github.com/mailru/easyjson/jwriter/writer.go b/vendor/github.com/mailru/easyjson/jwriter/writer.go index 7b55293a0f..250920d85b 100644 --- a/vendor/github.com/mailru/easyjson/jwriter/writer.go +++ b/vendor/github.com/mailru/easyjson/jwriter/writer.go @@ -196,6 +196,13 @@ func (w *Writer) Uint64Str(n uint64) { w.Buffer.Buf = append(w.Buffer.Buf, '"') } +func (w *Writer) UintptrStr(n uintptr) { + w.Buffer.EnsureSpace(20) + w.Buffer.Buf = append(w.Buffer.Buf, '"') + w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) + w.Buffer.Buf = append(w.Buffer.Buf, '"') +} + func (w *Writer) Int8Str(n int8) { w.Buffer.EnsureSpace(4) w.Buffer.Buf = append(w.Buffer.Buf, '"') diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go index 6ec5c33357..30a9957c65 100644 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure.go +++ b/vendor/github.com/mitchellh/mapstructure/mapstructure.go @@ -686,7 +686,11 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) // Compile the list of all the fields that we're going to be decoding // from all the structs. - fields := make(map[*reflect.StructField]reflect.Value) + type field struct { + field reflect.StructField + val reflect.Value + } + fields := []field{} for len(structs) > 0 { structVal := structs[0] structs = structs[1:] @@ -718,14 +722,16 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) } // Normal struct field, store it away - fields[&fieldType] = structVal.Field(i) + fields = append(fields, field{fieldType, structVal.Field(i)}) } } - for fieldType, field := range fields { - fieldName := fieldType.Name + // for fieldType, field := range fields { + for _, f := range fields { + field, fieldValue := f.field, f.val + fieldName := field.Name - tagValue := fieldType.Tag.Get(d.config.TagName) + tagValue := field.Tag.Get(d.config.TagName) tagValue = strings.SplitN(tagValue, ",", 2)[0] if tagValue != "" { fieldName = tagValue @@ -760,14 +766,14 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) // Delete the key we're using from the unused map so we stop tracking delete(dataValKeysUnused, rawMapKey.Interface()) - if !field.IsValid() { + if !fieldValue.IsValid() { // This should never happen panic("field is not valid") } // If we can't set the field, then it is unexported or something, // and we just continue onwards. - if !field.CanSet() { + if !fieldValue.CanSet() { continue } @@ -777,7 +783,7 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) fieldName = fmt.Sprintf("%s.%s", name, fieldName) } - if err := d.decode(fieldName, rawMapVal.Interface(), field); err != nil { + if err := d.decode(fieldName, rawMapVal.Interface(), fieldValue); err != nil { errors = appendErrors(errors, err) } }