diff --git a/Gopkg.lock b/Gopkg.lock index 57613a46f..b2a395689 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -13,24 +13,6 @@ packages = ["."] revision = "cd527374f1e5bff4938207604a14f2e38a9cf512" -[[projects]] - name = "github.com/PuerkitoBio/purell" - packages = ["."] - revision = "0bcb03f4b4d0a9428594752bd2a3b9aa0a9d4bd4" - version = "v1.1.0" - -[[projects]] - branch = "master" - name = "github.com/PuerkitoBio/urlesc" - packages = ["."] - revision = "de5bf2ad457846296e2031421a34e2568e304e35" - -[[projects]] - name = "github.com/asaskevich/govalidator" - packages = ["."] - revision = "ccb8e960c48f04d6935e72476ae4a51028f9e22f" - version = "v9" - [[projects]] name = "github.com/aws/aws-sdk-go" packages = [ @@ -81,7 +63,7 @@ branch = "master" name = "github.com/containerd/continuity" packages = ["pathdriver"] - revision = "d3c23511c1bf5851696cba83143d9cbcd666869b" + revision = "246e49050efdf45e8f17fbbcf1547ee376f9939e" [[projects]] name = "github.com/coreos/go-semver" @@ -96,7 +78,6 @@ version = "v1.1.0" [[projects]] - branch = "master" name = "github.com/docker/docker" packages = [ "api/types", @@ -136,8 +117,8 @@ [[projects]] name = "github.com/docker/go-units" packages = ["."] - revision = "0dadbb0345b35ec7ef35e228dabb8de89a65bf52" - version = "v0.3.2" + revision = "47565b4f722fb6ceae66b95f853feed578a4a51c" + version = "v0.3.3" [[projects]] branch = "master" @@ -146,20 +127,7 @@ ".", "utils" ] - revision = "0ae900cf56643afe316fcc87323c5845da0531c1" - -[[projects]] - name = "github.com/fnproject/fn_go" - packages = [ - "client", - "client/apps", - "client/call", - "client/operations", - "client/routes", - "models" - ] - revision = "e2f92e36625a4b93c596ac3b912a4994ae574f64" - version = "0.2.6" + revision = "1eb29530716f262bad5b83eb9a5b3f7483636949" [[projects]] name = "github.com/fsouza/go-dockerclient" @@ -200,77 +168,8 @@ [[projects]] name = "github.com/go-ini/ini" packages = ["."] - revision = "6333e38ac20b8949a8dd68baa3650f4dee8f39f0" - version = "v1.33.0" - -[[projects]] - branch = "master" - name = "github.com/go-openapi/analysis" - packages = ["."] - revision = "f59a71f0ece6f9dfb438be7f45148f006cbad88e" - -[[projects]] - branch = "master" - name = "github.com/go-openapi/errors" - packages = ["."] - revision = "7bcb96a367bac6b76e6e42fa84155bb5581dcff8" - -[[projects]] - branch = "master" - name = "github.com/go-openapi/jsonpointer" - packages = ["."] - revision = "3a0015ad55fa9873f41605d3e8f28cd279c32ab2" - -[[projects]] - branch = "master" - name = "github.com/go-openapi/jsonreference" - packages = ["."] - revision = "3fb327e6747da3043567ee86abd02bb6376b6be2" - -[[projects]] - branch = "master" - name = "github.com/go-openapi/loads" - packages = ["."] - revision = "2a2b323bab96e6b1fdee110e57d959322446e9c9" - -[[projects]] - branch = "master" - name = "github.com/go-openapi/runtime" - packages = [ - ".", - "client", - "logger", - "middleware", - "middleware/denco", - "middleware/header", - "middleware/untyped", - "security" - ] - revision = "62281b694b396a17fe3e4313ee8b0ca2c3cca719" - -[[projects]] - branch = "master" - name = "github.com/go-openapi/spec" - packages = ["."] - revision = "a3092263d8b39f66ff6fe87b0109668eca1e24ff" - -[[projects]] - branch = "master" - name = "github.com/go-openapi/strfmt" - packages = ["."] - revision = "6ba31556a6c60db8615afb9d8eddae7aae15eb48" - -[[projects]] - branch = "master" - name = "github.com/go-openapi/swag" - packages = ["."] - revision = "ceb469cb0fdf2d792f28d771bc05da6c606f55e5" - -[[projects]] - branch = "master" - name = "github.com/go-openapi/validate" - packages = ["."] - revision = "180bba53b98899f743a112e568bed9e2ef31aa20" + revision = "06f5f3d67269ccec1fe5fe4134ba6e982984f7f5" + version = "v1.37.0" [[projects]] name = "github.com/go-sql-driver/mysql" @@ -293,8 +192,8 @@ "ptypes/empty", "ptypes/timestamp" ] - revision = "925541529c1fa6821df4e44ce2723319eb2be768" - version = "v1.0.0" + revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" + version = "v1.1.0" [[projects]] branch = "master" @@ -302,18 +201,6 @@ packages = ["."] revision = "e89373fe6b4a7413d7acd6da1725b83ef713e6e4" -[[projects]] - name = "github.com/gorilla/context" - packages = ["."] - revision = "1ea25387ff6f684839d82767c1733ff4d4d15d0a" - version = "v1.1" - -[[projects]] - name = "github.com/gorilla/mux" - packages = ["."] - revision = "53c1911da2b537f792e7cafcb446b05ffe33b996" - version = "v1.6.1" - [[projects]] name = "github.com/grpc-ecosystem/go-grpc-middleware" packages = ["."] @@ -332,7 +219,7 @@ ".", "reflectx" ] - revision = "cf35089a197953c69420c8d0cecda90809764b1d" + revision = "0dae4fefe7c0e190f7b5a78dac28a1c82cc8d849" [[projects]] branch = "master" @@ -343,16 +230,6 @@ ] revision = "90697d60dd844d5ef6ff15135d0203f65d2f53b8" -[[projects]] - branch = "master" - name = "github.com/mailru/easyjson" - packages = [ - "buffer", - "jlexer", - "jwriter" - ] - revision = "8b799c424f57fa123fc63a99d6383bc6e4c02578" - [[projects]] name = "github.com/mattn/go-isatty" packages = ["."] @@ -362,20 +239,14 @@ [[projects]] name = "github.com/mattn/go-sqlite3" packages = ["."] - revision = "6c771bb9887719704b210e87e934f08be014bdb1" - version = "v1.6.0" + revision = "25ecb14adfc7543176f7d85291ec7dba82c6f7e4" + version = "v1.9.0" [[projects]] name = "github.com/matttproud/golang_protobuf_extensions" packages = ["pbutil"] - revision = "3247c84500bff8d9fb6d579d800f20b3e091582c" - version = "v1.0.0" - -[[projects]] - branch = "master" - name = "github.com/mitchellh/mapstructure" - packages = ["."] - revision = "00c29f56e2386353d58c599509e8dc3801b0d716" + revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c" + version = "v1.0.1" [[projects]] name = "github.com/opencontainers/go-digest" @@ -452,7 +323,7 @@ "internal/bitbucket.org/ww/goautoneg", "model" ] - revision = "38c53a9f4bfcd932d1b00bfc65e256a7fba6b37a" + revision = "7600349dcfe1abd18d72d3a1770870d9800a7801" [[projects]] branch = "master" @@ -463,7 +334,7 @@ "nfs", "xfs" ] - revision = "780932d4fbbe0e69b84c34c20f5c8d0981e109ea" + revision = "7d6f385de8bea29190f15ba9931442a0eaef9af7" [[projects]] name = "github.com/sirupsen/logrus" @@ -476,8 +347,8 @@ [[projects]] name = "github.com/ugorji/go" packages = ["codec"] - revision = "9831f2c3ac1068a78f50999a30db84270f647af6" - version = "v1.1" + revision = "b4c50a2b199d93b13dc15e78929cfb23bfdf21ab" + version = "v1.1.1" [[projects]] name = "go.opencensus.io" @@ -505,7 +376,7 @@ branch = "master" name = "golang.org/x/crypto" packages = ["ssh/terminal"] - revision = "88942b9c40a4c9d203b82b3731787b672d6e809b" + revision = "7f39a6fea4fe9364fb61e1def6a268a51b4f3a06" [[projects]] branch = "master" @@ -513,14 +384,14 @@ packages = [ "context", "context/ctxhttp", + "http/httpguts", "http2", "http2/hpack", "idna", "internal/timeseries", - "lex/httplex", "trace" ] - revision = "6078986fec03a1dcc236c34816c71b0e05018fda" + revision = "db08ff08e8622530d9ed3a0e8ac279f6d4c02196" [[projects]] branch = "master" @@ -535,7 +406,7 @@ "unix", "windows" ] - revision = "13d03a9a82fba647c21a0ef8fba44a795d0f0835" + revision = "ad87a3a340fa7f3bed189293fbfa7a9b7e021ae1" [[projects]] name = "golang.org/x/text" @@ -553,8 +424,7 @@ "unicode/bidi", "unicode/cldr", "unicode/norm", - "unicode/rangetable", - "width" + "unicode/rangetable" ] revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" version = "v0.3.0" @@ -563,19 +433,19 @@ branch = "master" name = "golang.org/x/time" packages = ["rate"] - revision = "26559e0f760e39c24d730d3224364aef164ee23f" + revision = "fbb02b2291d28baffd63558aa44b4b56f178d650" [[projects]] branch = "master" name = "google.golang.org/api" packages = ["support/bundler"] - revision = "e4126357c891acdef6dcd7805daa4c6533be6544" + revision = "2eea9ba0a3d94f6ab46508083e299a00bbbc65f6" [[projects]] branch = "master" name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] - revision = "ab0870e398d5dd054b868c0db1481ab029b9a9f2" + revision = "32ee49c4dd805befd833990acba36cb75042378c" [[projects]] name = "google.golang.org/grpc" @@ -589,9 +459,11 @@ "credentials", "encoding", "encoding/proto", - "grpclb/grpc_lb_v1/messages", "grpclog", "internal", + "internal/backoff", + "internal/channelz", + "internal/grpcrand", "keepalive", "metadata", "naming", @@ -604,8 +476,8 @@ "tap", "transport" ] - revision = "8e4536a86ab602859c20df5ebfd0bd4228d08655" - version = "v1.10.0" + revision = "168a6198bcb0ef175f7dacec0b8691fc141dc9b8" + version = "v1.13.0" [[projects]] name = "gopkg.in/go-playground/validator.v8" @@ -613,24 +485,15 @@ revision = "5f1438d3fca68893a817e4a66806cea46a9e4ebf" version = "v8.18.2" -[[projects]] - branch = "v2" - name = "gopkg.in/mgo.v2" - packages = [ - "bson", - "internal/json" - ] - revision = "3f83fa5005286a7fe593b055f0d7771a7dce4655" - [[projects]] name = "gopkg.in/yaml.v2" packages = ["."] - revision = "86f5ed62f8a0ee96bd888d2efdfd6d4fb100a4eb" - version = "v2.2.0" + revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" + version = "v2.2.1" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "c988af213ce5e034443bccfd948933a7f8ac9caf98a7c8a4730202dbf32372e7" + inputs-digest = "643d4a3862aeaa6f1115edc26fa3f1f3a6822bb17c01d60fcbdf9ce98bf183ac" solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index 67c580acd..295e0d4f6 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -28,18 +28,10 @@ ignored = ["github.com/fnproject/fn/cli", name = "github.com/boltdb/bolt" revision = "fa5367d20c994db73282594be0146ab221657943" -[[constraint]] - name = "github.com/fnproject/fn_go" - version = "0.2.6" - [[constraint]] name = "github.com/gin-gonic/gin" version = "v1.2" -[[constraint]] - branch = "master" - name = "github.com/go-openapi/strfmt" - [[constraint]] branch = "master" name = "github.com/google/btree" @@ -82,3 +74,6 @@ ignored = ["github.com/fnproject/fn/cli", name = "github.com/dchest/siphash" version = "1.1.0" +[[override]] + name = "github.com/docker/docker" + revision = "29fc64b590badcb1c3f5beff7563ffd31eb58974" diff --git a/api/agent/agent.go b/api/agent/agent.go index ec9111418..3d7725bfb 100644 --- a/api/agent/agent.go +++ b/api/agent/agent.go @@ -18,7 +18,6 @@ import ( "github.com/fnproject/fn/api/id" "github.com/fnproject/fn/api/models" "github.com/fnproject/fn/fnext" - "github.com/go-openapi/strfmt" "github.com/sirupsen/logrus" "go.opencensus.io/stats" "go.opencensus.io/trace" @@ -804,7 +803,7 @@ func (a *agent) prepCold(ctx context.Context, call *call, tok ResourceToken, ch deadline := time.Now().Add(time.Duration(call.Timeout) * time.Second) // add Fn-specific information to the config to shove everything into env vars for cold - call.Config["FN_DEADLINE"] = strfmt.DateTime(deadline).String() + call.Config["FN_DEADLINE"] = common.DateTime(deadline).String() call.Config["FN_METHOD"] = call.Model().Method call.Config["FN_REQUEST_URL"] = call.Model().URL call.Config["FN_CALL_ID"] = call.Model().ID diff --git a/api/agent/call.go b/api/agent/call.go index b6a783e32..201c2e6d1 100644 --- a/api/agent/call.go +++ b/api/agent/call.go @@ -16,7 +16,6 @@ import ( "github.com/fnproject/fn/api/common" "github.com/fnproject/fn/api/id" "github.com/fnproject/fn/api/models" - "github.com/go-openapi/strfmt" "github.com/sirupsen/logrus" ) @@ -128,7 +127,7 @@ func FromRequest(a Agent, app *models.App, path string, req *http.Request) CallO Config: buildConfig(app, route), Annotations: buildAnnotations(app, route), Headers: req.Header, - CreatedAt: strfmt.DateTime(time.Now()), + CreatedAt: common.DateTime(time.Now()), URL: reqURL(req), Method: req.Method, AppID: app.ID, @@ -373,7 +372,7 @@ func (c *call) Start(ctx context.Context) error { return ctx.Err() } - c.StartedAt = strfmt.DateTime(time.Now()) + c.StartedAt = common.DateTime(time.Now()) c.Status = "running" if !c.isLB { @@ -411,7 +410,7 @@ func (c *call) End(ctx context.Context, errIn error) error { ctx, span := trace.StartSpan(ctx, "agent_call_end") defer span.End() - c.CompletedAt = strfmt.DateTime(time.Now()) + c.CompletedAt = common.DateTime(time.Now()) switch errIn { case nil: diff --git a/api/agent/drivers/docker/docker.go b/api/agent/drivers/docker/docker.go index 760518014..a26e1b010 100644 --- a/api/agent/drivers/docker/docker.go +++ b/api/agent/drivers/docker/docker.go @@ -22,7 +22,6 @@ import ( "github.com/fnproject/fn/api/common" "github.com/fnproject/fn/api/models" "github.com/fsouza/go-dockerclient" - "github.com/go-openapi/strfmt" "github.com/sirupsen/logrus" ) @@ -536,7 +535,7 @@ func cherryPick(ds *docker.Stats) drivers.Stat { } return drivers.Stat{ - Timestamp: strfmt.DateTime(ds.Read), + Timestamp: common.DateTime(ds.Read), Metrics: map[string]uint64{ // source: https://godoc.org/github.com/fsouza/go-dockerclient#Stats // ex (for future expansion): {"read":"2016-08-03T18:08:05Z","pids_stats":{},"network":{},"networks":{"eth0":{"rx_bytes":508,"tx_packets":6,"rx_packets":6,"tx_bytes":508}},"memory_stats":{"stats":{"cache":16384,"pgpgout":281,"rss":8826880,"pgpgin":2440,"total_rss":8826880,"hierarchical_memory_limit":536870912,"total_pgfault":3809,"active_anon":8843264,"total_active_anon":8843264,"total_pgpgout":281,"total_cache":16384,"pgfault":3809,"total_pgpgin":2440},"max_usage":8953856,"usage":8953856,"limit":536870912},"blkio_stats":{"io_service_bytes_recursive":[{"major":202,"op":"Read"},{"major":202,"op":"Write"},{"major":202,"op":"Sync"},{"major":202,"op":"Async"},{"major":202,"op":"Total"}],"io_serviced_recursive":[{"major":202,"op":"Read"},{"major":202,"op":"Write"},{"major":202,"op":"Sync"},{"major":202,"op":"Async"},{"major":202,"op":"Total"}]},"cpu_stats":{"cpu_usage":{"percpu_usage":[47641874],"usage_in_usermode":30000000,"total_usage":47641874},"system_cpu_usage":8880800500000000,"throttling_data":{}},"precpu_stats":{"cpu_usage":{"percpu_usage":[44946186],"usage_in_usermode":30000000,"total_usage":44946186},"system_cpu_usage":8880799510000000,"throttling_data":{}}} diff --git a/api/agent/drivers/driver.go b/api/agent/drivers/driver.go index b5977fa9d..0b51b87da 100644 --- a/api/agent/drivers/driver.go +++ b/api/agent/drivers/driver.go @@ -12,7 +12,7 @@ import ( "strings" "time" - "github.com/go-openapi/strfmt" + "github.com/fnproject/fn/api/common" ) // A DriverCookie identifies a unique request to run a task. @@ -146,7 +146,7 @@ type ContainerTask interface { // Stat is a bucket of stats from a driver at a point in time for a certain task. type Stat struct { - Timestamp strfmt.DateTime `json:"timestamp"` + Timestamp common.DateTime `json:"timestamp"` Metrics map[string]uint64 `json:"metrics"` } @@ -237,7 +237,7 @@ func average(samples []Stat) (Stat, bool) { } } - s.Timestamp = strfmt.DateTime(time.Unix(0, t)) + s.Timestamp = common.DateTime(time.Unix(0, t)) for k, v := range s.Metrics { s.Metrics[k] = v / uint64(l) } diff --git a/api/agent/drivers/driver_test.go b/api/agent/drivers/driver_test.go index f33e2091b..9964a159f 100644 --- a/api/agent/drivers/driver_test.go +++ b/api/agent/drivers/driver_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "github.com/go-openapi/strfmt" + "github.com/fnproject/fn/api/common" ) func TestAverage(t *testing.T) { @@ -12,7 +12,7 @@ func TestAverage(t *testing.T) { stats := make([]Stat, 10) for i := 0; i < len(stats); i++ { stats[i] = Stat{ - Timestamp: strfmt.DateTime(start.Add(time.Duration(i) * time.Minute)), + Timestamp: common.DateTime(start.Add(time.Duration(i) * time.Minute)), Metrics: map[string]uint64{"x": uint64(i)}, } } @@ -38,7 +38,7 @@ func TestDecimate(t *testing.T) { stats := make([]Stat, 480) for i := range stats { stats[i] = Stat{ - Timestamp: strfmt.DateTime(start.Add(time.Duration(i) * time.Second)), + Timestamp: common.DateTime(start.Add(time.Duration(i) * time.Second)), Metrics: map[string]uint64{"x": uint64(i)}, } } @@ -55,7 +55,7 @@ func TestDecimate(t *testing.T) { stats = make([]Stat, 700) for i := range stats { stats[i] = Stat{ - Timestamp: strfmt.DateTime(start.Add(time.Duration(i) * time.Second)), + Timestamp: common.DateTime(start.Add(time.Duration(i) * time.Second)), Metrics: map[string]uint64{"x": uint64(i)}, } } @@ -67,7 +67,7 @@ func TestDecimate(t *testing.T) { stats = make([]Stat, 300) for i := range stats { stats[i] = Stat{ - Timestamp: strfmt.DateTime(start.Add(time.Duration(i) * time.Second)), + Timestamp: common.DateTime(start.Add(time.Duration(i) * time.Second)), Metrics: map[string]uint64{"x": uint64(i)}, } } @@ -83,7 +83,7 @@ func TestDecimate(t *testing.T) { start = start.Add(20 * time.Minute) } stats[i] = Stat{ - Timestamp: strfmt.DateTime(start.Add(time.Duration(i) * time.Second)), + Timestamp: common.DateTime(start.Add(time.Duration(i) * time.Second)), Metrics: map[string]uint64{"x": uint64(i)}, } } diff --git a/api/agent/protocol/cloudevent_test.go b/api/agent/protocol/cloudevent_test.go index be8bed402..7efb398c0 100644 --- a/api/agent/protocol/cloudevent_test.go +++ b/api/agent/protocol/cloudevent_test.go @@ -9,7 +9,7 @@ import ( "testing" "time" - "github.com/go-openapi/strfmt" + "github.com/fnproject/fn/api/common" ) // implements CallInfo, modify as needed @@ -23,8 +23,8 @@ func (t *testCall) IsCloudEvent() bool { return t.cloud } func (t *testCall) CallID() string { return "foo" } func (t *testCall) ContentType() string { return t.contentType } func (t *testCall) Input() io.Reader { return t.input } -func (t *testCall) Deadline() strfmt.DateTime { - return strfmt.DateTime(time.Now().Add(30 * time.Second)) +func (t *testCall) Deadline() common.DateTime { + return common.DateTime(time.Now().Add(30 * time.Second)) } func (t *testCall) CallType() string { return "sync" } func (t *testCall) ProtocolType() string { return "http" } diff --git a/api/agent/protocol/factory.go b/api/agent/protocol/factory.go index 5284881ae..e26aa7a5d 100644 --- a/api/agent/protocol/factory.go +++ b/api/agent/protocol/factory.go @@ -6,8 +6,8 @@ import ( "io" "net/http" + "github.com/fnproject/fn/api/common" "github.com/fnproject/fn/api/models" - "github.com/go-openapi/strfmt" ) var errInvalidProtocol = errors.New("Invalid Protocol") @@ -39,7 +39,7 @@ type CallInfo interface { CallID() string ContentType() string Input() io.Reader - Deadline() strfmt.DateTime + Deadline() common.DateTime CallType() string // ProtocolType let's function/fdk's know what type original request is. Only 'http' for now. @@ -75,13 +75,13 @@ func (ci callInfoImpl) Input() io.Reader { return ci.req.Body } -func (ci callInfoImpl) Deadline() strfmt.DateTime { +func (ci callInfoImpl) Deadline() common.DateTime { deadline, ok := ci.req.Context().Deadline() if !ok { // In theory deadline must have been set here panic("No context deadline is set in protocol, should never happen") } - return strfmt.DateTime(deadline) + return common.DateTime(deadline) } // CallType returns whether the function call was "sync" or "async". diff --git a/api/agent/pure_runner.go b/api/agent/pure_runner.go index cd58100f5..5fa334479 100644 --- a/api/agent/pure_runner.go +++ b/api/agent/pure_runner.go @@ -22,7 +22,6 @@ import ( "github.com/fnproject/fn/api/models" "github.com/fnproject/fn/fnext" "github.com/fnproject/fn/grpcutil" - "github.com/go-openapi/strfmt" "github.com/golang/protobuf/ptypes/empty" "github.com/sirupsen/logrus" "google.golang.org/grpc" @@ -69,7 +68,7 @@ type callHandle struct { c *call // the agent's version of call // Timings, for metrics: - receivedTime strfmt.DateTime // When was the call received? + receivedTime common.DateTime // When was the call received? // For implementing http.ResponseWriter: headers http.Header @@ -525,7 +524,7 @@ func (pr *pureRunner) spawnSubmit(state *callHandle) { // handleTryCall based on the TryCall message, tries to place the call on NBIO Agent func (pr *pureRunner) handleTryCall(tc *runner.TryCall, state *callHandle) error { - state.receivedTime = strfmt.DateTime(time.Now()) + state.receivedTime = common.DateTime(time.Now()) var c models.Call err := json.Unmarshal([]byte(tc.ModelsCallJson), &c) if err != nil { diff --git a/vendor/github.com/go-openapi/strfmt/time.go b/api/common/time.go similarity index 70% rename from vendor/github.com/go-openapi/strfmt/time.go rename to api/common/time.go index 4889ab821..09029274f 100644 --- a/vendor/github.com/go-openapi/strfmt/time.go +++ b/api/common/time.go @@ -12,25 +12,23 @@ // See the License for the specific language governing permissions and // limitations under the License. -package strfmt +// ^ we took this from then, and got rid of mgo since it's not a dep of ours. +// we can also change resolution to not be milliseconds. there's your attribution. + +package common import ( "database/sql/driver" - "errors" "fmt" "regexp" "strings" "time" - - "gopkg.in/mgo.v2/bson" - - "github.com/mailru/easyjson/jlexer" - "github.com/mailru/easyjson/jwriter" ) -func init() { - dt := DateTime{} - Default.Add("datetime", &dt, IsDateTime) +// IsDate returns true when the string is a valid date +func IsDate(str string) bool { + _, err := time.Parse(RFC3339FullDate, str) + return err == nil } // IsDateTime returns true when the string is a valid date-time @@ -59,6 +57,10 @@ const ( RFC3339Micro = "2006-01-02T15:04:05.000000Z07:00" // DateTimePattern pattern to match for the date-time format from http://tools.ietf.org/html/rfc3339#section-5.6 DateTimePattern = `^([0-9]{2}):([0-9]{2}):([0-9]{2})(.[0-9]+)?(z|([+-][0-9]{2}:[0-9]{2}))$` + + // RFC3339FullDate represents a full-date as specified by RFC3339 + // See: http://goo.gl/xXOvVd + RFC3339FullDate = "2006-01-02" ) var ( @@ -90,8 +92,6 @@ func ParseDateTime(data string) (DateTime, error) { // It knows how to read 3 different variations of a RFC3339 date time. // Most APIs we encounter want either millisecond or second precision times. // This just tries to make it worry-free. -// -// swagger:strfmt date-time type DateTime time.Time // NewDateTime is a representation of zero value for DateTime type @@ -132,7 +132,7 @@ func (t *DateTime) Scan(raw interface{}) error { case nil: *t = DateTime{} default: - return fmt.Errorf("cannot sql.Scan() strfmt.DateTime from: %#v", v) + return fmt.Errorf("cannot sql.Scan() common.DateTime from: %#v", v) } return nil @@ -142,55 +142,3 @@ func (t *DateTime) Scan(raw interface{}) error { func (t DateTime) Value() (driver.Value, error) { return driver.Value(t.String()), nil } - -// MarshalJSON returns the DateTime as JSON -func (t DateTime) MarshalJSON() ([]byte, error) { - var w jwriter.Writer - t.MarshalEasyJSON(&w) - return w.BuildBytes() -} - -// MarshalEasyJSON writes the DateTime to a easyjson.Writer -func (t DateTime) MarshalEasyJSON(w *jwriter.Writer) { - w.String(time.Time(t).Format(MarshalFormat)) -} - -// UnmarshalJSON sets the DateTime from JSON -func (t *DateTime) UnmarshalJSON(data []byte) error { - l := jlexer.Lexer{Data: data} - t.UnmarshalEasyJSON(&l) - return l.Error() -} - -// UnmarshalEasyJSON sets the DateTime from a easyjson.Lexer -func (t *DateTime) UnmarshalEasyJSON(in *jlexer.Lexer) { - if data := in.String(); in.Ok() { - tt, err := ParseDateTime(data) - if err != nil { - in.AddError(err) - return - } - *t = tt - } -} - -// GetBSON returns the DateTime as a bson.M{} map. -func (t *DateTime) GetBSON() (interface{}, error) { - return bson.M{"data": t.String()}, nil -} - -// SetBSON sets the DateTime from raw bson data -func (t *DateTime) SetBSON(raw bson.Raw) error { - var m bson.M - if err := raw.Unmarshal(&m); err != nil { - return err - } - - if data, ok := m["data"].(string); ok { - var err error - *t, err = ParseDateTime(data) - return err - } - - return errors.New("couldn't unmarshal bson raw value as Duration") -} diff --git a/api/logs/testing/test.go b/api/logs/testing/test.go index 90d58817e..98614bb74 100644 --- a/api/logs/testing/test.go +++ b/api/logs/testing/test.go @@ -8,9 +8,9 @@ import ( "testing" "time" + "github.com/fnproject/fn/api/common" "github.com/fnproject/fn/api/id" "github.com/fnproject/fn/api/models" - "github.com/go-openapi/strfmt" ) var testApp = &models.App{ @@ -30,10 +30,10 @@ func SetupTestCall(t *testing.T, ctx context.Context, ls models.LogStore) *model var call models.Call call.AppID = testApp.ID - call.CreatedAt = strfmt.DateTime(time.Now()) + call.CreatedAt = common.DateTime(time.Now()) call.Status = "success" - call.StartedAt = strfmt.DateTime(time.Now()) - call.CompletedAt = strfmt.DateTime(time.Now()) + call.StartedAt = common.DateTime(time.Now()) + call.CompletedAt = common.DateTime(time.Now()) call.Path = testRoute.Path return &call } @@ -48,7 +48,7 @@ func Test(t *testing.T, fnl models.LogStore) { t.Run("calls-get", func(t *testing.T) { filter := &models.CallFilter{AppID: call.AppID, Path: call.Path, PerPage: 100} now := time.Now() - call.CreatedAt = strfmt.DateTime(now) + call.CreatedAt = common.DateTime(now) call.ID = id.New().String() err := fnl.InsertCall(ctx, call) if err != nil { @@ -65,11 +65,11 @@ func Test(t *testing.T, fnl models.LogStore) { c2 := *call c3 := *call now = time.Now().Add(100 * time.Millisecond) - c2.CreatedAt = strfmt.DateTime(now) // add ms cuz db uses it for sort + c2.CreatedAt = common.DateTime(now) // add ms cuz db uses it for sort c2.ID = id.New().String() now = time.Now().Add(200 * time.Millisecond) - c3.CreatedAt = strfmt.DateTime(now) + c3.CreatedAt = common.DateTime(now) c3.ID = id.New().String() err = fnl.InsertCall(ctx, &c2) @@ -177,11 +177,11 @@ func Test(t *testing.T, fnl models.LogStore) { }) call = new(models.Call) - call.CreatedAt = strfmt.DateTime(time.Now()) + call.CreatedAt = common.DateTime(time.Now()) call.Status = "error" call.Error = "ya dun goofed" - call.StartedAt = strfmt.DateTime(time.Now()) - call.CompletedAt = strfmt.DateTime(time.Now()) + call.StartedAt = common.DateTime(time.Now()) + call.CompletedAt = common.DateTime(time.Now()) call.AppID = testApp.Name call.Path = testRoute.Path diff --git a/api/models/app.go b/api/models/app.go index 327e99ce9..00f7fec8e 100644 --- a/api/models/app.go +++ b/api/models/app.go @@ -8,8 +8,8 @@ import ( "time" "unicode" + "github.com/fnproject/fn/api/common" "github.com/fnproject/fn/api/id" - "github.com/go-openapi/strfmt" ) type App struct { @@ -18,16 +18,16 @@ type App struct { Config Config `json:"config,omitempty" db:"config"` Annotations Annotations `json:"annotations,omitempty" db:"annotations"` SyslogURL *string `json:"syslog_url,omitempty" db:"syslog_url"` - CreatedAt strfmt.DateTime `json:"created_at,omitempty" db:"created_at"` - UpdatedAt strfmt.DateTime `json:"updated_at,omitempty" db:"updated_at"` + CreatedAt common.DateTime `json:"created_at,omitempty" db:"created_at"` + UpdatedAt common.DateTime `json:"updated_at,omitempty" db:"updated_at"` } func (a *App) SetDefaults() { if time.Time(a.CreatedAt).IsZero() { - a.CreatedAt = strfmt.DateTime(time.Now()) + a.CreatedAt = common.DateTime(time.Now()) } if time.Time(a.UpdatedAt).IsZero() { - a.UpdatedAt = strfmt.DateTime(time.Now()) + a.UpdatedAt = common.DateTime(time.Now()) } if a.Config == nil { // keeps the json from being nil @@ -134,7 +134,7 @@ func (a *App) Update(patch *App) { a.Annotations = a.Annotations.MergeChange(patch.Annotations) if !a.Equals(original) { - a.UpdatedAt = strfmt.DateTime(time.Now()) + a.UpdatedAt = common.DateTime(time.Now()) } } diff --git a/api/models/call.go b/api/models/call.go index def3f6e0a..f4561e34b 100644 --- a/api/models/call.go +++ b/api/models/call.go @@ -4,7 +4,7 @@ import ( "net/http" "github.com/fnproject/fn/api/agent/drivers" - "github.com/go-openapi/strfmt" + "github.com/fnproject/fn/api/common" ) const ( @@ -132,13 +132,13 @@ type Call struct { SyslogURL string `json:"syslog_url,omitempty" db:"-"` // Time when call completed, whether it was successul or failed. Always in UTC. - CompletedAt strfmt.DateTime `json:"completed_at,omitempty" db:"completed_at"` + CompletedAt common.DateTime `json:"completed_at,omitempty" db:"completed_at"` // Time when call was submitted. Always in UTC. - CreatedAt strfmt.DateTime `json:"created_at,omitempty" db:"created_at"` + CreatedAt common.DateTime `json:"created_at,omitempty" db:"created_at"` // Time when call started execution. Always in UTC. - StartedAt strfmt.DateTime `json:"started_at,omitempty" db:"started_at"` + StartedAt common.DateTime `json:"started_at,omitempty" db:"started_at"` // Stats is a list of metrics from this call's execution, possibly empty. Stats drivers.Stats `json:"stats,omitempty" db:"stats"` @@ -154,8 +154,8 @@ type Call struct { type CallFilter struct { Path string // match AppID string // match - FromTime strfmt.DateTime - ToTime strfmt.DateTime + FromTime common.DateTime + ToTime common.DateTime Cursor string PerPage int } diff --git a/api/models/route.go b/api/models/route.go index 2558666be..7fd4a7e57 100644 --- a/api/models/route.go +++ b/api/models/route.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "github.com/go-openapi/strfmt" + "github.com/fnproject/fn/api/common" ) const ( @@ -38,8 +38,8 @@ type Route struct { TmpFsSize uint32 `json:"tmpfs_size" db:"tmpfs_size"` Config Config `json:"config,omitempty" db:"config"` Annotations Annotations `json:"annotations,omitempty" db:"annotations"` - CreatedAt strfmt.DateTime `json:"created_at,omitempty" db:"created_at"` - UpdatedAt strfmt.DateTime `json:"updated_at,omitempty" db:"updated_at"` + CreatedAt common.DateTime `json:"created_at,omitempty" db:"created_at"` + UpdatedAt common.DateTime `json:"updated_at,omitempty" db:"updated_at"` } // SetDefaults sets zeroed field to defaults. @@ -74,11 +74,11 @@ func (r *Route) SetDefaults() { } if time.Time(r.CreatedAt).IsZero() { - r.CreatedAt = strfmt.DateTime(time.Now()) + r.CreatedAt = common.DateTime(time.Now()) } if time.Time(r.UpdatedAt).IsZero() { - r.UpdatedAt = strfmt.DateTime(time.Now()) + r.UpdatedAt = common.DateTime(time.Now()) } } @@ -243,7 +243,7 @@ func (r *Route) Update(patch *Route) { r.Annotations = r.Annotations.MergeChange(patch.Annotations) if !r.Equals(original) { - r.UpdatedAt = strfmt.DateTime(time.Now()) + r.UpdatedAt = common.DateTime(time.Now()) } } diff --git a/api/server/call_list.go b/api/server/call_list.go index f43c9e726..47d299b9a 100644 --- a/api/server/call_list.go +++ b/api/server/call_list.go @@ -6,9 +6,9 @@ import ( "time" "github.com/fnproject/fn/api" + "github.com/fnproject/fn/api/common" "github.com/fnproject/fn/api/models" "github.com/gin-gonic/gin" - "github.com/go-openapi/strfmt" ) func (s *Server) handleCallList(c *gin.Context) { @@ -42,7 +42,7 @@ func (s *Server) handleCallList(c *gin.Context) { } // "" gets parsed to a zero time, which is fine (ignored in query) -func timeParams(c *gin.Context) (fromTime, toTime strfmt.DateTime, err error) { +func timeParams(c *gin.Context) (fromTime, toTime common.DateTime, err error) { fromStr := c.Query("from_time") toStr := c.Query("to_time") var ok bool @@ -61,10 +61,10 @@ func timeParams(c *gin.Context) (fromTime, toTime strfmt.DateTime, err error) { return fromTime, toTime, nil } -func strToTime(str string) (strfmt.DateTime, bool) { +func strToTime(str string) (common.DateTime, bool) { sec, err := strconv.ParseInt(str, 10, 64) if err != nil { - return strfmt.DateTime(time.Time{}), false + return common.DateTime(time.Time{}), false } - return strfmt.DateTime(time.Unix(sec, 0)), true + return common.DateTime(time.Unix(sec, 0)), true } diff --git a/api/server/calls_test.go b/api/server/calls_test.go index bfd4bcd6b..831b1765d 100644 --- a/api/server/calls_test.go +++ b/api/server/calls_test.go @@ -8,12 +8,12 @@ import ( "testing" "time" + "github.com/fnproject/fn/api/common" "github.com/fnproject/fn/api/datastore" "github.com/fnproject/fn/api/id" "github.com/fnproject/fn/api/logs" "github.com/fnproject/fn/api/models" "github.com/fnproject/fn/api/mqs" - "github.com/go-openapi/strfmt" ) func TestCallGet(t *testing.T) { @@ -39,7 +39,7 @@ func TestCallGet(t *testing.T) { Timeout: 30, IdleTimeout: 30, Memory: 256, - CreatedAt: strfmt.DateTime(time.Now()), + CreatedAt: common.DateTime(time.Now()), URL: "http://localhost:8080/r/myapp/thisisatest", Method: "GET", } @@ -110,16 +110,16 @@ func TestCallList(t *testing.T) { Timeout: 30, IdleTimeout: 30, Memory: 256, - CreatedAt: strfmt.DateTime(time.Now()), + CreatedAt: common.DateTime(time.Now()), URL: "http://localhost:8080/r/myapp/thisisatest", Method: "GET", } c2 := *call c3 := *call - c2.CreatedAt = strfmt.DateTime(time.Now().Add(100 * time.Second)) + c2.CreatedAt = common.DateTime(time.Now().Add(100 * time.Second)) c2.ID = id.New().String() c2.Path = "test2" - c3.CreatedAt = strfmt.DateTime(time.Now().Add(200 * time.Second)) + c3.CreatedAt = common.DateTime(time.Now().Add(200 * time.Second)) c3.ID = id.New().String() c3.Path = "/test3" diff --git a/api/server/hybrid.go b/api/server/hybrid.go index e8bbabee4..89a44f8ed 100644 --- a/api/server/hybrid.go +++ b/api/server/hybrid.go @@ -119,7 +119,7 @@ func (s *Server) handleRunnerStart(c *gin.Context) { // cover our tracks since if the db is down we can't run anything anyway (treat as such). // TODO do this client side and validate it here? //call.Status = "running" - //call.StartedAt = strfmt.DateTime(time.Now()) + //call.StartedAt = common.DateTime(time.Now()) //err := s.datastore.UpdateCall(c.Request.Context(), &call) //if err != nil { //if err == InvalidStatusChange { diff --git a/test/fn-api-tests/README.md b/test/fn-api-tests/README.md deleted file mode 100644 index a9a1cac2f..000000000 --- a/test/fn-api-tests/README.md +++ /dev/null @@ -1,22 +0,0 @@ -FN integration API tests -====================================== - - -These are tests that can either run locally against the current codebase (e.g. in an IDE) or remotely against a running Fn instance. - - -Test dependencies ------------------ - -```bash -DOCKER_HOST - for building images -FN_API_URL - Fn API endpoint - leave this unset to test using the local codebase -``` - -How to run tests? ------------------ - -```bash -export FN_API_URL=http://localhost:8080 -go test -v ./... -``` diff --git a/test/fn-api-tests/annotation_cases.go b/test/fn-api-tests/annotation_cases.go deleted file mode 100644 index dab2e0b1f..000000000 --- a/test/fn-api-tests/annotation_cases.go +++ /dev/null @@ -1,84 +0,0 @@ -package tests - -import ( - "fmt" - "reflect" - "strings" -) - -// common test cases around annotations (shared by any objects that support it) - -const ( - maxAnnotationKeys = 100 - maxAnnotationValueSize = 512 - maxAnnotationKeySize = 128 -) - -var emptyAnnMap = map[string]interface{}{} - -func makeAnnMap(size int) map[string]interface{} { - md := make(map[string]interface{}, size) - for i := 0; i < size; i++ { - md[fmt.Sprintf("k-%d", i)] = "val" - } - return md -} - -var createAnnotationsValidCases = []struct { - name string - annotations map[string]interface{} -}{ - {"valid_string", map[string]interface{}{"key": "value"}}, - {"valid_array", map[string]interface{}{"key": []interface{}{"value1", "value2"}}}, - {"valid_object", map[string]interface{}{"key": map[string]interface{}{"foo": "bar"}}}, - {"max_value_size", map[string]interface{}{"key": strings.Repeat("a", maxAnnotationValueSize-2)}}, - {"max_key_size", map[string]interface{}{strings.Repeat("a", maxAnnotationKeySize): "val"}}, - {"max_map_size", makeAnnMap(maxAnnotationKeys)}, -} - -var createAnnotationsErrorCases = []struct { - name string - annotations map[string]interface{} -}{ - {"value_too_long", map[string]interface{}{"key": strings.Repeat("a", maxAnnotationValueSize-1)}}, - {"key_too_long", map[string]interface{}{strings.Repeat("a", maxAnnotationKeySize+1): "value"}}, - {"whitespace_in_key", map[string]interface{}{" bad key ": "value"}}, - {"too_many_keys", makeAnnMap(maxAnnotationKeys + 1)}, -} - -var updateAnnotationsValidCases = []struct { - name string - initial map[string]interface{} - change map[string]interface{} - expected map[string]interface{} -}{ - {"overwrite_existing_annotation_keys", map[string]interface{}{"key": "value1"}, map[string]interface{}{"key": "value2"}, map[string]interface{}{"key": "value2"}}, - {"delete_annotation_key", map[string]interface{}{"key": "value1"}, map[string]interface{}{"key": ""}, map[string]interface{}{}}, - {"set_to_max_size_with_deletes", map[string]interface{}{"key": "value1"}, func() map[string]interface{} { - md := makeAnnMap(100) - md["key"] = "" - return md - }(), makeAnnMap(100)}, - {"noop_with_max_keys", makeAnnMap(maxAnnotationKeys), emptyAnnMap, makeAnnMap(maxAnnotationKeys)}, -} - -var updateAnnotationsErrorCases = []struct { - name string - initial map[string]interface{} - change map[string]interface{} -}{ - {"too_many_key_after_update", makeAnnMap(100), map[string]interface{}{"key": "value1"}}, - {"value_too_long", map[string]interface{}{}, map[string]interface{}{"key": strings.Repeat("a", maxAnnotationValueSize-1)}}, - {"key_too_long", map[string]interface{}{}, map[string]interface{}{strings.Repeat("a", maxAnnotationKeySize+1): "value"}}, - {"whitespace_in_key", map[string]interface{}{}, map[string]interface{}{" bad key ": "value"}}, - {"too_many_keys_in_update", map[string]interface{}{}, makeAnnMap(maxAnnotationKeys + 1)}, -} - -//AnnotationsEquivalent checks if two annotations maps are semantically equivalent, including nil == empty map -func AnnotationsEquivalent(md1, md2 map[string]interface{}) bool { - - if len(md1) == 0 && len(md2) == 0 { - return true - } - return reflect.DeepEqual(md1, md2) -} diff --git a/test/fn-api-tests/apps_api.go b/test/fn-api-tests/apps_api.go deleted file mode 100644 index e5254d5f8..000000000 --- a/test/fn-api-tests/apps_api.go +++ /dev/null @@ -1,68 +0,0 @@ -package tests - -import ( - "context" - "log" - "strings" - "testing" - "time" - - "github.com/fnproject/fn_go/client" - "github.com/fnproject/fn_go/client/apps" - "github.com/fnproject/fn_go/models" -) - -// PostApp creates an app and esures it is deleted on teardown if it was created -func (s *TestHarness) PostApp(app *models.App) (*apps.PostAppsOK, error) { - cfg := &apps.PostAppsParams{ - Body: &models.AppWrapper{ - App: app, - }, - Context: s.Context, - } - ok, err := s.Client.Apps.PostApps(cfg) - - if err == nil { - s.createdApps[ok.Payload.App.Name] = true - } - return ok, err -} - -// GivenAppExists creates an app and ensures it is deleted on teardown, this fatals if the app is not created -func (s *TestHarness) GivenAppExists(t *testing.T, app *models.App) { - - appPayload, err := s.PostApp(app) - if err != nil { - t.Fatalf("Failed to create app %v", app) - - } - if !strings.Contains(app.Name, appPayload.Payload.App.Name) { - t.Fatalf("App name mismatch.\nExpected: %v\nActual: %v", - app.Name, appPayload.Payload.App.Name) - } -} - -// AppMustExist fails the test if the specified app does not exist -func (s *TestHarness) AppMustExist(t *testing.T, appName string) *models.App { - app, err := s.Client.Apps.GetAppsApp(&apps.GetAppsAppParams{ - App: s.AppName, - Context: s.Context, - }) - if err != nil { - t.Fatalf("Expected new route to create app got %v", err) - return nil - } - return app.Payload.App -} - -func safeDeleteApp(ctx context.Context, fnclient *client.Fn, appName string) { - cfg := &apps.DeleteAppsAppParams{ - App: appName, - Context: ctx, - } - cfg.WithTimeout(time.Second * 60) - _, err := fnclient.Apps.DeleteAppsApp(cfg) - if _, ok := err.(*apps.DeleteAppsAppNotFound); err != nil && !ok { - log.Printf("Error cleaning up app %s: %v", appName, err) - } -} diff --git a/test/fn-api-tests/apps_test.go b/test/fn-api-tests/apps_test.go deleted file mode 100644 index 444ef5357..000000000 --- a/test/fn-api-tests/apps_test.go +++ /dev/null @@ -1,300 +0,0 @@ -package tests - -import ( - "github.com/fnproject/fn_go/client/apps" - "github.com/fnproject/fn_go/models" - "reflect" - "strings" - "testing" -) - -func TestAppDeleteNotFound(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - cfg := &apps.DeleteAppsAppParams{ - App: "missing-app", - Context: s.Context, - } - - _, err := s.Client.Apps.DeleteAppsApp(cfg) - - if _, ok := err.(*apps.DeleteAppsAppNotFound); !ok { - t.Errorf("Error during app delete: we should get HTTP 404, but got: %s", err.Error()) - } -} - -func TestAppGetNotFound(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - cfg := &apps.GetAppsAppParams{ - App: "missing-app", - Context: s.Context, - } - _, err := s.Client.Apps.GetAppsApp(cfg) - - if _, ok := err.(*apps.GetAppsAppNotFound); !ok { - t.Errorf("Error during get: we should get HTTP 404, but got: %s", err.Error()) - } - - if !strings.Contains(err.(*apps.GetAppsAppNotFound).Payload.Error.Message, "App not found") { - t.Errorf("Error during app delete: unexpeted error `%s`, wanted `App not found`", err.Error()) - } -} - -func TestAppCreateNoConfigSuccess(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - resp, err := s.PostApp(&models.App{ - Name: s.AppName, - }) - - if err != nil { - t.Errorf("Failed to create simple app %v", err) - return - } - - if resp.Payload.App.Name != s.AppName { - t.Errorf("app name in response %s does not match new app %s ", resp.Payload.App.Name, s.AppName) - } - -} - -func TestSetAppAnnotationsOnCreate(t *testing.T) { - t.Parallel() - for _, tci := range createAnnotationsValidCases { - // iterator mutation meets parallelism... pfft - tc := tci - t.Run("valid_"+tc.name, func(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - app, err := s.PostApp(&models.App{ - Name: s.AppName, - Annotations: tc.annotations, - }) - - if err != nil { - t.Fatalf("Failed to create app with valid annotations %v got error %v", tc.annotations, err) - } - - gotMd := app.Payload.App.Annotations - if !AnnotationsEquivalent(gotMd, tc.annotations) { - t.Errorf("Returned annotations %v does not match set annotations %v", gotMd, tc.annotations) - } - - getApp := s.AppMustExist(t, s.AppName) - - if !AnnotationsEquivalent(getApp.Annotations, tc.annotations) { - t.Errorf("GET annotations '%v' does not match set annotations %v", getApp.Annotations, tc.annotations) - } - - }) - } - - for _, tci := range createAnnotationsErrorCases { - // iterator mutation meets parallelism... pfft - tc := tci - t.Run("invalid_"+tc.name, func(ti *testing.T) { - ti.Parallel() - s := SetupHarness() - defer s.Cleanup() - - _, err := s.PostApp(&models.App{ - Name: s.AppName, - Annotations: tc.annotations, - }) - - if err == nil { - t.Fatalf("Created app with invalid annotations %v but expected error", tc.annotations) - } - - if _, ok := err.(*apps.PostAppsBadRequest); !ok { - t.Errorf("Expecting bad request for invalid annotations, got %v", err) - } - - }) - } -} - -func TestUpdateAppAnnotationsOnPatch(t *testing.T) { - t.Parallel() - - for _, tci := range updateAnnotationsValidCases { - // iterator mutation meets parallelism... pfft - tc := tci - t.Run("valid_"+tc.name, func(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{ - Name: s.AppName, - Annotations: tc.initial, - }) - - res, err := s.Client.Apps.PatchAppsApp(&apps.PatchAppsAppParams{ - App: s.AppName, - Context: s.Context, - Body: &models.AppWrapper{ - App: &models.App{ - Annotations: tc.change, - }, - }, - }) - - if err != nil { - t.Fatalf("Failed to patch annotations with %v on app: %v", tc.change, err) - } - - gotMd := res.Payload.App.Annotations - if !AnnotationsEquivalent(gotMd, tc.expected) { - t.Errorf("Returned annotations %v does not match set annotations %v", gotMd, tc.expected) - } - - getApp := s.AppMustExist(t, s.AppName) - - if !AnnotationsEquivalent(getApp.Annotations, tc.expected) { - t.Errorf("GET annotations '%v' does not match set annotations %v", getApp.Annotations, tc.expected) - } - }) - } - - for _, tci := range updateAnnotationsErrorCases { - // iterator mutation meets parallelism... pfft - tc := tci - t.Run("invalid_"+tc.name, func(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{ - Name: s.AppName, - Annotations: tc.initial, - }) - - _, err := s.Client.Apps.PatchAppsApp(&apps.PatchAppsAppParams{ - App: s.AppName, - Context: s.Context, - Body: &models.AppWrapper{ - App: &models.App{ - Annotations: tc.change, - }, - }, - }) - - if err == nil { - t.Errorf("patched app with invalid annotations %v but expected error", tc.change) - } - if _, ok := err.(*apps.PatchAppsAppBadRequest); !ok { - t.Errorf("Expecting bad request for invalid annotations, got %v", err) - } - - }) - } -} - -func TestAppCreateWithConfigSuccess(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - validConfig := map[string]string{"A": "a"} - appPayload, err := s.PostApp(&models.App{ - Name: s.AppName, - Config: validConfig, - }) - - if err != nil { - t.Fatalf("Failed to create app with valid config got %v", err) - } - - if !reflect.DeepEqual(validConfig, appPayload.Payload.App.Config) { - t.Errorf("Expecting config %v but got %v in response", validConfig, appPayload.Payload.App.Config) - } - -} - -func TestAppInsect(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - validConfig := map[string]string{"A": "a"} - - s.GivenAppExists(t, &models.App{Name: s.AppName, - Config: validConfig}) - - appOk, err := s.Client.Apps.GetAppsApp(&apps.GetAppsAppParams{ - App: s.AppName, - Context: s.Context, - }) - - if err != nil { - t.Fatalf("Expected valid response to get app, got %v", err) - } - - if !reflect.DeepEqual(validConfig, appOk.Payload.App.Config) { - t.Errorf("Returned config %v does not match requested config %v", appOk.Payload.App.Config, validConfig) - } -} - -func TestAppPatchConfig(t *testing.T) { - t.Parallel() - - for _, tci := range updateConfigCases { - // iterator mutation meets parallelism... pfft - tc := tci - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{ - Name: s.AppName, - Config: tc.intialConfig, - }) - - patch, err := s.Client.Apps.PatchAppsApp(&apps.PatchAppsAppParams{ - App: s.AppName, - Body: &models.AppWrapper{ - App: &models.App{ - Config: tc.change, - }, - }, - Context: s.Context, - }) - - if err != nil { - t.Fatalf("Failed to patch app with valid value %v, %v", tc.change, err) - } - - if !ConfigEquivalent(patch.Payload.App.Config, tc.expected) { - t.Errorf("Expected returned app config to be %v, but was %v", tc.expected, patch.Payload.App.Config) - } - - }) - } - -} - -func TestAppDuplicate(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - - _, err := s.PostApp(&models.App{Name: s.AppName}) - - if _, ok := err.(*apps.PostAppsConflict); !ok { - t.Errorf("Expecting conflict response on duplicate app, got %v", err) - } - -} diff --git a/test/fn-api-tests/calls_test.go b/test/fn-api-tests/calls_test.go deleted file mode 100644 index 1de2b57c3..000000000 --- a/test/fn-api-tests/calls_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package tests - -import ( - "bytes" - "net/url" - "path" - "testing" - "time" - - "github.com/fnproject/fn_go/client/call" - "github.com/fnproject/fn_go/models" -) - -func TestCallsMissingApp(t *testing.T) { - t.Parallel() - s := SetupHarness() - cfg := &call.GetAppsAppCallsParams{ - App: s.AppName, - Path: &s.RoutePath, - Context: s.Context, - } - _, err := s.Client.Call.GetAppsAppCalls(cfg) - if err == nil { - t.Errorf("Must fail with missing app error, but got %s", err) - } -} - -func TestCallsDummy(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - s.GivenRouteExists(t, s.AppName, s.BasicRoute()) - - cfg := &call.GetAppsAppCallsCallParams{ - Call: "dummy", - App: s.AppName, - Context: s.Context, - } - cfg.WithTimeout(time.Second * 60) - _, err := s.Client.Call.GetAppsAppCallsCall(cfg) - if err == nil { - t.Error("Must fail because `dummy` call does not exist.") - } - -} - -func TestGetExactCall(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - s.GivenRouteExists(t, s.AppName, s.BasicRoute()) - - u := url.URL{ - Scheme: "http", - Host: Host(), - } - u.Path = path.Join(u.Path, "r", s.AppName, s.RoutePath) - - callID := CallAsync(t, s.Context, u, &bytes.Buffer{}) - - cfg := &call.GetAppsAppCallsCallParams{ - Call: callID, - App: s.AppName, - Context: s.Context, - } - cfg.WithTimeout(time.Second * 60) - - retryErr := APICallWithRetry(t, 10, time.Second*2, func() (err error) { - _, err = s.Client.Call.GetAppsAppCallsCall(cfg) - return err - }) - - if retryErr != nil { - t.Error(retryErr.Error()) - } - -} diff --git a/test/fn-api-tests/config_cases.go b/test/fn-api-tests/config_cases.go deleted file mode 100644 index 59c6be37b..000000000 --- a/test/fn-api-tests/config_cases.go +++ /dev/null @@ -1,29 +0,0 @@ -package tests - -import "reflect" - -// common test cases around config for apps/routes - -var updateConfigCases = []struct { - name string - intialConfig map[string]string - change map[string]string - expected map[string]string -}{ - {"preserve existing config keys with nop", map[string]string{"key": "value1"}, map[string]string{}, map[string]string{"key": "value1"}}, - - {"preserve existing config keys with change", map[string]string{"key": "value1"}, map[string]string{"key": "value1"}, map[string]string{"key": "value1"}}, - - {"overwrite existing config keys", map[string]string{"key": "value1"}, map[string]string{"key": "value2"}, map[string]string{"key": "value2"}}, - - {"delete config key", map[string]string{"key": "value1"}, map[string]string{"key": ""}, map[string]string{}}, -} - -//ConfigEquivalent checks if two config objects are semantically equivalent (including nils) -func ConfigEquivalent(a map[string]string, b map[string]string) bool { - if len(a) == 0 && len(b) == 0 { - return true - } - return reflect.DeepEqual(a, b) - -} diff --git a/test/fn-api-tests/exec_test.go b/test/fn-api-tests/exec_test.go deleted file mode 100644 index 40884d13a..000000000 --- a/test/fn-api-tests/exec_test.go +++ /dev/null @@ -1,383 +0,0 @@ -package tests - -import ( - "bytes" - "context" - "encoding/json" - "io" - "net/url" - "path" - "strings" - "testing" - "time" - - "github.com/fnproject/fn_go/client/call" - "github.com/fnproject/fn_go/client/operations" - "github.com/fnproject/fn_go/models" -) - -func CallAsync(t *testing.T, ctx context.Context, u url.URL, content io.Reader) string { - output := &bytes.Buffer{} - _, err := CallFN(ctx, u.String(), content, output, "POST", []string{}) - if err != nil { - t.Errorf("Got unexpected error: %v", err) - } - - expectedOutput := "call_id" - if !strings.Contains(output.String(), expectedOutput) { - t.Errorf("Assertion error.\n\tExpected: %v\n\tActual: %v", expectedOutput, output.String()) - } - - type CallID struct { - CallID string `json:"call_id"` - } - - callID := &CallID{} - json.NewDecoder(output).Decode(callID) - - if callID.CallID == "" { - t.Errorf("`call_id` not suppose to be empty string") - } - t.Logf("Async execution call ID: %v", callID.CallID) - return callID.CallID -} - -func CallSync(t *testing.T, ctx context.Context, u url.URL, content io.Reader) string { - output := &bytes.Buffer{} - resp, err := CallFN(ctx, u.String(), content, output, "POST", []string{}) - if err != nil { - t.Errorf("Got unexpected error: %v", err) - } - - callId := resp.Header.Get("FN_CALL_ID") - if callId == "" { - t.Errorf("Assertion error.\n\tExpected call id header in response, got: %v", resp.Header) - } - - t.Logf("Sync execution call ID: %v", callId) - return callId -} - -func TestCanCallfunction(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - rt := s.BasicRoute() - rt.Type = "sync" - s.GivenRouteExists(t, s.AppName, rt) - - u := url.URL{ - Scheme: "http", - Host: Host(), - } - u.Path = path.Join(u.Path, "r", s.AppName, s.RoutePath) - - content := &bytes.Buffer{} - output := &bytes.Buffer{} - _, err := CallFN(s.Context, u.String(), content, output, "POST", []string{}) - if err != nil { - t.Errorf("Got unexpected error: %v", err) - } - expectedOutput := "Hello World!\n" - if !strings.Contains(expectedOutput, output.String()) { - t.Errorf("Assertion error.\n\tExpected: %v\n\tActual: %v", expectedOutput, output.String()) - } -} - -func TestCallOutputMatch(t *testing.T) { - t.Parallel() - s := SetupHarness() - s.GivenAppExists(t, &models.App{Name: s.AppName}) - rt := s.BasicRoute() - rt.Type = "sync" - s.GivenRouteExists(t, s.AppName, rt) - - u := url.URL{ - Scheme: "http", - Host: Host(), - } - u.Path = path.Join(u.Path, "r", s.AppName, s.RoutePath) - - content := &bytes.Buffer{} - json.NewEncoder(content).Encode(struct { - Name string - }{Name: "John"}) - output := &bytes.Buffer{} - _, err := CallFN(s.Context, u.String(), content, output, "POST", []string{}) - if err != nil { - t.Errorf("Got unexpected error: %v", err) - } - expectedOutput := "Hello John!\n" - if !strings.Contains(expectedOutput, output.String()) { - t.Errorf("Assertion error.\n\tExpected: %v\n\tActual: %v", expectedOutput, output.String()) - } -} - -func TestCanCallAsync(t *testing.T) { - newRouteType := "async" - t.Parallel() - - s := SetupHarness() - s.GivenAppExists(t, &models.App{Name: s.AppName}) - rt := s.BasicRoute() - rt.Type = "sync" - s.GivenRouteExists(t, s.AppName, rt) - - u := url.URL{ - Scheme: "http", - Host: Host(), - } - u.Path = path.Join(u.Path, "r", s.AppName, s.RoutePath) - - s.GivenRoutePatched(t, s.AppName, s.RoutePath, &models.Route{ - Type: newRouteType, - }) - - CallAsync(t, s.Context, u, &bytes.Buffer{}) -} - -func TestCanGetAsyncState(t *testing.T) { - newRouteType := "async" - t.Parallel() - s := SetupHarness() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - rt := s.BasicRoute() - rt.Type = "sync" - s.GivenRouteExists(t, s.AppName, rt) - - u := url.URL{ - Scheme: "http", - Host: Host(), - } - u.Path = path.Join(u.Path, "r", s.AppName, s.RoutePath) - - s.GivenRoutePatched(t, s.AppName, rt.Path, &models.Route{ - Type: newRouteType, - }) - - callID := CallAsync(t, s.Context, u, &bytes.Buffer{}) - cfg := &call.GetAppsAppCallsCallParams{ - Call: callID, - App: s.AppName, - Context: s.Context, - } - cfg.WithTimeout(time.Second * 60) - - retryErr := APICallWithRetry(t, 10, time.Second*2, func() (err error) { - _, err = s.Client.Call.GetAppsAppCallsCall(cfg) - return err - }) - - if retryErr != nil { - t.Error(retryErr.Error()) - } else { - callResponse, err := s.Client.Call.GetAppsAppCallsCall(cfg) - if err != nil { - switch err.(type) { - case *call.GetAppsAppCallsCallNotFound: - msg := err.(*call.GetAppsAppCallsCallNotFound).Payload.Error.Message - t.Errorf("Unexpected error occurred: %v.", msg) - } - } - callObject := callResponse.Payload.Call - - if callObject.ID != callID { - t.Errorf("Call object ID mismatch.\n\tExpected: %v\n\tActual:%v", callID, callObject.ID) - } - if callObject.Path != s.RoutePath { - t.Errorf("Call object route path mismatch.\n\tExpected: %v\n\tActual:%v", s.RoutePath, callObject.Path) - } - if callObject.Status != "success" { - t.Errorf("Call object status mismatch.\n\tExpected: %v\n\tActual:%v", "success", callObject.Status) - } - } -} - -func TestCanCauseTimeout(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - - rt := s.BasicRoute() - timeout := int32(10) - rt.Timeout = &timeout - rt.Type = "sync" - rt.Image = "funcy/timeout:0.0.1" - s.GivenRouteExists(t, s.AppName, rt) - - u := url.URL{ - Scheme: "http", - Host: Host(), - } - u.Path = path.Join(u.Path, "r", s.AppName, rt.Path) - - content := &bytes.Buffer{} - json.NewEncoder(content).Encode(struct { - Seconds int64 `json:"seconds"` - }{Seconds: 11}) - output := &bytes.Buffer{} - - resp, _ := CallFN(s.Context, u.String(), content, output, "POST", []string{}) - - if !strings.Contains(output.String(), "Timed out") { - t.Errorf("Must fail because of timeout, but got error message: %v", output.String()) - } - cfg := &call.GetAppsAppCallsCallParams{ - Call: resp.Header.Get("FN_CALL_ID"), - App: s.AppName, - Context: s.Context, - } - cfg.WithTimeout(time.Second * 60) - - retryErr := APICallWithRetry(t, 10, time.Second*2, func() (err error) { - _, err = s.Client.Call.GetAppsAppCallsCall(cfg) - return err - }) - - if retryErr != nil { - t.Error(retryErr.Error()) - } else { - callObj, err := s.Client.Call.GetAppsAppCallsCall(cfg) - if err != nil { - t.Errorf("Unexpected error: %s", err) - } - if !strings.Contains("timeout", callObj.Payload.Call.Status) { - t.Errorf("Call status mismatch.\n\tExpected: %v\n\tActual: %v", - "output", "callObj.Payload.Call.Status") - } - } -} - -func TestCallResponseHeadersMatch(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - rt := s.BasicRoute() - rt.Image = "denismakogon/os.environ" - rt.Type = "sync" - s.GivenRouteExists(t, s.AppName, rt) - - u := url.URL{ - Scheme: "http", - Host: Host(), - } - u.Path = path.Join(u.Path, "r", s.AppName, rt.Path) - content := &bytes.Buffer{} - output := &bytes.Buffer{} - CallFN(s.Context, u.String(), content, output, "POST", - []string{ - "ACCEPT: application/xml", - "ACCEPT: application/json; q=0.2", - }) - res := output.String() - if !strings.Contains("application/xml, application/json; q=0.2", res) { - t.Errorf("HEADER_ACCEPT='application/xml, application/json; q=0.2' "+ - "should be in output, have:%s\n", res) - } -} - -func TestCanWriteLogs(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - rt := s.BasicRoute() - rt.Path = "/log" - rt.Image = "funcy/log:0.0.1" - rt.Type = "sync" - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - s.GivenRouteExists(t, s.AppName, rt) - - u := url.URL{ - Scheme: "http", - Host: Host(), - } - u.Path = path.Join(u.Path, "r", s.AppName, rt.Path) - content := &bytes.Buffer{} - json.NewEncoder(content).Encode(struct { - Size int - }{Size: 20}) - - callID := CallSync(t, s.Context, u, content) - - cfg := &operations.GetAppsAppCallsCallLogParams{ - Call: callID, - App: s.AppName, - Context: s.Context, - } - - // TODO this test is redundant we have 3 tests for this? - retryErr := APICallWithRetry(t, 10, time.Second*2, func() (err error) { - _, err = s.Client.Operations.GetAppsAppCallsCallLog(cfg) - return err - }) - - if retryErr != nil { - t.Error(retryErr.Error()) - } else { - _, err := s.Client.Operations.GetAppsAppCallsCallLog(cfg) - if err != nil { - t.Error(err.Error()) - } - } -} - -func TestOversizedLog(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - rt := s.BasicRoute() - rt.Path = "/log" - rt.Image = "funcy/log:0.0.1" - rt.Type = "sync" - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - s.GivenRouteExists(t, s.AppName, rt) - - size := 1 * 1024 * 1024 * 1024 - u := url.URL{ - Scheme: "http", - Host: Host(), - } - u.Path = path.Join(u.Path, "r", s.AppName, rt.Path) - content := &bytes.Buffer{} - json.NewEncoder(content).Encode(struct { - Size int - }{Size: size}) //exceeding log by 1 symbol - - callID := CallSync(t, s.Context, u, content) - - cfg := &operations.GetAppsAppCallsCallLogParams{ - Call: callID, - App: s.AppName, - Context: s.Context, - } - - retryErr := APICallWithRetry(t, 10, time.Second*2, func() (err error) { - _, err = s.Client.Operations.GetAppsAppCallsCallLog(cfg) - return err - }) - - if retryErr != nil { - t.Error(retryErr.Error()) - } else { - logObj, err := s.Client.Operations.GetAppsAppCallsCallLog(cfg) - if err != nil { - t.Error(err.Error()) - } - log := logObj.Payload.Log.Log - if len(log) >= size { - t.Errorf("Log entry suppose to be truncated up to expected size %v, got %v", - size/1024, len(log)) - } - } -} diff --git a/test/fn-api-tests/fn/formats/json/go/Dockerfile b/test/fn-api-tests/fn/formats/json/go/Dockerfile deleted file mode 100644 index 1c1b324fd..000000000 --- a/test/fn-api-tests/fn/formats/json/go/Dockerfile +++ /dev/null @@ -1,8 +0,0 @@ -FROM fnproject/go:dev as build-stage -WORKDIR /function -ADD . /src -RUN cd /src && go build -o func -FROM fnproject/go -WORKDIR /function -COPY --from=build-stage /src/func /function/ -ENTRYPOINT ["./func"] diff --git a/test/fn-api-tests/fn/formats/json/go/func.go b/test/fn-api-tests/fn/formats/json/go/func.go deleted file mode 100644 index f61222d2f..000000000 --- a/test/fn-api-tests/fn/formats/json/go/func.go +++ /dev/null @@ -1,68 +0,0 @@ -package main - -import ( - "bytes" - "encoding/json" - "fmt" - "log" - "net/http" - "os" - "strconv" -) - -type Person struct { - Name string `json:"name"` -} - -type JSON struct { - Headers http.Header `json:"headers"` - Body string `json:"body,omitempty"` - StatusCode int `json:"status,omitempty"` -} - -func main() { - - stdin := json.NewDecoder(os.Stdin) - stdout := json.NewEncoder(os.Stdout) - stderr := json.NewEncoder(os.Stderr) - for { - in := &JSON{} - - err := stdin.Decode(in) - if err != nil { - log.Fatalf("Unable to decode incoming data: %s", err.Error()) - fmt.Fprintf(os.Stderr, err.Error()) - } - person := Person{} - stderr.Encode(in.Body) - if len(in.Body) != 0 { - if err := json.NewDecoder(bytes.NewReader([]byte(in.Body))).Decode(&person); err != nil { - log.Fatalf("Unable to decode Person object data: %s", err.Error()) - fmt.Fprintf(os.Stderr, err.Error()) - } - } - if person.Name == "" { - person.Name = "World" - } - - mapResult := map[string]string{"message": fmt.Sprintf("Hello %s", person.Name)} - b, err := json.Marshal(mapResult) - if err != nil { - log.Fatalf("Unable to marshal JSON response body: %s", err.Error()) - fmt.Fprintf(os.Stderr, err.Error()) - } - h := http.Header{} - h.Set("Content-Type", "application/json") - h.Set("Content-Length", strconv.Itoa(len(b))) - out := &JSON{ - StatusCode: http.StatusOK, - Body: string(b), - Headers: h, - } - stderr.Encode(out) - if err := stdout.Encode(out); err != nil { - log.Fatalf("Unable to encode JSON response: %s", err.Error()) - fmt.Fprintf(os.Stderr, err.Error()) - } - } -} diff --git a/test/fn-api-tests/fn/log/Dockerfile b/test/fn-api-tests/fn/log/Dockerfile deleted file mode 100644 index 1c1b324fd..000000000 --- a/test/fn-api-tests/fn/log/Dockerfile +++ /dev/null @@ -1,8 +0,0 @@ -FROM fnproject/go:dev as build-stage -WORKDIR /function -ADD . /src -RUN cd /src && go build -o func -FROM fnproject/go -WORKDIR /function -COPY --from=build-stage /src/func /function/ -ENTRYPOINT ["./func"] diff --git a/test/fn-api-tests/fn/log/func.yaml b/test/fn-api-tests/fn/log/func.yaml deleted file mode 100644 index 2149508f9..000000000 --- a/test/fn-api-tests/fn/log/func.yaml +++ /dev/null @@ -1,5 +0,0 @@ -name: funcy/log -version: 0.0.1 -runtime: go -entrypoint: ./func -path: /log diff --git a/test/fn-api-tests/fn/log/main.go b/test/fn-api-tests/fn/log/main.go deleted file mode 100644 index b4737f6c4..000000000 --- a/test/fn-api-tests/fn/log/main.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "math/rand" - "os" -) - -const lBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" - -type OutputSize struct { - Size int `json:"size"` -} - -func RandStringBytes(n int) string { - b := make([]byte, n) - for i := range b { - b[i] = lBytes[rand.Intn(len(lBytes))] - } - return string(b) -} - -func main() { - out := &OutputSize{} - json.NewDecoder(os.Stdin).Decode(out) - fmt.Fprintln(os.Stderr, RandStringBytes(out.Size)) -} diff --git a/test/fn-api-tests/fn/log/sample.payload.json b/test/fn-api-tests/fn/log/sample.payload.json deleted file mode 100644 index 8f2e36ac3..000000000 --- a/test/fn-api-tests/fn/log/sample.payload.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "size": 1048576 -} diff --git a/test/fn-api-tests/fn/timeout/Dockerfile b/test/fn-api-tests/fn/timeout/Dockerfile deleted file mode 100644 index 1c1b324fd..000000000 --- a/test/fn-api-tests/fn/timeout/Dockerfile +++ /dev/null @@ -1,8 +0,0 @@ -FROM fnproject/go:dev as build-stage -WORKDIR /function -ADD . /src -RUN cd /src && go build -o func -FROM fnproject/go -WORKDIR /function -COPY --from=build-stage /src/func /function/ -ENTRYPOINT ["./func"] diff --git a/test/fn-api-tests/fn/timeout/func.yaml b/test/fn-api-tests/fn/timeout/func.yaml deleted file mode 100644 index a2c43df85..000000000 --- a/test/fn-api-tests/fn/timeout/func.yaml +++ /dev/null @@ -1,5 +0,0 @@ -name: funcy/timeout -version: 0.0.1 -runtime: go -entrypoint: ./func -path: /timeouter diff --git a/test/fn-api-tests/fn/timeout/main.go b/test/fn-api-tests/fn/timeout/main.go deleted file mode 100644 index 747006b5f..000000000 --- a/test/fn-api-tests/fn/timeout/main.go +++ /dev/null @@ -1,9 +0,0 @@ -package main - -import ( - "time" -) - -func main() { - time.Sleep(32 * time.Second) -} diff --git a/test/fn-api-tests/formats_test.go b/test/fn-api-tests/formats_test.go deleted file mode 100644 index 21a4ec688..000000000 --- a/test/fn-api-tests/formats_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package tests - -import ( - "bytes" - "encoding/json" - "github.com/fnproject/fn_go/models" - "net/url" - "path" - "strconv" - "strings" - "testing" -) - -type JSONResponse struct { - Message string `json:"message"` -} - -func TestFnJSONFormats(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - // TODO(treeder): put image in fnproject @ dockerhub - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - rt := s.BasicRoute() - rt.Image = "denismakogon/test-hot-json-go:0.0.1" - rt.Format = "json" - s.GivenRouteExists(t, s.AppName, rt) - - u := url.URL{ - Scheme: "http", - Host: Host(), - } - u.Path = path.Join(u.Path, "r", s.AppName, s.RoutePath) - - b, _ := json.Marshal(&struct { - Name string `json:"name"` - }{ - Name: "Jimmy", - }) - content := bytes.NewBuffer(b) - output := &bytes.Buffer{} - resp, err := CallFN(s.Context, u.String(), content, output, "POST", []string{}) - if err != nil { - t.Errorf("Got unexpected error: %v", err) - } - - msg := &JSONResponse{} - json.Unmarshal(output.Bytes(), msg) - expectedOutput := "Hello Jimmy" - if !strings.Contains(expectedOutput, msg.Message) { - t.Errorf("Assertion error.\n\tExpected: %v\n\tActual: %v", expectedOutput, output.String()) - } - - expectedHeaderNames := []string{"Content-Type", "Content-Length"} - expectedHeaderValues := []string{"application/json; charset=utf-8", strconv.Itoa(output.Len())} - for i, name := range expectedHeaderNames { - actual := resp.Header.Get(name) - expected := expectedHeaderValues[i] - if !strings.Contains(expected, actual) { - t.Errorf("HTTP header assertion error for %v."+ - "\n\tExpected: %v\n\tActual: %v", name, expected, actual) - } - } - -} diff --git a/test/fn-api-tests/init_test.go b/test/fn-api-tests/init_test.go deleted file mode 100644 index 4a88946b9..000000000 --- a/test/fn-api-tests/init_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package tests - -import ( - "context" - "fmt" - "log" - "os" - "testing" - "time" - - "github.com/fnproject/fn/api/server" - _ "github.com/fnproject/fn/api/server/defaultexts" -) - -func stopServer(done chan struct{}, stop func()) { - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) - defer cancel() - - stop() - - select { - case <-done: - case <-ctx.Done(): - log.Panic("Server Cleanup failed, timeout") - } -} - -func startServer() (chan struct{}, func()) { - - log.Print("Starting server") - - ctx, srvCancel := context.WithCancel(context.Background()) - srvDone := make(chan struct{}) - - timeString := time.Now().Format("2006_01_02_15_04_05") - dbURL := os.Getenv(server.EnvDBURL) - tmpDir := os.TempDir() - tmpMq := fmt.Sprintf("%s/fn_integration_test_%s_worker_mq.db", tmpDir, timeString) - tmpDb := fmt.Sprintf("%s/fn_integration_test_%s_fn.db", tmpDir, timeString) - mqURL := fmt.Sprintf("bolt://%s", tmpMq) - if dbURL == "" { - dbURL = fmt.Sprintf("sqlite3://%s", tmpDb) - } - - srv := server.New(ctx, - server.WithLogLevel(getEnv(server.EnvLogLevel, server.DefaultLogLevel)), - server.WithDBURL(dbURL), - server.WithMQURL(mqURL), - server.WithFullAgent(), - ) - - go func() { - srv.Start(ctx) - log.Print("Stopped server") - os.Remove(tmpMq) - os.Remove(tmpDb) - close(srvDone) - }() - - startCtx, startCancel := context.WithDeadline(ctx, time.Now().Add(time.Duration(10)*time.Second)) - defer startCancel() - for { - err := checkServer(startCtx) - if err == nil { - break - } - select { - case <-time.After(time.Second * 1): - case <-ctx.Done(): - } - if ctx.Err() != nil { - log.Panic("Server check failed, timeout") - } - } - - return srvDone, srvCancel -} - -func TestMain(m *testing.M) { - done, cancel := startServer() - // call flag.Parse() here if TestMain uses flags - result := m.Run() - stopServer(done, cancel) - - if result == 0 { - fmt.Fprintln(os.Stdout, "😀 👍 🎗") - } - os.Exit(result) -} diff --git a/test/fn-api-tests/routes_api.go b/test/fn-api-tests/routes_api.go deleted file mode 100644 index 3e208ad5a..000000000 --- a/test/fn-api-tests/routes_api.go +++ /dev/null @@ -1,124 +0,0 @@ -package tests - -import ( - "testing" - - "github.com/fnproject/fn_go/client/routes" - "github.com/fnproject/fn_go/models" -) - -func AssertRouteMatches(t *testing.T, expected *models.Route, got *models.Route) { - - if expected.Path != got.Path { - t.Errorf("Route path mismatch. Expected: %v. Actual: %v", expected.Path, got.Path) - } - if expected.Image != got.Image { - t.Errorf("Route image mismatch. Expected: %v. Actual: %v", expected.Image, got.Image) - } - if expected.Image != got.Image { - t.Errorf("Route type mismatch. Expected: %v. Actual: %v", expected.Image, got.Image) - } - if expected.Format != got.Format { - t.Errorf("Route format mismatch. Expected: %v. Actual: %v", expected.Format, got.Format) - } - -} - -// PostRoute Creates a route and deletes the corresponding app (if created) on teardown -func (s *TestHarness) PostRoute(appName string, route *models.Route) (*routes.PostAppsAppRoutesOK, error) { - cfg := &routes.PostAppsAppRoutesParams{ - App: appName, - Body: &models.RouteWrapper{ - Route: route, - }, - Context: s.Context, - } - ok, err := s.Client.Routes.PostAppsAppRoutes(cfg) - - if err == nil { - s.createdApps[appName] = true - } - return ok, err - -} - -func (s *TestHarness) BasicRoute() *models.Route { - return &models.Route{ - Format: s.Format, - Path: s.RoutePath, - Image: s.Image, - Type: s.RouteType, - Timeout: &s.Timeout, - IDLETimeout: &s.IdleTimeout, - } -} - -//GivenRouteExists creates a route using the specified arguments, failing the test if the creation fails, this tears down any apps that are created when the test is complete -func (s *TestHarness) GivenRouteExists(t *testing.T, appName string, route *models.Route) { - _, err := s.PostRoute(appName, route) - if err != nil { - t.Fatalf("Expected route to be created, got %v", err) - } - -} - -//RouteMustExist checks that a route exists, failing the test if it doesn't, returns the route -func (s *TestHarness) RouteMustExist(t *testing.T, appName string, routePath string) *models.Route { - cfg := &routes.GetAppsAppRoutesRouteParams{ - App: appName, - Route: routePath[1:], - Context: s.Context, - } - - routeResponse, err := s.Client.Routes.GetAppsAppRoutesRoute(cfg) - if err != nil { - t.Fatalf("Expected route %s %s to exist but got %v", appName, routePath, err) - } - return routeResponse.Payload.Route -} - -//GivenRoutePatched applies a patch to a route, failing the test if this fails. -func (s *TestHarness) GivenRoutePatched(t *testing.T, appName, routeName string, rt *models.Route) { - - _, err := s.Client.Routes.PatchAppsAppRoutesRoute(&routes.PatchAppsAppRoutesRouteParams{ - App: appName, - Route: routeName, - Context: s.Context, - Body: &models.RouteWrapper{ - Route: rt, - }, - }) - - if err != nil { - t.Fatalf("Failed to patch route %s %s : %v", appName, routeName, err) - } -} - -func assertContainsRoute(routeModels []*models.Route, expectedRoute string) bool { - for _, r := range routeModels { - if r.Path == expectedRoute { - return true - } - } - return false -} - -//PutRoute creates a route via PUT, tearing down any apps that are created when the test is complete -func (s *TestHarness) PutRoute(appName string, routePath string, route *models.Route) (*routes.PutAppsAppRoutesRouteOK, error) { - cfg := &routes.PutAppsAppRoutesRouteParams{ - App: appName, - Context: s.Context, - Route: routePath, - Body: &models.RouteWrapper{ - Route: route, - }, - } - - resp, err := s.Client.Routes.PutAppsAppRoutesRoute(cfg) - - if err == nil { - s.createdApps[appName] = true - } - - return resp, err -} diff --git a/test/fn-api-tests/routes_test.go b/test/fn-api-tests/routes_test.go deleted file mode 100644 index 9afd2a320..000000000 --- a/test/fn-api-tests/routes_test.go +++ /dev/null @@ -1,502 +0,0 @@ -package tests - -import ( - "testing" - - "reflect" - - "github.com/fnproject/fn/api/id" - "github.com/fnproject/fn_go/client/apps" - "github.com/fnproject/fn_go/client/routes" - "github.com/fnproject/fn_go/models" -) - -func TestShouldRejectEmptyRouteType(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - - _, err := s.PostRoute(s.AppName, &models.Route{ - Path: s.RoutePath, - Image: s.Image, - Type: "v", - Format: s.Format, - }) - - if err == nil { - t.Errorf("Should fail with Invalid route Type.") - } -} - -func TestCanCreateRoute(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - _, err := s.PostRoute(s.AppName, &models.Route{ - Path: s.RoutePath, - Image: s.Image, - Format: s.Format, - }) - - if err != nil { - t.Errorf("expected route success, got %v", err) - } - // TODO validate route returned matches request -} - -func TestListRoutes(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - s.GivenRouteExists(t, s.AppName, s.BasicRoute()) - - cfg := &routes.GetAppsAppRoutesParams{ - App: s.AppName, - Context: s.Context, - } - - routesResponse, err := s.Client.Routes.GetAppsAppRoutes(cfg) - - if err != nil { - t.Fatalf("Expecting list routes to be successful, got %v", err) - } - if !assertContainsRoute(routesResponse.Payload.Routes, s.RoutePath) { - t.Errorf("Unable to find corresponding route `%v` in list", s.RoutePath) - } -} - -func TestInspectRoute(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - newRt := s.BasicRoute() - s.GivenRouteExists(t, s.AppName, newRt) - - resp, err := s.Client.Routes.GetAppsAppRoutesRoute(&routes.GetAppsAppRoutesRouteParams{ - App: s.AppName, - Route: newRt.Path[1:], - Context: s.Context, - }) - - if err != nil { - t.Fatalf("Failed to get route %s, %v", s.RoutePath, err) - } - - gotRt := resp.Payload.Route - - AssertRouteMatches(t, newRt, gotRt) - -} - -var validRouteUpdates = []struct { - name string - update *models.Route - extract func(*models.Route) interface{} -}{ - {"route type (sync)", &models.Route{Type: "sync"}, func(m *models.Route) interface{} { return m.Type }}, - {"route type (async)", &models.Route{Type: "async"}, func(m *models.Route) interface{} { return m.Type }}, - {"format (json)", &models.Route{Format: "json"}, func(m *models.Route) interface{} { return m.Format }}, - {"format (default)", &models.Route{Format: "default"}, func(m *models.Route) interface{} { return m.Format }}, - // ... -} - -func TestCanUpdateRouteAttributes(t *testing.T) { - t.Parallel() - - for _, tci := range validRouteUpdates { - tc := tci - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - s.GivenRouteExists(t, s.AppName, s.BasicRoute()) - - routeResp, err := s.Client.Routes.PatchAppsAppRoutesRoute( - &routes.PatchAppsAppRoutesRouteParams{ - App: s.AppName, - Context: s.Context, - Route: s.RoutePath, - Body: &models.RouteWrapper{ - Route: tc.update, - }, - }, - ) - if err != nil { - t.Fatalf("Failed to patch route, got %v", err) - } - - got := tc.extract(routeResp.Payload.Route) - change := tc.extract(tc.update) - if !reflect.DeepEqual(got, change) { - t.Errorf("Expected value in response tobe %v but was %v", change, got) - } - }) - } - -} - -func TestRoutePatchConfig(t *testing.T) { - t.Parallel() - for _, tci := range updateConfigCases { - tc := tci - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - s.GivenAppExists(t, &models.App{Name: s.AppName}) - route := s.BasicRoute() - route.Config = tc.intialConfig - - s.GivenRouteExists(t, s.AppName, route) - - routeResp, err := s.Client.Routes.PatchAppsAppRoutesRoute( - &routes.PatchAppsAppRoutesRouteParams{ - App: s.AppName, - Route: s.RoutePath, - Body: &models.RouteWrapper{ - Route: &models.Route{ - Config: tc.change, - }, - }, - Context: s.Context, - }, - ) - - if err != nil { - t.Fatalf("Failed to patch route, got %v", err) - } - actual := routeResp.Payload.Route.Config - if !ConfigEquivalent(actual, tc.expected) { - t.Errorf("Expected config : %v after update, got %v", tc.expected, actual) - } - - }) - } - -} - -func TestSetRouteAnnotationsOnCreate(t *testing.T) { - t.Parallel() - for _, tci := range createAnnotationsValidCases { - // iterator mutation meets parallelism... pfft - tc := tci - t.Run("valid_"+tc.name, func(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{ - Name: s.AppName, - }) - rt := s.BasicRoute() - rt.Annotations = tc.annotations - - route, err := s.Client.Routes.PostAppsAppRoutes(&routes.PostAppsAppRoutesParams{ - App: s.AppName, - Context: s.Context, - Body: &models.RouteWrapper{ - Route: rt, - }, - }) - - if err != nil { - t.Fatalf("Failed to create route with valid annotations %v got error %v", tc.annotations, err) - } - - gotMd := route.Payload.Route.Annotations - if !AnnotationsEquivalent(gotMd, tc.annotations) { - t.Errorf("Returned annotations %v does not match set annotations %v", gotMd, tc.annotations) - } - - getRoute := s.RouteMustExist(t, s.AppName, s.RoutePath) - - if !AnnotationsEquivalent(getRoute.Annotations, tc.annotations) { - t.Errorf("GET annotations '%v' does not match set annotations %v", getRoute.Annotations, tc.annotations) - } - - }) - } - - for _, tci := range createAnnotationsErrorCases { - // iterator mutation meets parallelism... pfft - tc := tci - t.Run("invalid_"+tc.name, func(ti *testing.T) { - ti.Parallel() - s := SetupHarness() - defer s.Cleanup() - - _, err := s.PostApp(&models.App{ - Name: s.AppName, - Annotations: tc.annotations, - }) - - if err == nil { - t.Fatalf("Created app with invalid annotations %v but expected error", tc.annotations) - } - - if _, ok := err.(*apps.PostAppsBadRequest); !ok { - t.Errorf("Expecting bad request for invalid annotations, got %v", err) - } - - }) - } -} - -func TestSetRouteMetadataOnPatch(t *testing.T) { - t.Parallel() - - for _, tci := range updateAnnotationsValidCases { - // iterator mutation meets parallelism... pfft - tc := tci - t.Run("valid_"+tc.name, func(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - rt := s.BasicRoute() - rt.Annotations = tc.initial - s.GivenRouteExists(t, s.AppName, rt) - - res, err := s.Client.Routes.PatchAppsAppRoutesRoute(&routes.PatchAppsAppRoutesRouteParams{ - App: s.AppName, - Route: s.RoutePath[1:], - Context: s.Context, - Body: &models.RouteWrapper{ - Route: &models.Route{ - Annotations: tc.change, - }, - }, - }) - - if err != nil { - t.Fatalf("Failed to patch annotations with %v on route: %v", tc.change, err) - } - - gotMd := res.Payload.Route.Annotations - if !AnnotationsEquivalent(gotMd, tc.expected) { - t.Errorf("Returned annotations %v does not match set annotations %v", gotMd, tc.expected) - } - - getRoute := s.RouteMustExist(t, s.AppName, s.RoutePath) - - if !AnnotationsEquivalent(getRoute.Annotations, tc.expected) { - t.Errorf("GET annotations '%v' does not match set annotations %v", getRoute.Annotations, tc.expected) - } - }) - } - - for _, tci := range updateAnnotationsErrorCases { - // iterator mutation meets parallelism... pfft - tc := tci - t.Run("invalid_"+tc.name, func(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{ - Name: s.AppName, - }) - rt := s.BasicRoute() - rt.Annotations = tc.initial - s.GivenRouteExists(t, s.AppName, rt) - - _, err := s.Client.Routes.PatchAppsAppRoutesRoute(&routes.PatchAppsAppRoutesRouteParams{ - App: s.AppName, - Route: s.RoutePath[1:], - Context: s.Context, - Body: &models.RouteWrapper{ - Route: &models.Route{ - Annotations: tc.change, - }, - }, - }) - - if err == nil { - t.Errorf("patched route with invalid annotations %v but expected error", tc.change) - } - if _, ok := err.(*routes.PatchAppsAppRoutesRouteBadRequest); !ok { - t.Errorf("Expecting bad request for invalid annotations, got %v", err) - } - - }) - } -} - -func TestCantUpdateRoutePath(t *testing.T) { - - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - s.GivenRouteExists(t, s.AppName, s.BasicRoute()) - - _, err := s.Client.Routes.PatchAppsAppRoutesRoute( - &routes.PatchAppsAppRoutesRouteParams{ - App: s.AppName, - Route: s.RoutePath, - Body: &models.RouteWrapper{ - Route: &models.Route{ - Path: id.New().String(), - }, - }, - }) - if err == nil { - t.Fatalf("Expected error when patching route") - } - if _, ok := err.(*routes.PatchAppsAppRoutesRouteBadRequest); ok { - t.Errorf("Error should be bad request when updating route path ") - } - -} - -func TestRoutePreventsDuplicate(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - s.GivenRouteExists(t, s.AppName, s.BasicRoute()) - - _, err := s.PostRoute(s.AppName, s.BasicRoute()) - - if err == nil { - t.Errorf("Route duplicate error should appear, but it didn't") - } - if _, ok := err.(*routes.PostAppsAppRoutesConflict); !ok { - t.Errorf("Error should be a conflict when creating a new route, got %v", err) - } -} - -func TestCanDeleteRoute(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - s.GivenRouteExists(t, s.AppName, s.BasicRoute()) - - _, err := s.Client.Routes.DeleteAppsAppRoutesRoute(&routes.DeleteAppsAppRoutesRouteParams{ - App: s.AppName, - Route: s.RoutePath, - Context: s.Context, - }) - - if err != nil { - t.Errorf("Expected success when deleting existing route, got %v", err) - } -} - -func TestCantDeleteMissingRoute(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - - _, err := s.Client.Routes.DeleteAppsAppRoutesRoute(&routes.DeleteAppsAppRoutesRouteParams{ - App: s.AppName, - Route: s.RoutePath, - Context: s.Context, - }) - - if err == nil { - t.Fatalf("Expected error when deleting non-existing route, got none") - } - - if _, ok := err.(*routes.DeleteAppsAppRoutesRouteNotFound); !ok { - t.Fatalf("Expected not-found when deleting non-existing route, got %v", err) - - } -} - -func TestPutRouteCreatesNewApp(t *testing.T) { - t.Parallel() - s := SetupHarness() - defer s.Cleanup() - - _, err := s.PutRoute(s.AppName, s.RoutePath, s.BasicRoute()) - - if err != nil { - t.Fatalf("Expected new route to be created, got %v", err) - } - - s.AppMustExist(t, s.AppName) - s.RouteMustExist(t, s.AppName, s.RoutePath) - -} - -func TestPutRouteToExistingApp(t *testing.T) { - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - _, err := s.PutRoute(s.AppName, s.RoutePath, s.BasicRoute()) - if err != nil { - t.Fatalf("Failed to create route, got error %v", err) - } - s.AppMustExist(t, s.AppName) - s.RouteMustExist(t, s.AppName, s.RoutePath) -} - -func TestPutRouteUpdatesRoute(t *testing.T) { - newRouteType := "sync" - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - s.GivenRouteExists(t, s.AppName, s.BasicRoute()) - - changed := s.BasicRoute() - changed.Type = newRouteType - - updatedRoute, err := s.PutRoute(s.AppName, s.RoutePath, changed) - - if err != nil { - t.Fatalf("Failed to update route, got %v", err) - } - got := updatedRoute.Payload.Route.Type - if got != newRouteType { - t.Errorf("expected type to be %v after update, got %v", newRouteType, got) - } -} - -func TestPutIsIdempotentForHeaders(t *testing.T) { - s := SetupHarness() - defer s.Cleanup() - - s.GivenAppExists(t, &models.App{Name: s.AppName}) - - routeHeaders := map[string][]string{} - routeHeaders["A"] = []string{"a"} - routeHeaders["B"] = []string{"b"} - - r1 := s.BasicRoute() - r1.Headers = routeHeaders - - updatedRoute1, err := s.PutRoute(s.AppName, s.RoutePath, r1) - - if err != nil { - t.Fatalf("Failed to update route, got %v", err) - } - if firstMatches := reflect.DeepEqual(routeHeaders, updatedRoute1.Payload.Route.Headers); !firstMatches { - t.Errorf("Route headers should remain the same after multiple deploys with exact the same parameters '%v' != '%v'", routeHeaders, updatedRoute1.Payload.Route.Headers) - } - - updatedRoute2, err := s.PutRoute(s.AppName, s.RoutePath, r1) - - if bothmatch := reflect.DeepEqual(updatedRoute1.Payload.Route.Headers, updatedRoute2.Payload.Route.Headers); !bothmatch { - t.Error("Route headers should remain the same after multiple deploys with exact the same parameters") - } -} diff --git a/test/fn-api-tests/utils.go b/test/fn-api-tests/utils.go deleted file mode 100644 index 48b9da12d..000000000 --- a/test/fn-api-tests/utils.go +++ /dev/null @@ -1,201 +0,0 @@ -package tests - -import ( - "context" - "fmt" - "io" - "log" - "math/rand" - "net/http" - "net/url" - "os" - "strings" - "testing" - "time" - - "github.com/fnproject/fn_go/client" - httptransport "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" -) - -const lBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" - -func GetAPIURL() (string, *url.URL) { - apiURL := getEnv("FN_API_URL", "http://localhost:8080") - u, err := url.Parse(apiURL) - if err != nil { - log.Fatalf("Couldn't parse API URL: %s error: %s", apiURL, err) - } - return apiURL, u -} - -func Host() string { - _, u := GetAPIURL() - return u.Host -} - -func APIClient() *client.Fn { - transport := httptransport.New(Host(), "/v1", []string{"http"}) - if os.Getenv("FN_TOKEN") != "" { - transport.DefaultAuthentication = httptransport.BearerToken(os.Getenv("FN_TOKEN")) - } - - // create the API client, with the transport - return client.New(transport, strfmt.Default) -} - -func checkServer(ctx context.Context) error { - if ctx.Err() != nil { - log.Print("Server check failed, timeout") - return ctx.Err() - } - - apiURL, _ := GetAPIURL() - - client := &http.Client{} - req, err := http.NewRequest("GET", apiURL+"/version", nil) - if err != nil { - log.Panicf("Server check new request failed: %s", err) - } - - req = req.WithContext(ctx) - _, err = client.Do(req) - if err != nil { - log.Printf("Server is not up... err: %s", err) - return err - } - return ctx.Err() -} - -func getEnv(key, fallback string) string { - if value, ok := os.LookupEnv(key); ok { - return value - } - return fallback -} - -// TestHarness provides context and pre-configured clients to an individual test, it has some helper functions to create Apps and Routes that mirror the underlying client operations and clean them up after the test is complete -// This is not goroutine safe and each test case should use its own harness. -type TestHarness struct { - Context context.Context - Cancel func() - Client *client.Fn - AppName string - RoutePath string - Image string - RouteType string - Format string - Memory uint64 - Timeout int32 - IdleTimeout int32 - RouteConfig map[string]string - RouteHeaders map[string][]string - - createdApps map[string]bool -} - -func RandStringBytes(n int) string { - b := make([]byte, n) - for i := range b { - b[i] = lBytes[rand.Intn(len(lBytes))] - } - return strings.ToLower(string(b)) -} - -// SetupHarness creates a test harness for a test case - this picks up external options and -func SetupHarness() *TestHarness { - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) - - ss := &TestHarness{ - Context: ctx, - Cancel: cancel, - Client: APIClient(), - AppName: "fnintegrationtestapp" + RandStringBytes(10), - RoutePath: "/fnintegrationtestroute" + RandStringBytes(10), - Image: "fnproject/hello", - Format: "default", - RouteType: "async", - RouteConfig: map[string]string{}, - RouteHeaders: map[string][]string{}, - Memory: uint64(256), - Timeout: int32(30), - IdleTimeout: int32(30), - createdApps: make(map[string]bool), - } - return ss -} - -func (s *TestHarness) Cleanup() { - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) - defer cancel() - - //for _,ar := range s.createdRoutes { - // deleteRoute(ctx, s.Client, ar.appName, ar.routeName) - //} - - for app, _ := range s.createdApps { - safeDeleteApp(ctx, s.Client, app) - } - - s.Cancel() -} - -func EnvAsHeader(req *http.Request, selectedEnv []string) { - detectedEnv := os.Environ() - if len(selectedEnv) > 0 { - detectedEnv = selectedEnv - } - - for _, e := range detectedEnv { - kv := strings.Split(e, "=") - name := kv[0] - req.Header.Set(name, os.Getenv(name)) - } -} - -func CallFN(ctx context.Context, u string, content io.Reader, output io.Writer, method string, env []string) (*http.Response, error) { - if method == "" { - if content == nil { - method = "GET" - } else { - method = "POST" - } - } - - req, err := http.NewRequest(method, u, content) - if err != nil { - return nil, fmt.Errorf("error running route: %s", err) - } - req.Header.Set("Content-Type", "application/json") - req = req.WithContext(ctx) - - if len(env) > 0 { - EnvAsHeader(req, env) - } - - resp, err := http.DefaultClient.Do(req) - if err != nil { - return nil, fmt.Errorf("error running route: %s", err) - } - - io.Copy(output, resp.Body) - - return resp, nil -} - -func init() { - rand.Seed(time.Now().UnixNano()) -} - -func APICallWithRetry(t *testing.T, attempts int, sleep time.Duration, callback func() error) (err error) { - for i := 0; i < attempts; i++ { - err = callback() - if err == nil { - t.Log("Exiting retry loop, API call was successful") - return nil - } - t.Logf("[%v] - Retrying API call after unsuccessful attempt with error: %v", i, err.Error()) - time.Sleep(sleep) - } - return err -} diff --git a/test/fn-system-tests/exec_test.go b/test/fn-system-tests/exec_test.go index 8a015a768..48142717d 100644 --- a/test/fn-system-tests/exec_test.go +++ b/test/fn-system-tests/exec_test.go @@ -6,6 +6,8 @@ import ( "encoding/json" "errors" "fmt" + "io" + "log" "net/http" "net/url" "path" @@ -13,8 +15,7 @@ import ( "testing" "time" - apiutils "github.com/fnproject/fn/test/fn-api-tests" - sdkmodels "github.com/fnproject/fn_go/models" + "github.com/fnproject/fn/api/models" ) // See fn-test-utils for json response @@ -64,17 +65,9 @@ func getConfigContent(key string, respBytes []byte) (string, error) { } func TestCanExecuteFunction(t *testing.T) { - s := apiutils.SetupHarness() - s.GivenAppExists(t, &sdkmodels.App{Name: s.AppName}) - defer s.Cleanup() - - rt := s.BasicRoute() - rt.Image = "fnproject/fn-test-utils" - rt.Format = "json" - rt.Memory = 64 - rt.Type = "sync" - - s.GivenRouteExists(t, s.AppName, rt) + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + rt := ensureRoute(t) lb, err := LB() if err != nil { @@ -84,13 +77,13 @@ func TestCanExecuteFunction(t *testing.T) { Scheme: "http", Host: lb, } - u.Path = path.Join(u.Path, "r", s.AppName, s.RoutePath) + u.Path = path.Join(u.Path, "r", appName, rt.Path) body := `{"echoContent": "HelloWorld", "sleepTime": 0, "isDebug": true}` content := bytes.NewBuffer([]byte(body)) output := &bytes.Buffer{} - resp, err := apiutils.CallFN(s.Context, u.String(), content, output, "POST", []string{}) + resp, err := callFN(ctx, u.String(), content, output, "POST") if err != nil { t.Fatalf("Got unexpected error: %v", err) } @@ -119,17 +112,9 @@ func TestCanExecuteFunction(t *testing.T) { } func TestCanExecuteBigOutput(t *testing.T) { - s := apiutils.SetupHarness() - s.GivenAppExists(t, &sdkmodels.App{Name: s.AppName}) - defer s.Cleanup() - - rt := s.BasicRoute() - rt.Image = "fnproject/fn-test-utils" - rt.Format = "json" - rt.Memory = 64 - rt.Type = "sync" - - s.GivenRouteExists(t, s.AppName, rt) + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + rt := ensureRoute(t) lb, err := LB() if err != nil { @@ -139,14 +124,14 @@ func TestCanExecuteBigOutput(t *testing.T) { Scheme: "http", Host: lb, } - u.Path = path.Join(u.Path, "r", s.AppName, s.RoutePath) + u.Path = path.Join(u.Path, "r", appName, rt.Path) // Approx 5.3MB output body := `{"echoContent": "HelloWorld", "sleepTime": 0, "isDebug": true, "trailerRepeat": 410000}` content := bytes.NewBuffer([]byte(body)) output := &bytes.Buffer{} - resp, err := apiutils.CallFN(s.Context, u.String(), content, output, "POST", []string{}) + resp, err := callFN(ctx, u.String(), content, output, "POST") if err != nil { t.Fatalf("Got unexpected error: %v", err) } @@ -164,17 +149,9 @@ func TestCanExecuteBigOutput(t *testing.T) { } func TestCanExecuteTooBigOutput(t *testing.T) { - s := apiutils.SetupHarness() - s.GivenAppExists(t, &sdkmodels.App{Name: s.AppName}) - defer s.Cleanup() - - rt := s.BasicRoute() - rt.Image = "fnproject/fn-test-utils" - rt.Format = "json" - rt.Memory = 64 - rt.Type = "sync" - - s.GivenRouteExists(t, s.AppName, rt) + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + rt := ensureRoute(t) lb, err := LB() if err != nil { @@ -184,14 +161,14 @@ func TestCanExecuteTooBigOutput(t *testing.T) { Scheme: "http", Host: lb, } - u.Path = path.Join(u.Path, "r", s.AppName, s.RoutePath) + u.Path = path.Join(u.Path, "r", appName, rt.Path) // > 6MB output body := `{"echoContent": "HelloWorld", "sleepTime": 0, "isDebug": true, "trailerRepeat": 600000}` content := bytes.NewBuffer([]byte(body)) output := &bytes.Buffer{} - resp, err := apiutils.CallFN(s.Context, u.String(), content, output, "POST", []string{}) + resp, err := callFN(ctx, u.String(), content, output, "POST") if err != nil { t.Fatalf("Got unexpected error: %v", err) } @@ -209,17 +186,9 @@ func TestCanExecuteTooBigOutput(t *testing.T) { } func TestCanExecuteEmptyOutput(t *testing.T) { - s := apiutils.SetupHarness() - s.GivenAppExists(t, &sdkmodels.App{Name: s.AppName}) - defer s.Cleanup() - - rt := s.BasicRoute() - rt.Image = "fnproject/fn-test-utils" - rt.Format = "json" - rt.Memory = 64 - rt.Type = "sync" - - s.GivenRouteExists(t, s.AppName, rt) + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + rt := ensureRoute(t) lb, err := LB() if err != nil { @@ -229,14 +198,14 @@ func TestCanExecuteEmptyOutput(t *testing.T) { Scheme: "http", Host: lb, } - u.Path = path.Join(u.Path, "r", s.AppName, s.RoutePath) + u.Path = path.Join(u.Path, "r", appName, rt.Path) // empty body output body := `{"sleepTime": 0, "isDebug": true, "isEmptyBody": true}` content := bytes.NewBuffer([]byte(body)) output := &bytes.Buffer{} - resp, err := apiutils.CallFN(s.Context, u.String(), content, output, "POST", []string{}) + resp, err := callFN(ctx, u.String(), content, output, "POST") if err != nil { t.Fatalf("Got unexpected error: %v", err) } @@ -253,19 +222,9 @@ func TestCanExecuteEmptyOutput(t *testing.T) { } func TestBasicConcurrentExecution(t *testing.T) { - - s := apiutils.SetupHarness() - - s.GivenAppExists(t, &sdkmodels.App{Name: s.AppName}) - defer s.Cleanup() - - rt := s.BasicRoute() - rt.Image = "fnproject/fn-test-utils" - rt.Format = "json" - rt.Memory = 32 - rt.Type = "sync" - - s.GivenRouteExists(t, s.AppName, rt) + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + rt := ensureRoute(t) lb, err := LB() if err != nil { @@ -275,7 +234,7 @@ func TestBasicConcurrentExecution(t *testing.T) { Scheme: "http", Host: lb, } - u.Path = path.Join(u.Path, "r", s.AppName, s.RoutePath) + u.Path = path.Join(u.Path, "r", appName, rt.Path) results := make(chan error) concurrentFuncs := 10 @@ -284,7 +243,7 @@ func TestBasicConcurrentExecution(t *testing.T) { body := `{"echoContent": "HelloWorld", "sleepTime": 0, "isDebug": true}` content := bytes.NewBuffer([]byte(body)) output := &bytes.Buffer{} - resp, err := apiutils.CallFN(s.Context, u.String(), content, output, "POST", []string{}) + resp, err := callFN(ctx, u.String(), content, output, "POST") if err != nil { results <- fmt.Errorf("Got unexpected error: %v", err) return @@ -313,26 +272,17 @@ func TestBasicConcurrentExecution(t *testing.T) { } func TestSaturatedSystem(t *testing.T) { - - s := apiutils.SetupHarness() - - // override default 60 secs with shorter. - s.Cancel() - s.Context, s.Cancel = context.WithTimeout(context.Background(), 4*time.Second) - - s.GivenAppExists(t, &sdkmodels.App{Name: s.AppName}) - defer s.Cleanup() - - timeout := int32(1) - - rt := s.BasicRoute() - rt.Image = "fnproject/fn-test-utils" - rt.Format = "json" - rt.Timeout = &timeout - rt.Memory = 300 - rt.Type = "sync" - - s.GivenRouteExists(t, s.AppName, rt) + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + defer cancel() + rt := &models.Route{ + Path: routeName, + Timeout: 1, + Image: "fnproject/fn-test-utils", + Format: "json", + Memory: 300, + Type: "sync", + } + rt = ensureRoute(t, rt) lb, err := LB() if err != nil { @@ -342,14 +292,119 @@ func TestSaturatedSystem(t *testing.T) { Scheme: "http", Host: lb, } - u.Path = path.Join(u.Path, "r", s.AppName, s.RoutePath) + u.Path = path.Join(u.Path, "r", appName, rt.Path) body := `{"echoContent": "HelloWorld", "sleepTime": 0, "isDebug": true}` content := bytes.NewBuffer([]byte(body)) output := &bytes.Buffer{} - resp, err := apiutils.CallFN(s.Context, u.String(), content, output, "POST", []string{}) - if resp != nil || err == nil || s.Context.Err() == nil { + resp, err := callFN(ctx, u.String(), content, output, "POST") + if resp != nil || err == nil || ctx.Err() == nil { t.Fatalf("Expected response: %v err:%v", resp, err) } } + +func callFN(ctx context.Context, u string, content io.Reader, output io.Writer, method string) (*http.Response, error) { + if method == "" { + if content == nil { + method = "GET" + } else { + method = "POST" + } + } + + req, err := http.NewRequest(method, u, content) + if err != nil { + return nil, fmt.Errorf("error running route: %s", err) + } + req.Header.Set("Content-Type", "application/json") + req = req.WithContext(ctx) + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, fmt.Errorf("error running route: %s", err) + } + + io.Copy(output, resp.Body) + + return resp, nil +} + +func getAPIURL() (string, *url.URL) { + apiURL := getEnv("FN_API_URL", "http://localhost:8080") + u, err := url.Parse(apiURL) + if err != nil { + log.Fatalf("Couldn't parse API URL: %s error: %s", apiURL, err) + } + return apiURL, u +} + +func host() string { + u, _ := getAPIURL() + return u +} + +const ( + appName = "systemtestapp" + routeName = "/systemtestroute" + image = "fnproject/fn-test-utils" + format = "json" + memory = 64 + typ = "sync" +) + +func ensureRoute(t *testing.T, rts ...*models.Route) *models.Route { + var rt *models.Route + if len(rts) > 0 { + rt = rts[0] + } else { + rt = &models.Route{ + Path: routeName + "yabbadabbadoo", + Image: image, + Format: format, + Memory: memory, + Type: typ, + } + } + var wrapped struct { + Route *models.Route `json:"route"` + } + + wrapped.Route = rt + + var buf bytes.Buffer + err := json.NewEncoder(&buf).Encode(wrapped) + if err != nil { + t.Fatal("error encoding body", err) + } + + urlStr := host() + "/v1/apps/" + appName + "/routes" + rt.Path + u, err := url.Parse(urlStr) + if err != nil { + t.Fatal("error creating url", urlStr, err) + } + + req, err := http.NewRequest("PUT", u.String(), &buf) + if err != nil { + t.Fatal("error creating request", err) + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal("error creating route", err) + } + + buf.Reset() + io.Copy(&buf, resp.Body) + if resp.StatusCode != 200 { + t.Fatal("error creating/updating app or otherwise ensuring it exists:", resp.StatusCode, buf.String()) + } + + wrapped.Route = nil + err = json.NewDecoder(&buf).Decode(&wrapped) + if err != nil { + t.Fatal("error decoding response") + } + + return wrapped.Route +} diff --git a/vendor/github.com/PuerkitoBio/purell/.gitignore b/vendor/github.com/PuerkitoBio/purell/.gitignore deleted file mode 100644 index 748e4c807..000000000 --- a/vendor/github.com/PuerkitoBio/purell/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -*.sublime-* -.DS_Store -*.swp -*.swo -tags diff --git a/vendor/github.com/PuerkitoBio/purell/.travis.yml b/vendor/github.com/PuerkitoBio/purell/.travis.yml deleted file mode 100644 index facfc91c6..000000000 --- a/vendor/github.com/PuerkitoBio/purell/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: go - -go: - - 1.4 - - 1.5 - - 1.6 - - tip diff --git a/vendor/github.com/PuerkitoBio/purell/LICENSE b/vendor/github.com/PuerkitoBio/purell/LICENSE deleted file mode 100644 index 4b9986dea..000000000 --- a/vendor/github.com/PuerkitoBio/purell/LICENSE +++ /dev/null @@ -1,12 +0,0 @@ -Copyright (c) 2012, Martin Angers -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. - -* Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -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/PuerkitoBio/purell/README.md b/vendor/github.com/PuerkitoBio/purell/README.md deleted file mode 100644 index 09e8a32cb..000000000 --- a/vendor/github.com/PuerkitoBio/purell/README.md +++ /dev/null @@ -1,187 +0,0 @@ -# Purell - -Purell is a tiny Go library to normalize URLs. It returns a pure URL. Pure-ell. Sanitizer and all. Yeah, I know... - -Based on the [wikipedia paper][wiki] and the [RFC 3986 document][rfc]. - -[![build status](https://secure.travis-ci.org/PuerkitoBio/purell.png)](http://travis-ci.org/PuerkitoBio/purell) - -## Install - -`go get github.com/PuerkitoBio/purell` - -## Changelog - -* **2016-11-14 (v1.1.0)** : IDN: Conform to RFC 5895: Fold character width (thanks to @beeker1121). -* **2016-07-27 (v1.0.0)** : Normalize IDN to ASCII (thanks to @zenovich). -* **2015-02-08** : Add fix for relative paths issue ([PR #5][pr5]) and add fix for unnecessary encoding of reserved characters ([see issue #7][iss7]). -* **v0.2.0** : Add benchmarks, Attempt IDN support. -* **v0.1.0** : Initial release. - -## Examples - -From `example_test.go` (note that in your code, you would import "github.com/PuerkitoBio/purell", and would prefix references to its methods and constants with "purell."): - -```go -package purell - -import ( - "fmt" - "net/url" -) - -func ExampleNormalizeURLString() { - if normalized, err := NormalizeURLString("hTTp://someWEBsite.com:80/Amazing%3f/url/", - FlagLowercaseScheme|FlagLowercaseHost|FlagUppercaseEscapes); err != nil { - panic(err) - } else { - fmt.Print(normalized) - } - // Output: http://somewebsite.com:80/Amazing%3F/url/ -} - -func ExampleMustNormalizeURLString() { - normalized := MustNormalizeURLString("hTTpS://someWEBsite.com:443/Amazing%fa/url/", - FlagsUnsafeGreedy) - fmt.Print(normalized) - - // Output: http://somewebsite.com/Amazing%FA/url -} - -func ExampleNormalizeURL() { - if u, err := url.Parse("Http://SomeUrl.com:8080/a/b/.././c///g?c=3&a=1&b=9&c=0#target"); err != nil { - panic(err) - } else { - normalized := NormalizeURL(u, FlagsUsuallySafeGreedy|FlagRemoveDuplicateSlashes|FlagRemoveFragment) - fmt.Print(normalized) - } - - // Output: http://someurl.com:8080/a/c/g?c=3&a=1&b=9&c=0 -} -``` - -## API - -As seen in the examples above, purell offers three methods, `NormalizeURLString(string, NormalizationFlags) (string, error)`, `MustNormalizeURLString(string, NormalizationFlags) (string)` and `NormalizeURL(*url.URL, NormalizationFlags) (string)`. They all normalize the provided URL based on the specified flags. Here are the available flags: - -```go -const ( - // Safe normalizations - FlagLowercaseScheme NormalizationFlags = 1 << iota // HTTP://host -> http://host, applied by default in Go1.1 - FlagLowercaseHost // http://HOST -> http://host - FlagUppercaseEscapes // http://host/t%ef -> http://host/t%EF - FlagDecodeUnnecessaryEscapes // http://host/t%41 -> http://host/tA - FlagEncodeNecessaryEscapes // http://host/!"#$ -> http://host/%21%22#$ - FlagRemoveDefaultPort // http://host:80 -> http://host - FlagRemoveEmptyQuerySeparator // http://host/path? -> http://host/path - - // Usually safe normalizations - FlagRemoveTrailingSlash // http://host/path/ -> http://host/path - FlagAddTrailingSlash // http://host/path -> http://host/path/ (should choose only one of these add/remove trailing slash flags) - FlagRemoveDotSegments // http://host/path/./a/b/../c -> http://host/path/a/c - - // Unsafe normalizations - FlagRemoveDirectoryIndex // http://host/path/index.html -> http://host/path/ - FlagRemoveFragment // http://host/path#fragment -> http://host/path - FlagForceHTTP // https://host -> http://host - FlagRemoveDuplicateSlashes // http://host/path//a///b -> http://host/path/a/b - FlagRemoveWWW // http://www.host/ -> http://host/ - FlagAddWWW // http://host/ -> http://www.host/ (should choose only one of these add/remove WWW flags) - FlagSortQuery // http://host/path?c=3&b=2&a=1&b=1 -> http://host/path?a=1&b=1&b=2&c=3 - - // Normalizations not in the wikipedia article, required to cover tests cases - // submitted by jehiah - FlagDecodeDWORDHost // http://1113982867 -> http://66.102.7.147 - FlagDecodeOctalHost // http://0102.0146.07.0223 -> http://66.102.7.147 - FlagDecodeHexHost // http://0x42660793 -> http://66.102.7.147 - FlagRemoveUnnecessaryHostDots // http://.host../path -> http://host/path - FlagRemoveEmptyPortSeparator // http://host:/path -> http://host/path - - // Convenience set of safe normalizations - FlagsSafe NormalizationFlags = FlagLowercaseHost | FlagLowercaseScheme | FlagUppercaseEscapes | FlagDecodeUnnecessaryEscapes | FlagEncodeNecessaryEscapes | FlagRemoveDefaultPort | FlagRemoveEmptyQuerySeparator - - // For convenience sets, "greedy" uses the "remove trailing slash" and "remove www. prefix" flags, - // while "non-greedy" uses the "add (or keep) the trailing slash" and "add www. prefix". - - // Convenience set of usually safe normalizations (includes FlagsSafe) - FlagsUsuallySafeGreedy NormalizationFlags = FlagsSafe | FlagRemoveTrailingSlash | FlagRemoveDotSegments - FlagsUsuallySafeNonGreedy NormalizationFlags = FlagsSafe | FlagAddTrailingSlash | FlagRemoveDotSegments - - // Convenience set of unsafe normalizations (includes FlagsUsuallySafe) - FlagsUnsafeGreedy NormalizationFlags = FlagsUsuallySafeGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagRemoveWWW | FlagSortQuery - FlagsUnsafeNonGreedy NormalizationFlags = FlagsUsuallySafeNonGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagAddWWW | FlagSortQuery - - // Convenience set of all available flags - FlagsAllGreedy = FlagsUnsafeGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator - FlagsAllNonGreedy = FlagsUnsafeNonGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator -) -``` - -For convenience, the set of flags `FlagsSafe`, `FlagsUsuallySafe[Greedy|NonGreedy]`, `FlagsUnsafe[Greedy|NonGreedy]` and `FlagsAll[Greedy|NonGreedy]` are provided for the similarly grouped normalizations on [wikipedia's URL normalization page][wiki]. You can add (using the bitwise OR `|` operator) or remove (using the bitwise AND NOT `&^` operator) individual flags from the sets if required, to build your own custom set. - -The [full godoc reference is available on gopkgdoc][godoc]. - -Some things to note: - -* `FlagDecodeUnnecessaryEscapes`, `FlagEncodeNecessaryEscapes`, `FlagUppercaseEscapes` and `FlagRemoveEmptyQuerySeparator` are always implicitly set, because internally, the URL string is parsed as an URL object, which automatically decodes unnecessary escapes, uppercases and encodes necessary ones, and removes empty query separators (an unnecessary `?` at the end of the url). So this operation cannot **not** be done. For this reason, `FlagRemoveEmptyQuerySeparator` (as well as the other three) has been included in the `FlagsSafe` convenience set, instead of `FlagsUnsafe`, where Wikipedia puts it. - -* The `FlagDecodeUnnecessaryEscapes` decodes the following escapes (*from -> to*): - - %24 -> $ - - %26 -> & - - %2B-%3B -> +,-./0123456789:; - - %3D -> = - - %40-%5A -> @ABCDEFGHIJKLMNOPQRSTUVWXYZ - - %5F -> _ - - %61-%7A -> abcdefghijklmnopqrstuvwxyz - - %7E -> ~ - - -* When the `NormalizeURL` function is used (passing an URL object), this source URL object is modified (that is, after the call, the URL object will be modified to reflect the normalization). - -* The *replace IP with domain name* normalization (`http://208.77.188.166/ → http://www.example.com/`) is obviously not possible for a library without making some network requests. This is not implemented in purell. - -* The *remove unused query string parameters* and *remove default query parameters* are also not implemented, since this is a very case-specific normalization, and it is quite trivial to do with an URL object. - -### Safe vs Usually Safe vs Unsafe - -Purell allows you to control the level of risk you take while normalizing an URL. You can aggressively normalize, play it totally safe, or anything in between. - -Consider the following URL: - -`HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid` - -Normalizing with the `FlagsSafe` gives: - -`https://www.root.com/toto/tE%1F///a/./b/../c/?z=3&w=2&a=4&w=1#invalid` - -With the `FlagsUsuallySafeGreedy`: - -`https://www.root.com/toto/tE%1F///a/c?z=3&w=2&a=4&w=1#invalid` - -And with `FlagsUnsafeGreedy`: - -`http://root.com/toto/tE%1F/a/c?a=4&w=1&w=2&z=3` - -## TODOs - -* Add a class/default instance to allow specifying custom directory index names? At the moment, removing directory index removes `(^|/)((?:default|index)\.\w{1,4})$`. - -## Thanks / Contributions - -@rogpeppe -@jehiah -@opennota -@pchristopher1275 -@zenovich -@beeker1121 - -## License - -The [BSD 3-Clause license][bsd]. - -[bsd]: http://opensource.org/licenses/BSD-3-Clause -[wiki]: http://en.wikipedia.org/wiki/URL_normalization -[rfc]: http://tools.ietf.org/html/rfc3986#section-6 -[godoc]: http://go.pkgdoc.org/github.com/PuerkitoBio/purell -[pr5]: https://github.com/PuerkitoBio/purell/pull/5 -[iss7]: https://github.com/PuerkitoBio/purell/issues/7 diff --git a/vendor/github.com/PuerkitoBio/purell/bench_test.go b/vendor/github.com/PuerkitoBio/purell/bench_test.go deleted file mode 100644 index 7549731fc..000000000 --- a/vendor/github.com/PuerkitoBio/purell/bench_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package purell - -import ( - "testing" -) - -var ( - safeUrl = "HttPS://..iaMHost..Test:443/paTh^A%ef//./%41PaTH/..//?" - usuallySafeUrl = "HttPS://..iaMHost..Test:443/paTh^A%ef//./%41PaTH/../final/" - unsafeUrl = "HttPS://..www.iaMHost..Test:443/paTh^A%ef//./%41PaTH/../final/index.html?t=val1&a=val4&z=val5&a=val1#fragment" - allDWORDUrl = "HttPS://1113982867:/paTh^A%ef//./%41PaTH/../final/index.html?t=val1&a=val4&z=val5&a=val1#fragment" - allOctalUrl = "HttPS://0102.0146.07.0223:/paTh^A%ef//./%41PaTH/../final/index.html?t=val1&a=val4&z=val5&a=val1#fragment" - allHexUrl = "HttPS://0x42660793:/paTh^A%ef//./%41PaTH/../final/index.html?t=val1&a=val4&z=val5&a=val1#fragment" - allCombinedUrl = "HttPS://..0x42660793.:/paTh^A%ef//./%41PaTH/../final/index.html?t=val1&a=val4&z=val5&a=val1#fragment" -) - -func BenchmarkSafe(b *testing.B) { - for i := 0; i < b.N; i++ { - NormalizeURLString(safeUrl, FlagsSafe) - } -} - -func BenchmarkUsuallySafe(b *testing.B) { - for i := 0; i < b.N; i++ { - NormalizeURLString(usuallySafeUrl, FlagsUsuallySafeGreedy) - } -} - -func BenchmarkUnsafe(b *testing.B) { - for i := 0; i < b.N; i++ { - NormalizeURLString(unsafeUrl, FlagsUnsafeGreedy) - } -} - -func BenchmarkAllDWORD(b *testing.B) { - for i := 0; i < b.N; i++ { - NormalizeURLString(allDWORDUrl, FlagsAllGreedy) - } -} - -func BenchmarkAllOctal(b *testing.B) { - for i := 0; i < b.N; i++ { - NormalizeURLString(allOctalUrl, FlagsAllGreedy) - } -} - -func BenchmarkAllHex(b *testing.B) { - for i := 0; i < b.N; i++ { - NormalizeURLString(allHexUrl, FlagsAllGreedy) - } -} - -func BenchmarkAllCombined(b *testing.B) { - for i := 0; i < b.N; i++ { - NormalizeURLString(allCombinedUrl, FlagsAllGreedy) - } -} diff --git a/vendor/github.com/PuerkitoBio/purell/benchmarks/v0.1.0 b/vendor/github.com/PuerkitoBio/purell/benchmarks/v0.1.0 deleted file mode 100644 index 3bbe7113c..000000000 --- a/vendor/github.com/PuerkitoBio/purell/benchmarks/v0.1.0 +++ /dev/null @@ -1,9 +0,0 @@ -PASS -BenchmarkSafe 500000 6131 ns/op -BenchmarkUsuallySafe 200000 7864 ns/op -BenchmarkUnsafe 100000 28560 ns/op -BenchmarkAllDWORD 50000 38722 ns/op -BenchmarkAllOctal 50000 40941 ns/op -BenchmarkAllHex 50000 44063 ns/op -BenchmarkAllCombined 50000 33613 ns/op -ok github.com/PuerkitoBio/purell 17.404s diff --git a/vendor/github.com/PuerkitoBio/purell/example_test.go b/vendor/github.com/PuerkitoBio/purell/example_test.go deleted file mode 100644 index 997b95369..000000000 --- a/vendor/github.com/PuerkitoBio/purell/example_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package purell - -import ( - "fmt" - "net/url" -) - -func ExampleNormalizeURLString() { - if normalized, err := NormalizeURLString("hTTp://someWEBsite.com:80/Amazing%3f/url/", - FlagLowercaseScheme|FlagLowercaseHost|FlagUppercaseEscapes); err != nil { - panic(err) - } else { - fmt.Print(normalized) - } - // Output: http://somewebsite.com:80/Amazing%3F/url/ -} - -func ExampleMustNormalizeURLString() { - normalized := MustNormalizeURLString("hTTpS://someWEBsite.com:443/Amazing%fa/url/", - FlagsUnsafeGreedy) - fmt.Print(normalized) - - // Output: http://somewebsite.com/Amazing%FA/url -} - -func ExampleNormalizeURL() { - if u, err := url.Parse("Http://SomeUrl.com:8080/a/b/.././c///g?c=3&a=1&b=9&c=0#target"); err != nil { - panic(err) - } else { - normalized := NormalizeURL(u, FlagsUsuallySafeGreedy|FlagRemoveDuplicateSlashes|FlagRemoveFragment) - fmt.Print(normalized) - } - - // Output: http://someurl.com:8080/a/c/g?c=3&a=1&b=9&c=0 -} diff --git a/vendor/github.com/PuerkitoBio/purell/purell.go b/vendor/github.com/PuerkitoBio/purell/purell.go deleted file mode 100644 index 645e1b76f..000000000 --- a/vendor/github.com/PuerkitoBio/purell/purell.go +++ /dev/null @@ -1,379 +0,0 @@ -/* -Package purell offers URL normalization as described on the wikipedia page: -http://en.wikipedia.org/wiki/URL_normalization -*/ -package purell - -import ( - "bytes" - "fmt" - "net/url" - "regexp" - "sort" - "strconv" - "strings" - - "github.com/PuerkitoBio/urlesc" - "golang.org/x/net/idna" - "golang.org/x/text/unicode/norm" - "golang.org/x/text/width" -) - -// A set of normalization flags determines how a URL will -// be normalized. -type NormalizationFlags uint - -const ( - // Safe normalizations - FlagLowercaseScheme NormalizationFlags = 1 << iota // HTTP://host -> http://host, applied by default in Go1.1 - FlagLowercaseHost // http://HOST -> http://host - FlagUppercaseEscapes // http://host/t%ef -> http://host/t%EF - FlagDecodeUnnecessaryEscapes // http://host/t%41 -> http://host/tA - FlagEncodeNecessaryEscapes // http://host/!"#$ -> http://host/%21%22#$ - FlagRemoveDefaultPort // http://host:80 -> http://host - FlagRemoveEmptyQuerySeparator // http://host/path? -> http://host/path - - // Usually safe normalizations - FlagRemoveTrailingSlash // http://host/path/ -> http://host/path - FlagAddTrailingSlash // http://host/path -> http://host/path/ (should choose only one of these add/remove trailing slash flags) - FlagRemoveDotSegments // http://host/path/./a/b/../c -> http://host/path/a/c - - // Unsafe normalizations - FlagRemoveDirectoryIndex // http://host/path/index.html -> http://host/path/ - FlagRemoveFragment // http://host/path#fragment -> http://host/path - FlagForceHTTP // https://host -> http://host - FlagRemoveDuplicateSlashes // http://host/path//a///b -> http://host/path/a/b - FlagRemoveWWW // http://www.host/ -> http://host/ - FlagAddWWW // http://host/ -> http://www.host/ (should choose only one of these add/remove WWW flags) - FlagSortQuery // http://host/path?c=3&b=2&a=1&b=1 -> http://host/path?a=1&b=1&b=2&c=3 - - // Normalizations not in the wikipedia article, required to cover tests cases - // submitted by jehiah - FlagDecodeDWORDHost // http://1113982867 -> http://66.102.7.147 - FlagDecodeOctalHost // http://0102.0146.07.0223 -> http://66.102.7.147 - FlagDecodeHexHost // http://0x42660793 -> http://66.102.7.147 - FlagRemoveUnnecessaryHostDots // http://.host../path -> http://host/path - FlagRemoveEmptyPortSeparator // http://host:/path -> http://host/path - - // Convenience set of safe normalizations - FlagsSafe NormalizationFlags = FlagLowercaseHost | FlagLowercaseScheme | FlagUppercaseEscapes | FlagDecodeUnnecessaryEscapes | FlagEncodeNecessaryEscapes | FlagRemoveDefaultPort | FlagRemoveEmptyQuerySeparator - - // For convenience sets, "greedy" uses the "remove trailing slash" and "remove www. prefix" flags, - // while "non-greedy" uses the "add (or keep) the trailing slash" and "add www. prefix". - - // Convenience set of usually safe normalizations (includes FlagsSafe) - FlagsUsuallySafeGreedy NormalizationFlags = FlagsSafe | FlagRemoveTrailingSlash | FlagRemoveDotSegments - FlagsUsuallySafeNonGreedy NormalizationFlags = FlagsSafe | FlagAddTrailingSlash | FlagRemoveDotSegments - - // Convenience set of unsafe normalizations (includes FlagsUsuallySafe) - FlagsUnsafeGreedy NormalizationFlags = FlagsUsuallySafeGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagRemoveWWW | FlagSortQuery - FlagsUnsafeNonGreedy NormalizationFlags = FlagsUsuallySafeNonGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagAddWWW | FlagSortQuery - - // Convenience set of all available flags - FlagsAllGreedy = FlagsUnsafeGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator - FlagsAllNonGreedy = FlagsUnsafeNonGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator -) - -const ( - defaultHttpPort = ":80" - defaultHttpsPort = ":443" -) - -// Regular expressions used by the normalizations -var rxPort = regexp.MustCompile(`(:\d+)/?$`) -var rxDirIndex = regexp.MustCompile(`(^|/)((?:default|index)\.\w{1,4})$`) -var rxDupSlashes = regexp.MustCompile(`/{2,}`) -var rxDWORDHost = regexp.MustCompile(`^(\d+)((?:\.+)?(?:\:\d*)?)$`) -var rxOctalHost = regexp.MustCompile(`^(0\d*)\.(0\d*)\.(0\d*)\.(0\d*)((?:\.+)?(?:\:\d*)?)$`) -var rxHexHost = regexp.MustCompile(`^0x([0-9A-Fa-f]+)((?:\.+)?(?:\:\d*)?)$`) -var rxHostDots = regexp.MustCompile(`^(.+?)(:\d+)?$`) -var rxEmptyPort = regexp.MustCompile(`:+$`) - -// Map of flags to implementation function. -// FlagDecodeUnnecessaryEscapes has no action, since it is done automatically -// by parsing the string as an URL. Same for FlagUppercaseEscapes and FlagRemoveEmptyQuerySeparator. - -// Since maps have undefined traversing order, make a slice of ordered keys -var flagsOrder = []NormalizationFlags{ - FlagLowercaseScheme, - FlagLowercaseHost, - FlagRemoveDefaultPort, - FlagRemoveDirectoryIndex, - FlagRemoveDotSegments, - FlagRemoveFragment, - FlagForceHTTP, // Must be after remove default port (because https=443/http=80) - FlagRemoveDuplicateSlashes, - FlagRemoveWWW, - FlagAddWWW, - FlagSortQuery, - FlagDecodeDWORDHost, - FlagDecodeOctalHost, - FlagDecodeHexHost, - FlagRemoveUnnecessaryHostDots, - FlagRemoveEmptyPortSeparator, - FlagRemoveTrailingSlash, // These two (add/remove trailing slash) must be last - FlagAddTrailingSlash, -} - -// ... and then the map, where order is unimportant -var flags = map[NormalizationFlags]func(*url.URL){ - FlagLowercaseScheme: lowercaseScheme, - FlagLowercaseHost: lowercaseHost, - FlagRemoveDefaultPort: removeDefaultPort, - FlagRemoveDirectoryIndex: removeDirectoryIndex, - FlagRemoveDotSegments: removeDotSegments, - FlagRemoveFragment: removeFragment, - FlagForceHTTP: forceHTTP, - FlagRemoveDuplicateSlashes: removeDuplicateSlashes, - FlagRemoveWWW: removeWWW, - FlagAddWWW: addWWW, - FlagSortQuery: sortQuery, - FlagDecodeDWORDHost: decodeDWORDHost, - FlagDecodeOctalHost: decodeOctalHost, - FlagDecodeHexHost: decodeHexHost, - FlagRemoveUnnecessaryHostDots: removeUnncessaryHostDots, - FlagRemoveEmptyPortSeparator: removeEmptyPortSeparator, - FlagRemoveTrailingSlash: removeTrailingSlash, - FlagAddTrailingSlash: addTrailingSlash, -} - -// MustNormalizeURLString returns the normalized string, and panics if an error occurs. -// It takes an URL string as input, as well as the normalization flags. -func MustNormalizeURLString(u string, f NormalizationFlags) string { - result, e := NormalizeURLString(u, f) - if e != nil { - panic(e) - } - return result -} - -// NormalizeURLString returns the normalized string, or an error if it can't be parsed into an URL object. -// It takes an URL string as input, as well as the normalization flags. -func NormalizeURLString(u string, f NormalizationFlags) (string, error) { - parsed, err := url.Parse(u) - if err != nil { - return "", err - } - - if f&FlagLowercaseHost == FlagLowercaseHost { - parsed.Host = strings.ToLower(parsed.Host) - } - - // The idna package doesn't fully conform to RFC 5895 - // (https://tools.ietf.org/html/rfc5895), so we do it here. - // Taken from Go 1.8 cycle source, courtesy of bradfitz. - // TODO: Remove when (if?) idna package conforms to RFC 5895. - parsed.Host = width.Fold.String(parsed.Host) - parsed.Host = norm.NFC.String(parsed.Host) - if parsed.Host, err = idna.ToASCII(parsed.Host); err != nil { - return "", err - } - - return NormalizeURL(parsed, f), nil -} - -// NormalizeURL returns the normalized string. -// It takes a parsed URL object as input, as well as the normalization flags. -func NormalizeURL(u *url.URL, f NormalizationFlags) string { - for _, k := range flagsOrder { - if f&k == k { - flags[k](u) - } - } - return urlesc.Escape(u) -} - -func lowercaseScheme(u *url.URL) { - if len(u.Scheme) > 0 { - u.Scheme = strings.ToLower(u.Scheme) - } -} - -func lowercaseHost(u *url.URL) { - if len(u.Host) > 0 { - u.Host = strings.ToLower(u.Host) - } -} - -func removeDefaultPort(u *url.URL) { - if len(u.Host) > 0 { - scheme := strings.ToLower(u.Scheme) - u.Host = rxPort.ReplaceAllStringFunc(u.Host, func(val string) string { - if (scheme == "http" && val == defaultHttpPort) || (scheme == "https" && val == defaultHttpsPort) { - return "" - } - return val - }) - } -} - -func removeTrailingSlash(u *url.URL) { - if l := len(u.Path); l > 0 { - if strings.HasSuffix(u.Path, "/") { - u.Path = u.Path[:l-1] - } - } else if l = len(u.Host); l > 0 { - if strings.HasSuffix(u.Host, "/") { - u.Host = u.Host[:l-1] - } - } -} - -func addTrailingSlash(u *url.URL) { - if l := len(u.Path); l > 0 { - if !strings.HasSuffix(u.Path, "/") { - u.Path += "/" - } - } else if l = len(u.Host); l > 0 { - if !strings.HasSuffix(u.Host, "/") { - u.Host += "/" - } - } -} - -func removeDotSegments(u *url.URL) { - if len(u.Path) > 0 { - var dotFree []string - var lastIsDot bool - - sections := strings.Split(u.Path, "/") - for _, s := range sections { - if s == ".." { - if len(dotFree) > 0 { - dotFree = dotFree[:len(dotFree)-1] - } - } else if s != "." { - dotFree = append(dotFree, s) - } - lastIsDot = (s == "." || s == "..") - } - // Special case if host does not end with / and new path does not begin with / - u.Path = strings.Join(dotFree, "/") - if u.Host != "" && !strings.HasSuffix(u.Host, "/") && !strings.HasPrefix(u.Path, "/") { - u.Path = "/" + u.Path - } - // Special case if the last segment was a dot, make sure the path ends with a slash - if lastIsDot && !strings.HasSuffix(u.Path, "/") { - u.Path += "/" - } - } -} - -func removeDirectoryIndex(u *url.URL) { - if len(u.Path) > 0 { - u.Path = rxDirIndex.ReplaceAllString(u.Path, "$1") - } -} - -func removeFragment(u *url.URL) { - u.Fragment = "" -} - -func forceHTTP(u *url.URL) { - if strings.ToLower(u.Scheme) == "https" { - u.Scheme = "http" - } -} - -func removeDuplicateSlashes(u *url.URL) { - if len(u.Path) > 0 { - u.Path = rxDupSlashes.ReplaceAllString(u.Path, "/") - } -} - -func removeWWW(u *url.URL) { - if len(u.Host) > 0 && strings.HasPrefix(strings.ToLower(u.Host), "www.") { - u.Host = u.Host[4:] - } -} - -func addWWW(u *url.URL) { - if len(u.Host) > 0 && !strings.HasPrefix(strings.ToLower(u.Host), "www.") { - u.Host = "www." + u.Host - } -} - -func sortQuery(u *url.URL) { - q := u.Query() - - if len(q) > 0 { - arKeys := make([]string, len(q)) - i := 0 - for k, _ := range q { - arKeys[i] = k - i++ - } - sort.Strings(arKeys) - buf := new(bytes.Buffer) - for _, k := range arKeys { - sort.Strings(q[k]) - for _, v := range q[k] { - if buf.Len() > 0 { - buf.WriteRune('&') - } - buf.WriteString(fmt.Sprintf("%s=%s", k, urlesc.QueryEscape(v))) - } - } - - // Rebuild the raw query string - u.RawQuery = buf.String() - } -} - -func decodeDWORDHost(u *url.URL) { - if len(u.Host) > 0 { - if matches := rxDWORDHost.FindStringSubmatch(u.Host); len(matches) > 2 { - var parts [4]int64 - - dword, _ := strconv.ParseInt(matches[1], 10, 0) - for i, shift := range []uint{24, 16, 8, 0} { - parts[i] = dword >> shift & 0xFF - } - u.Host = fmt.Sprintf("%d.%d.%d.%d%s", parts[0], parts[1], parts[2], parts[3], matches[2]) - } - } -} - -func decodeOctalHost(u *url.URL) { - if len(u.Host) > 0 { - if matches := rxOctalHost.FindStringSubmatch(u.Host); len(matches) > 5 { - var parts [4]int64 - - for i := 1; i <= 4; i++ { - parts[i-1], _ = strconv.ParseInt(matches[i], 8, 0) - } - u.Host = fmt.Sprintf("%d.%d.%d.%d%s", parts[0], parts[1], parts[2], parts[3], matches[5]) - } - } -} - -func decodeHexHost(u *url.URL) { - if len(u.Host) > 0 { - if matches := rxHexHost.FindStringSubmatch(u.Host); len(matches) > 2 { - // Conversion is safe because of regex validation - parsed, _ := strconv.ParseInt(matches[1], 16, 0) - // Set host as DWORD (base 10) encoded host - u.Host = fmt.Sprintf("%d%s", parsed, matches[2]) - // The rest is the same as decoding a DWORD host - decodeDWORDHost(u) - } - } -} - -func removeUnncessaryHostDots(u *url.URL) { - if len(u.Host) > 0 { - if matches := rxHostDots.FindStringSubmatch(u.Host); len(matches) > 1 { - // Trim the leading and trailing dots - u.Host = strings.Trim(matches[1], ".") - if len(matches) > 2 { - u.Host += matches[2] - } - } - } -} - -func removeEmptyPortSeparator(u *url.URL) { - if len(u.Host) > 0 { - u.Host = rxEmptyPort.ReplaceAllString(u.Host, "") - } -} diff --git a/vendor/github.com/PuerkitoBio/purell/purell_test.go b/vendor/github.com/PuerkitoBio/purell/purell_test.go deleted file mode 100644 index a3732e5a3..000000000 --- a/vendor/github.com/PuerkitoBio/purell/purell_test.go +++ /dev/null @@ -1,768 +0,0 @@ -package purell - -import ( - "fmt" - "net/url" - "testing" -) - -type testCase struct { - nm string - src string - flgs NormalizationFlags - res string - parsed bool -} - -var ( - cases = [...]*testCase{ - &testCase{ - "LowerScheme", - "HTTP://www.SRC.ca", - FlagLowercaseScheme, - "http://www.SRC.ca", - false, - }, - &testCase{ - "LowerScheme2", - "http://www.SRC.ca", - FlagLowercaseScheme, - "http://www.SRC.ca", - false, - }, - &testCase{ - "LowerHost", - "HTTP://www.SRC.ca/", - FlagLowercaseHost, - "http://www.src.ca/", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "UpperEscapes", - `http://www.whatever.com/Some%aa%20Special%8Ecases/`, - FlagUppercaseEscapes, - "http://www.whatever.com/Some%AA%20Special%8Ecases/", - false, - }, - &testCase{ - "UnnecessaryEscapes", - `http://www.toto.com/%41%42%2E%44/%32%33%52%2D/%5f%7E`, - FlagDecodeUnnecessaryEscapes, - "http://www.toto.com/AB.D/23R-/_~", - false, - }, - &testCase{ - "RemoveDefaultPort", - "HTTP://www.SRC.ca:80/", - FlagRemoveDefaultPort, - "http://www.SRC.ca/", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveDefaultPort2", - "HTTP://www.SRC.ca:80", - FlagRemoveDefaultPort, - "http://www.SRC.ca", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveDefaultPort3", - "HTTP://www.SRC.ca:8080", - FlagRemoveDefaultPort, - "http://www.SRC.ca:8080", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "Safe", - "HTTP://www.SRC.ca:80/to%1ato%8b%ee/OKnow%41%42%43%7e", - FlagsSafe, - "http://www.src.ca/to%1Ato%8B%EE/OKnowABC~", - false, - }, - &testCase{ - "BothLower", - "HTTP://www.SRC.ca:80/to%1ato%8b%ee/OKnow%41%42%43%7e", - FlagLowercaseHost | FlagLowercaseScheme, - "http://www.src.ca:80/to%1Ato%8B%EE/OKnowABC~", - false, - }, - &testCase{ - "RemoveTrailingSlash", - "HTTP://www.SRC.ca:80/", - FlagRemoveTrailingSlash, - "http://www.SRC.ca:80", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveTrailingSlash2", - "HTTP://www.SRC.ca:80/toto/titi/", - FlagRemoveTrailingSlash, - "http://www.SRC.ca:80/toto/titi", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveTrailingSlash3", - "HTTP://www.SRC.ca:80/toto/titi/fin/?a=1", - FlagRemoveTrailingSlash, - "http://www.SRC.ca:80/toto/titi/fin?a=1", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "AddTrailingSlash", - "HTTP://www.SRC.ca:80", - FlagAddTrailingSlash, - "http://www.SRC.ca:80/", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "AddTrailingSlash2", - "HTTP://www.SRC.ca:80/toto/titi.html", - FlagAddTrailingSlash, - "http://www.SRC.ca:80/toto/titi.html/", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "AddTrailingSlash3", - "HTTP://www.SRC.ca:80/toto/titi/fin?a=1", - FlagAddTrailingSlash, - "http://www.SRC.ca:80/toto/titi/fin/?a=1", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveDotSegments", - "HTTP://root/a/b/./../../c/", - FlagRemoveDotSegments, - "http://root/c/", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveDotSegments2", - "HTTP://root/../a/b/./../c/../d", - FlagRemoveDotSegments, - "http://root/a/d", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "UsuallySafe", - "HTTP://www.SRC.ca:80/to%1ato%8b%ee/./c/d/../OKnow%41%42%43%7e/?a=b#test", - FlagsUsuallySafeGreedy, - "http://www.src.ca/to%1Ato%8B%EE/c/OKnowABC~?a=b#test", - false, - }, - &testCase{ - "RemoveDirectoryIndex", - "HTTP://root/a/b/c/default.aspx", - FlagRemoveDirectoryIndex, - "http://root/a/b/c/", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveDirectoryIndex2", - "HTTP://root/a/b/c/default#a=b", - FlagRemoveDirectoryIndex, - "http://root/a/b/c/default#a=b", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "RemoveFragment", - "HTTP://root/a/b/c/default#toto=tata", - FlagRemoveFragment, - "http://root/a/b/c/default", // Since Go1.1, scheme is automatically lowercased - false, - }, - &testCase{ - "ForceHTTP", - "https://root/a/b/c/default#toto=tata", - FlagForceHTTP, - "http://root/a/b/c/default#toto=tata", - false, - }, - &testCase{ - "RemoveDuplicateSlashes", - "https://root/a//b///c////default#toto=tata", - FlagRemoveDuplicateSlashes, - "https://root/a/b/c/default#toto=tata", - false, - }, - &testCase{ - "RemoveDuplicateSlashes2", - "https://root//a//b///c////default#toto=tata", - FlagRemoveDuplicateSlashes, - "https://root/a/b/c/default#toto=tata", - false, - }, - &testCase{ - "RemoveWWW", - "https://www.root/a/b/c/", - FlagRemoveWWW, - "https://root/a/b/c/", - false, - }, - &testCase{ - "RemoveWWW2", - "https://WwW.Root/a/b/c/", - FlagRemoveWWW, - "https://Root/a/b/c/", - false, - }, - &testCase{ - "AddWWW", - "https://Root/a/b/c/", - FlagAddWWW, - "https://www.Root/a/b/c/", - false, - }, - &testCase{ - "SortQuery", - "http://root/toto/?b=4&a=1&c=3&b=2&a=5", - FlagSortQuery, - "http://root/toto/?a=1&a=5&b=2&b=4&c=3", - false, - }, - &testCase{ - "RemoveEmptyQuerySeparator", - "http://root/toto/?", - FlagRemoveEmptyQuerySeparator, - "http://root/toto/", - false, - }, - &testCase{ - "Unsafe", - "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", - FlagsUnsafeGreedy, - "http://root.com/toto/tE%1F/a/c?a=4&w=1&w=2&z=3", - false, - }, - &testCase{ - "Safe2", - "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", - FlagsSafe, - "https://www.root.com/toto/tE%1F///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", - false, - }, - &testCase{ - "UsuallySafe2", - "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", - FlagsUsuallySafeGreedy, - "https://www.root.com/toto/tE%1F///a/c?z=3&w=2&a=4&w=1#invalid", - false, - }, - &testCase{ - "AddTrailingSlashBug", - "http://src.ca/", - FlagsAllNonGreedy, - "http://www.src.ca/", - false, - }, - &testCase{ - "SourceModified", - "HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid", - FlagsUnsafeGreedy, - "http://root.com/toto/tE%1F/a/c?a=4&w=1&w=2&z=3", - true, - }, - &testCase{ - "IPv6-1", - "http://[2001:db8:1f70::999:de8:7648:6e8]/test", - FlagsSafe | FlagRemoveDotSegments, - "http://[2001:db8:1f70::999:de8:7648:6e8]/test", - false, - }, - &testCase{ - "IPv6-2", - "http://[::ffff:192.168.1.1]/test", - FlagsSafe | FlagRemoveDotSegments, - "http://[::ffff:192.168.1.1]/test", - false, - }, - &testCase{ - "IPv6-3", - "http://[::ffff:192.168.1.1]:80/test", - FlagsSafe | FlagRemoveDotSegments, - "http://[::ffff:192.168.1.1]/test", - false, - }, - &testCase{ - "IPv6-4", - "htTps://[::fFff:192.168.1.1]:443/test", - FlagsSafe | FlagRemoveDotSegments, - "https://[::ffff:192.168.1.1]/test", - false, - }, - &testCase{ - "FTP", - "ftp://user:pass@ftp.foo.net/foo/bar", - FlagsSafe | FlagRemoveDotSegments, - "ftp://user:pass@ftp.foo.net/foo/bar", - false, - }, - &testCase{ - "Standard-1", - "http://www.foo.com:80/foo", - FlagsSafe | FlagRemoveDotSegments, - "http://www.foo.com/foo", - false, - }, - &testCase{ - "Standard-2", - "http://www.foo.com:8000/foo", - FlagsSafe | FlagRemoveDotSegments, - "http://www.foo.com:8000/foo", - false, - }, - &testCase{ - "Standard-3", - "http://www.foo.com/%7ebar", - FlagsSafe | FlagRemoveDotSegments, - "http://www.foo.com/~bar", - false, - }, - &testCase{ - "Standard-4", - "http://www.foo.com/%7Ebar", - FlagsSafe | FlagRemoveDotSegments, - "http://www.foo.com/~bar", - false, - }, - &testCase{ - "Standard-5", - "http://USER:pass@www.Example.COM/foo/bar", - FlagsSafe | FlagRemoveDotSegments, - "http://USER:pass@www.example.com/foo/bar", - false, - }, - &testCase{ - "Standard-6", - "http://test.example/?a=%26&b=1", - FlagsSafe | FlagRemoveDotSegments, - "http://test.example/?a=%26&b=1", - false, - }, - &testCase{ - "Standard-7", - "http://test.example/%25/?p=%20val%20%25", - FlagsSafe | FlagRemoveDotSegments, - "http://test.example/%25/?p=%20val%20%25", - false, - }, - &testCase{ - "Standard-8", - "http://test.example/path/with a%20space+/", - FlagsSafe | FlagRemoveDotSegments, - "http://test.example/path/with%20a%20space+/", - false, - }, - &testCase{ - "Standard-9", - "http://test.example/?", - FlagsSafe | FlagRemoveDotSegments, - "http://test.example/", - false, - }, - &testCase{ - "Standard-10", - "http://a.COM/path/?b&a", - FlagsSafe | FlagRemoveDotSegments, - "http://a.com/path/?b&a", - false, - }, - &testCase{ - "StandardCasesAddTrailingSlash", - "http://test.example?", - FlagsSafe | FlagAddTrailingSlash, - "http://test.example/", - false, - }, - &testCase{ - "OctalIP-1", - "http://0123.011.0.4/", - FlagsSafe | FlagDecodeOctalHost, - "http://0123.011.0.4/", - false, - }, - &testCase{ - "OctalIP-2", - "http://0102.0146.07.0223/", - FlagsSafe | FlagDecodeOctalHost, - "http://66.102.7.147/", - false, - }, - &testCase{ - "OctalIP-3", - "http://0102.0146.07.0223.:23/", - FlagsSafe | FlagDecodeOctalHost, - "http://66.102.7.147.:23/", - false, - }, - &testCase{ - "OctalIP-4", - "http://USER:pass@0102.0146.07.0223../", - FlagsSafe | FlagDecodeOctalHost, - "http://USER:pass@66.102.7.147../", - false, - }, - &testCase{ - "DWORDIP-1", - "http://123.1113982867/", - FlagsSafe | FlagDecodeDWORDHost, - "http://123.1113982867/", - false, - }, - &testCase{ - "DWORDIP-2", - "http://1113982867/", - FlagsSafe | FlagDecodeDWORDHost, - "http://66.102.7.147/", - false, - }, - &testCase{ - "DWORDIP-3", - "http://1113982867.:23/", - FlagsSafe | FlagDecodeDWORDHost, - "http://66.102.7.147.:23/", - false, - }, - &testCase{ - "DWORDIP-4", - "http://USER:pass@1113982867../", - FlagsSafe | FlagDecodeDWORDHost, - "http://USER:pass@66.102.7.147../", - false, - }, - &testCase{ - "HexIP-1", - "http://0x123.1113982867/", - FlagsSafe | FlagDecodeHexHost, - "http://0x123.1113982867/", - false, - }, - &testCase{ - "HexIP-2", - "http://0x42660793/", - FlagsSafe | FlagDecodeHexHost, - "http://66.102.7.147/", - false, - }, - &testCase{ - "HexIP-3", - "http://0x42660793.:23/", - FlagsSafe | FlagDecodeHexHost, - "http://66.102.7.147.:23/", - false, - }, - &testCase{ - "HexIP-4", - "http://USER:pass@0x42660793../", - FlagsSafe | FlagDecodeHexHost, - "http://USER:pass@66.102.7.147../", - false, - }, - &testCase{ - "UnnecessaryHostDots-1", - "http://.www.foo.com../foo/bar.html", - FlagsSafe | FlagRemoveUnnecessaryHostDots, - "http://www.foo.com/foo/bar.html", - false, - }, - &testCase{ - "UnnecessaryHostDots-2", - "http://www.foo.com./foo/bar.html", - FlagsSafe | FlagRemoveUnnecessaryHostDots, - "http://www.foo.com/foo/bar.html", - false, - }, - &testCase{ - "UnnecessaryHostDots-3", - "http://www.foo.com.:81/foo", - FlagsSafe | FlagRemoveUnnecessaryHostDots, - "http://www.foo.com:81/foo", - false, - }, - &testCase{ - "UnnecessaryHostDots-4", - "http://www.example.com./", - FlagsSafe | FlagRemoveUnnecessaryHostDots, - "http://www.example.com/", - false, - }, - &testCase{ - "EmptyPort-1", - "http://www.thedraymin.co.uk:/main/?p=308", - FlagsSafe | FlagRemoveEmptyPortSeparator, - "http://www.thedraymin.co.uk/main/?p=308", - false, - }, - &testCase{ - "EmptyPort-2", - "http://www.src.ca:", - FlagsSafe | FlagRemoveEmptyPortSeparator, - "http://www.src.ca", - false, - }, - &testCase{ - "Slashes-1", - "http://test.example/foo/bar/.", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/bar/", - false, - }, - &testCase{ - "Slashes-2", - "http://test.example/foo/bar/./", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/bar/", - false, - }, - &testCase{ - "Slashes-3", - "http://test.example/foo/bar/..", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/", - false, - }, - &testCase{ - "Slashes-4", - "http://test.example/foo/bar/../", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/", - false, - }, - &testCase{ - "Slashes-5", - "http://test.example/foo/bar/../baz", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/baz", - false, - }, - &testCase{ - "Slashes-6", - "http://test.example/foo/bar/../..", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/", - false, - }, - &testCase{ - "Slashes-7", - "http://test.example/foo/bar/../../", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/", - false, - }, - &testCase{ - "Slashes-8", - "http://test.example/foo/bar/../../baz", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/baz", - false, - }, - &testCase{ - "Slashes-9", - "http://test.example/foo/bar/../../../baz", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/baz", - false, - }, - &testCase{ - "Slashes-10", - "http://test.example/foo/bar/../../../../baz", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/baz", - false, - }, - &testCase{ - "Slashes-11", - "http://test.example/./foo", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo", - false, - }, - &testCase{ - "Slashes-12", - "http://test.example/../foo", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo", - false, - }, - &testCase{ - "Slashes-13", - "http://test.example/foo.", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo.", - false, - }, - &testCase{ - "Slashes-14", - "http://test.example/.foo", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/.foo", - false, - }, - &testCase{ - "Slashes-15", - "http://test.example/foo..", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo..", - false, - }, - &testCase{ - "Slashes-16", - "http://test.example/..foo", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/..foo", - false, - }, - &testCase{ - "Slashes-17", - "http://test.example/./../foo", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo", - false, - }, - &testCase{ - "Slashes-18", - "http://test.example/./foo/.", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/", - false, - }, - &testCase{ - "Slashes-19", - "http://test.example/foo/./bar", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/bar", - false, - }, - &testCase{ - "Slashes-20", - "http://test.example/foo/../bar", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/bar", - false, - }, - &testCase{ - "Slashes-21", - "http://test.example/foo//", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/", - false, - }, - &testCase{ - "Slashes-22", - "http://test.example/foo///bar//", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "http://test.example/foo/bar/", - false, - }, - &testCase{ - "Relative", - "foo/bar", - FlagsAllGreedy, - "foo/bar", - false, - }, - &testCase{ - "Relative-1", - "./../foo", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "foo", - false, - }, - &testCase{ - "Relative-2", - "./foo/bar/../baz/../bang/..", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "foo/", - false, - }, - &testCase{ - "Relative-3", - "foo///bar//", - FlagsSafe | FlagRemoveDotSegments | FlagRemoveDuplicateSlashes, - "foo/bar/", - false, - }, - &testCase{ - "Relative-4", - "www.youtube.com", - FlagsUsuallySafeGreedy, - "www.youtube.com", - false, - }, - /*&testCase{ - "UrlNorm-5", - "http://ja.wikipedia.org/wiki/%E3%82%AD%E3%83%A3%E3%82%BF%E3%83%94%E3%83%A9%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%91%E3%83%B3", - FlagsSafe | FlagRemoveDotSegments, - "http://ja.wikipedia.org/wiki/\xe3\x82\xad\xe3\x83\xa3\xe3\x82\xbf\xe3\x83\x94\xe3\x83\xa9\xe3\x83\xbc\xe3\x82\xb8\xe3\x83\xa3\xe3\x83\x91\xe3\x83\xb3", - false, - }, - &testCase{ - "UrlNorm-1", - "http://test.example/?a=%e3%82%82%26", - FlagsAllGreedy, - "http://test.example/?a=\xe3\x82\x82%26", - false, - },*/ - } -) - -func TestRunner(t *testing.T) { - for _, tc := range cases { - runCase(tc, t) - } -} - -func runCase(tc *testCase, t *testing.T) { - t.Logf("running %s...", tc.nm) - if tc.parsed { - u, e := url.Parse(tc.src) - if e != nil { - t.Errorf("%s - FAIL : %s", tc.nm, e) - return - } else { - NormalizeURL(u, tc.flgs) - if s := u.String(); s != tc.res { - t.Errorf("%s - FAIL expected '%s', got '%s'", tc.nm, tc.res, s) - } - } - } else { - if s, e := NormalizeURLString(tc.src, tc.flgs); e != nil { - t.Errorf("%s - FAIL : %s", tc.nm, e) - } else if s != tc.res { - t.Errorf("%s - FAIL expected '%s', got '%s'", tc.nm, tc.res, s) - } - } -} - -func TestDecodeUnnecessaryEscapesAll(t *testing.T) { - var url = "http://host/" - - for i := 0; i < 256; i++ { - url += fmt.Sprintf("%%%02x", i) - } - if s, e := NormalizeURLString(url, FlagDecodeUnnecessaryEscapes); e != nil { - t.Fatalf("Got error %s", e.Error()) - } else { - const want = "http://host/%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20!%22%23$%25&'()*+,-./0123456789:;%3C=%3E%3F@ABCDEFGHIJKLMNOPQRSTUVWXYZ[%5C]%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D~%7F%80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF" - if s != want { - t.Errorf("DecodeUnnecessaryEscapesAll:\nwant\n%s\ngot\n%s", want, s) - } - } -} - -func TestEncodeNecessaryEscapesAll(t *testing.T) { - var url = "http://host/" - - for i := 0; i < 256; i++ { - if i != 0x25 { - url += string(i) - } - } - if s, e := NormalizeURLString(url, FlagEncodeNecessaryEscapes); e != nil { - t.Fatalf("Got error %s", e.Error()) - } else { - const want = "http://host/%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20!%22#$&'()*+,-./0123456789:;%3C=%3E?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[%5C]%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D~%7F%C2%80%C2%81%C2%82%C2%83%C2%84%C2%85%C2%86%C2%87%C2%88%C2%89%C2%8A%C2%8B%C2%8C%C2%8D%C2%8E%C2%8F%C2%90%C2%91%C2%92%C2%93%C2%94%C2%95%C2%96%C2%97%C2%98%C2%99%C2%9A%C2%9B%C2%9C%C2%9D%C2%9E%C2%9F%C2%A0%C2%A1%C2%A2%C2%A3%C2%A4%C2%A5%C2%A6%C2%A7%C2%A8%C2%A9%C2%AA%C2%AB%C2%AC%C2%AD%C2%AE%C2%AF%C2%B0%C2%B1%C2%B2%C2%B3%C2%B4%C2%B5%C2%B6%C2%B7%C2%B8%C2%B9%C2%BA%C2%BB%C2%BC%C2%BD%C2%BE%C2%BF%C3%80%C3%81%C3%82%C3%83%C3%84%C3%85%C3%86%C3%87%C3%88%C3%89%C3%8A%C3%8B%C3%8C%C3%8D%C3%8E%C3%8F%C3%90%C3%91%C3%92%C3%93%C3%94%C3%95%C3%96%C3%97%C3%98%C3%99%C3%9A%C3%9B%C3%9C%C3%9D%C3%9E%C3%9F%C3%A0%C3%A1%C3%A2%C3%A3%C3%A4%C3%A5%C3%A6%C3%A7%C3%A8%C3%A9%C3%AA%C3%AB%C3%AC%C3%AD%C3%AE%C3%AF%C3%B0%C3%B1%C3%B2%C3%B3%C3%B4%C3%B5%C3%B6%C3%B7%C3%B8%C3%B9%C3%BA%C3%BB%C3%BC%C3%BD%C3%BE%C3%BF" - if s != want { - t.Errorf("EncodeNecessaryEscapesAll:\nwant\n%s\ngot\n%s", want, s) - } - } -} diff --git a/vendor/github.com/PuerkitoBio/purell/urlnorm_test.go b/vendor/github.com/PuerkitoBio/purell/urlnorm_test.go deleted file mode 100644 index d1b2ca6c0..000000000 --- a/vendor/github.com/PuerkitoBio/purell/urlnorm_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package purell - -import ( - "testing" -) - -// Test cases merged from PR #1 -// Originally from https://github.com/jehiah/urlnorm/blob/master/test_urlnorm.py - -func assertMap(t *testing.T, cases map[string]string, f NormalizationFlags) { - for bad, good := range cases { - s, e := NormalizeURLString(bad, f) - if e != nil { - t.Errorf("%s normalizing %v to %v", e.Error(), bad, good) - } else { - if s != good { - t.Errorf("source: %v expected: %v got: %v", bad, good, s) - } - } - } -} - -// This tests normalization to a unicode representation -// precent escapes for unreserved values are unescaped to their unicode value -// tests normalization to idna domains -// test ip word handling, ipv6 address handling, and trailing domain periods -// in general, this matches google chromes unescaping for things in the address bar. -// spaces are converted to '+' (perhaphs controversial) -// http://code.google.com/p/google-url/ probably is another good reference for this approach -func TestUrlnorm(t *testing.T) { - testcases := map[string]string{ - "http://test.example/?a=%e3%82%82%26": "http://test.example/?a=%e3%82%82%26", - //"http://test.example/?a=%e3%82%82%26": "http://test.example/?a=\xe3\x82\x82%26", //should return a unicode character - "http://s.xn--q-bga.DE/": "http://s.xn--q-bga.de/", //should be in idna format - "http://XBLA\u306eXbox.com": "http://xn--xblaxbox-jf4g.com", //test utf8 and unicode - "http://президент.рф": "http://xn--d1abbgf6aiiy.xn--p1ai", - "http://ПРЕЗИДЕНТ.РФ": "http://xn--d1abbgf6aiiy.xn--p1ai", - "http://ab¥ヲ₩○.com": "http://xn--ab-ida8983azmfnvs.com", //test width folding - "http://\u00e9.com": "http://xn--9ca.com", - "http://e\u0301.com": "http://xn--9ca.com", - "http://ja.wikipedia.org/wiki/%E3%82%AD%E3%83%A3%E3%82%BF%E3%83%94%E3%83%A9%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%91%E3%83%B3": "http://ja.wikipedia.org/wiki/%E3%82%AD%E3%83%A3%E3%82%BF%E3%83%94%E3%83%A9%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%91%E3%83%B3", - //"http://ja.wikipedia.org/wiki/%E3%82%AD%E3%83%A3%E3%82%BF%E3%83%94%E3%83%A9%E3%83%BC%E3%82%B8%E3%83%A3%E3%83%91%E3%83%B3": "http://ja.wikipedia.org/wiki/\xe3\x82\xad\xe3\x83\xa3\xe3\x82\xbf\xe3\x83\x94\xe3\x83\xa9\xe3\x83\xbc\xe3\x82\xb8\xe3\x83\xa3\xe3\x83\x91\xe3\x83\xb3", - - "http://test.example/\xe3\x82\xad": "http://test.example/%E3%82%AD", - //"http://test.example/\xe3\x82\xad": "http://test.example/\xe3\x82\xad", - "http://test.example/?p=%23val#test-%23-val%25": "http://test.example/?p=%23val#test-%23-val%25", //check that %23 (#) is not escaped where it shouldn't be - - "http://test.domain/I%C3%B1t%C3%ABrn%C3%A2ti%C3%B4n%EF%BF%BDliz%C3%A6ti%C3%B8n": "http://test.domain/I%C3%B1t%C3%ABrn%C3%A2ti%C3%B4n%EF%BF%BDliz%C3%A6ti%C3%B8n", - //"http://test.domain/I%C3%B1t%C3%ABrn%C3%A2ti%C3%B4n%EF%BF%BDliz%C3%A6ti%C3%B8n": "http://test.domain/I\xc3\xb1t\xc3\xabrn\xc3\xa2ti\xc3\xb4n\xef\xbf\xbdliz\xc3\xa6ti\xc3\xb8n", - } - - assertMap(t, testcases, FlagsSafe|FlagRemoveDotSegments) -} diff --git a/vendor/github.com/PuerkitoBio/urlesc/.travis.yml b/vendor/github.com/PuerkitoBio/urlesc/.travis.yml deleted file mode 100644 index ba6b225f9..000000000 --- a/vendor/github.com/PuerkitoBio/urlesc/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -language: go - -go: - - 1.4.x - - 1.5.x - - 1.6.x - - 1.7.x - - 1.8.x - - tip - -install: - - go build . - -script: - - go test -v diff --git a/vendor/github.com/PuerkitoBio/urlesc/LICENSE b/vendor/github.com/PuerkitoBio/urlesc/LICENSE deleted file mode 100644 index 744875676..000000000 --- a/vendor/github.com/PuerkitoBio/urlesc/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 The Go 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. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -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 -OWNER 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/PuerkitoBio/urlesc/README.md b/vendor/github.com/PuerkitoBio/urlesc/README.md deleted file mode 100644 index 57aff0a53..000000000 --- a/vendor/github.com/PuerkitoBio/urlesc/README.md +++ /dev/null @@ -1,16 +0,0 @@ -urlesc [![Build Status](https://travis-ci.org/PuerkitoBio/urlesc.svg?branch=master)](https://travis-ci.org/PuerkitoBio/urlesc) [![GoDoc](http://godoc.org/github.com/PuerkitoBio/urlesc?status.svg)](http://godoc.org/github.com/PuerkitoBio/urlesc) -====== - -Package urlesc implements query escaping as per RFC 3986. - -It contains some parts of the net/url package, modified so as to allow -some reserved characters incorrectly escaped by net/url (see [issue 5684](https://github.com/golang/go/issues/5684)). - -## Install - - go get github.com/PuerkitoBio/urlesc - -## License - -Go license (BSD-3-Clause) - diff --git a/vendor/github.com/PuerkitoBio/urlesc/urlesc.go b/vendor/github.com/PuerkitoBio/urlesc/urlesc.go deleted file mode 100644 index 1b8462459..000000000 --- a/vendor/github.com/PuerkitoBio/urlesc/urlesc.go +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright 2009 The Go 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 urlesc implements query escaping as per RFC 3986. -// It contains some parts of the net/url package, modified so as to allow -// some reserved characters incorrectly escaped by net/url. -// See https://github.com/golang/go/issues/5684 -package urlesc - -import ( - "bytes" - "net/url" - "strings" -) - -type encoding int - -const ( - encodePath encoding = 1 + iota - encodeUserPassword - encodeQueryComponent - encodeFragment -) - -// Return true if the specified character should be escaped when -// appearing in a URL string, according to RFC 3986. -func shouldEscape(c byte, mode encoding) bool { - // §2.3 Unreserved characters (alphanum) - if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' { - return false - } - - switch c { - case '-', '.', '_', '~': // §2.3 Unreserved characters (mark) - return false - - // §2.2 Reserved characters (reserved) - case ':', '/', '?', '#', '[', ']', '@', // gen-delims - '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=': // sub-delims - // Different sections of the URL allow a few of - // the reserved characters to appear unescaped. - switch mode { - case encodePath: // §3.3 - // The RFC allows sub-delims and : @. - // '/', '[' and ']' can be used to assign meaning to individual path - // segments. This package only manipulates the path as a whole, - // so we allow those as well. That leaves only ? and # to escape. - return c == '?' || c == '#' - - case encodeUserPassword: // §3.2.1 - // The RFC allows : and sub-delims in - // userinfo. The parsing of userinfo treats ':' as special so we must escape - // all the gen-delims. - return c == ':' || c == '/' || c == '?' || c == '#' || c == '[' || c == ']' || c == '@' - - case encodeQueryComponent: // §3.4 - // The RFC allows / and ?. - return c != '/' && c != '?' - - case encodeFragment: // §4.1 - // The RFC text is silent but the grammar allows - // everything, so escape nothing but # - return c == '#' - } - } - - // Everything else must be escaped. - return true -} - -// QueryEscape escapes the string so it can be safely placed -// inside a URL query. -func QueryEscape(s string) string { - return escape(s, encodeQueryComponent) -} - -func escape(s string, mode encoding) string { - spaceCount, hexCount := 0, 0 - for i := 0; i < len(s); i++ { - c := s[i] - if shouldEscape(c, mode) { - if c == ' ' && mode == encodeQueryComponent { - spaceCount++ - } else { - hexCount++ - } - } - } - - if spaceCount == 0 && hexCount == 0 { - return s - } - - t := make([]byte, len(s)+2*hexCount) - j := 0 - for i := 0; i < len(s); i++ { - switch c := s[i]; { - case c == ' ' && mode == encodeQueryComponent: - t[j] = '+' - j++ - case shouldEscape(c, mode): - t[j] = '%' - t[j+1] = "0123456789ABCDEF"[c>>4] - t[j+2] = "0123456789ABCDEF"[c&15] - j += 3 - default: - t[j] = s[i] - j++ - } - } - return string(t) -} - -var uiReplacer = strings.NewReplacer( - "%21", "!", - "%27", "'", - "%28", "(", - "%29", ")", - "%2A", "*", -) - -// unescapeUserinfo unescapes some characters that need not to be escaped as per RFC3986. -func unescapeUserinfo(s string) string { - return uiReplacer.Replace(s) -} - -// Escape reassembles the URL into a valid URL string. -// The general form of the result is one of: -// -// scheme:opaque -// scheme://userinfo@host/path?query#fragment -// -// If u.Opaque is non-empty, String uses the first form; -// otherwise it uses the second form. -// -// In the second form, the following rules apply: -// - if u.Scheme is empty, scheme: is omitted. -// - if u.User is nil, userinfo@ is omitted. -// - if u.Host is empty, host/ is omitted. -// - if u.Scheme and u.Host are empty and u.User is nil, -// the entire scheme://userinfo@host/ is omitted. -// - if u.Host is non-empty and u.Path begins with a /, -// the form host/path does not add its own /. -// - if u.RawQuery is empty, ?query is omitted. -// - if u.Fragment is empty, #fragment is omitted. -func Escape(u *url.URL) string { - var buf bytes.Buffer - if u.Scheme != "" { - buf.WriteString(u.Scheme) - buf.WriteByte(':') - } - if u.Opaque != "" { - buf.WriteString(u.Opaque) - } else { - if u.Scheme != "" || u.Host != "" || u.User != nil { - buf.WriteString("//") - if ui := u.User; ui != nil { - buf.WriteString(unescapeUserinfo(ui.String())) - buf.WriteByte('@') - } - if h := u.Host; h != "" { - buf.WriteString(h) - } - } - if u.Path != "" && u.Path[0] != '/' && u.Host != "" { - buf.WriteByte('/') - } - buf.WriteString(escape(u.Path, encodePath)) - } - if u.RawQuery != "" { - buf.WriteByte('?') - buf.WriteString(u.RawQuery) - } - if u.Fragment != "" { - buf.WriteByte('#') - buf.WriteString(escape(u.Fragment, encodeFragment)) - } - return buf.String() -} diff --git a/vendor/github.com/PuerkitoBio/urlesc/urlesc_test.go b/vendor/github.com/PuerkitoBio/urlesc/urlesc_test.go deleted file mode 100644 index 45202e1dd..000000000 --- a/vendor/github.com/PuerkitoBio/urlesc/urlesc_test.go +++ /dev/null @@ -1,641 +0,0 @@ -// Copyright 2009 The Go 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 urlesc - -import ( - "net/url" - "testing" -) - -type URLTest struct { - in string - out *url.URL - roundtrip string // expected result of reserializing the URL; empty means same as "in". -} - -var urltests = []URLTest{ - // no path - { - "http://www.google.com", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - }, - "", - }, - // path - { - "http://www.google.com/", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "/", - }, - "", - }, - // path with hex escaping - { - "http://www.google.com/file%20one%26two", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "/file one&two", - }, - "http://www.google.com/file%20one&two", - }, - // user - { - "ftp://webmaster@www.google.com/", - &url.URL{ - Scheme: "ftp", - User: url.User("webmaster"), - Host: "www.google.com", - Path: "/", - }, - "", - }, - // escape sequence in username - { - "ftp://john%20doe@www.google.com/", - &url.URL{ - Scheme: "ftp", - User: url.User("john doe"), - Host: "www.google.com", - Path: "/", - }, - "ftp://john%20doe@www.google.com/", - }, - // query - { - "http://www.google.com/?q=go+language", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "/", - RawQuery: "q=go+language", - }, - "", - }, - // query with hex escaping: NOT parsed - { - "http://www.google.com/?q=go%20language", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "/", - RawQuery: "q=go%20language", - }, - "", - }, - // %20 outside query - { - "http://www.google.com/a%20b?q=c+d", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "/a b", - RawQuery: "q=c+d", - }, - "", - }, - // path without leading /, so no parsing - { - "http:www.google.com/?q=go+language", - &url.URL{ - Scheme: "http", - Opaque: "www.google.com/", - RawQuery: "q=go+language", - }, - "http:www.google.com/?q=go+language", - }, - // path without leading /, so no parsing - { - "http:%2f%2fwww.google.com/?q=go+language", - &url.URL{ - Scheme: "http", - Opaque: "%2f%2fwww.google.com/", - RawQuery: "q=go+language", - }, - "http:%2f%2fwww.google.com/?q=go+language", - }, - // non-authority with path - { - "mailto:/webmaster@golang.org", - &url.URL{ - Scheme: "mailto", - Path: "/webmaster@golang.org", - }, - "mailto:///webmaster@golang.org", // unfortunate compromise - }, - // non-authority - { - "mailto:webmaster@golang.org", - &url.URL{ - Scheme: "mailto", - Opaque: "webmaster@golang.org", - }, - "", - }, - // unescaped :// in query should not create a scheme - { - "/foo?query=http://bad", - &url.URL{ - Path: "/foo", - RawQuery: "query=http://bad", - }, - "", - }, - // leading // without scheme should create an authority - { - "//foo", - &url.URL{ - Host: "foo", - }, - "", - }, - // leading // without scheme, with userinfo, path, and query - { - "//user@foo/path?a=b", - &url.URL{ - User: url.User("user"), - Host: "foo", - Path: "/path", - RawQuery: "a=b", - }, - "", - }, - // Three leading slashes isn't an authority, but doesn't return an error. - // (We can't return an error, as this code is also used via - // ServeHTTP -> ReadRequest -> Parse, which is arguably a - // different URL parsing context, but currently shares the - // same codepath) - { - "///threeslashes", - &url.URL{ - Path: "///threeslashes", - }, - "", - }, - { - "http://user:password@google.com", - &url.URL{ - Scheme: "http", - User: url.UserPassword("user", "password"), - Host: "google.com", - }, - "http://user:password@google.com", - }, - // unescaped @ in username should not confuse host - { - "http://j@ne:password@google.com", - &url.URL{ - Scheme: "http", - User: url.UserPassword("j@ne", "password"), - Host: "google.com", - }, - "http://j%40ne:password@google.com", - }, - // unescaped @ in password should not confuse host - { - "http://jane:p@ssword@google.com", - &url.URL{ - Scheme: "http", - User: url.UserPassword("jane", "p@ssword"), - Host: "google.com", - }, - "http://jane:p%40ssword@google.com", - }, - { - "http://j@ne:password@google.com/p@th?q=@go", - &url.URL{ - Scheme: "http", - User: url.UserPassword("j@ne", "password"), - Host: "google.com", - Path: "/p@th", - RawQuery: "q=@go", - }, - "http://j%40ne:password@google.com/p@th?q=@go", - }, - { - "http://www.google.com/?q=go+language#foo", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "/", - RawQuery: "q=go+language", - Fragment: "foo", - }, - "", - }, - { - "http://www.google.com/?q=go+language#foo%26bar", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "/", - RawQuery: "q=go+language", - Fragment: "foo&bar", - }, - "http://www.google.com/?q=go+language#foo&bar", - }, - { - "file:///home/adg/rabbits", - &url.URL{ - Scheme: "file", - Host: "", - Path: "/home/adg/rabbits", - }, - "file:///home/adg/rabbits", - }, - // "Windows" paths are no exception to the rule. - // See golang.org/issue/6027, especially comment #9. - { - "file:///C:/FooBar/Baz.txt", - &url.URL{ - Scheme: "file", - Host: "", - Path: "/C:/FooBar/Baz.txt", - }, - "file:///C:/FooBar/Baz.txt", - }, - // case-insensitive scheme - { - "MaIlTo:webmaster@golang.org", - &url.URL{ - Scheme: "mailto", - Opaque: "webmaster@golang.org", - }, - "mailto:webmaster@golang.org", - }, - // Relative path - { - "a/b/c", - &url.URL{ - Path: "a/b/c", - }, - "a/b/c", - }, - // escaped '?' in username and password - { - "http://%3Fam:pa%3Fsword@google.com", - &url.URL{ - Scheme: "http", - User: url.UserPassword("?am", "pa?sword"), - Host: "google.com", - }, - "", - }, - // escaped '?' and '#' in path - { - "http://example.com/%3F%23", - &url.URL{ - Scheme: "http", - Host: "example.com", - Path: "?#", - }, - "", - }, - // unescaped [ ] ! ' ( ) * in path - { - "http://example.com/[]!'()*", - &url.URL{ - Scheme: "http", - Host: "example.com", - Path: "[]!'()*", - }, - "http://example.com/[]!'()*", - }, - // escaped : / ? # [ ] @ in username and password - { - "http://%3A%2F%3F:%23%5B%5D%40@example.com", - &url.URL{ - Scheme: "http", - User: url.UserPassword(":/?", "#[]@"), - Host: "example.com", - }, - "", - }, - // unescaped ! $ & ' ( ) * + , ; = in username and password - { - "http://!$&'():*+,;=@example.com", - &url.URL{ - Scheme: "http", - User: url.UserPassword("!$&'()", "*+,;="), - Host: "example.com", - }, - "", - }, - // unescaped = : / . ? = in query component - { - "http://example.com/?q=http://google.com/?q=", - &url.URL{ - Scheme: "http", - Host: "example.com", - Path: "/", - RawQuery: "q=http://google.com/?q=", - }, - "", - }, - // unescaped : / ? [ ] @ ! $ & ' ( ) * + , ; = in fragment - { - "http://example.com/#:/?%23[]@!$&'()*+,;=", - &url.URL{ - Scheme: "http", - Host: "example.com", - Path: "/", - Fragment: ":/?#[]@!$&'()*+,;=", - }, - "", - }, -} - -func DoTestString(t *testing.T, parse func(string) (*url.URL, error), name string, tests []URLTest) { - for _, tt := range tests { - u, err := parse(tt.in) - if err != nil { - t.Errorf("%s(%q) returned error %s", name, tt.in, err) - continue - } - expected := tt.in - if len(tt.roundtrip) > 0 { - expected = tt.roundtrip - } - s := Escape(u) - if s != expected { - t.Errorf("Escape(%s(%q)) == %q (expected %q)", name, tt.in, s, expected) - } - } -} - -func TestURLString(t *testing.T) { - DoTestString(t, url.Parse, "Parse", urltests) - - // no leading slash on path should prepend - // slash on String() call - noslash := URLTest{ - "http://www.google.com/search", - &url.URL{ - Scheme: "http", - Host: "www.google.com", - Path: "search", - }, - "", - } - s := Escape(noslash.out) - if s != noslash.in { - t.Errorf("Expected %s; go %s", noslash.in, s) - } -} - -type EscapeTest struct { - in string - out string - err error -} - -var escapeTests = []EscapeTest{ - { - "", - "", - nil, - }, - { - "abc", - "abc", - nil, - }, - { - "one two", - "one+two", - nil, - }, - { - "10%", - "10%25", - nil, - }, - { - " ?&=#+%!<>#\"{}|\\^[]`☺\t:/@$'()*,;", - "+?%26%3D%23%2B%25%21%3C%3E%23%22%7B%7D%7C%5C%5E%5B%5D%60%E2%98%BA%09%3A/%40%24%27%28%29%2A%2C%3B", - nil, - }, -} - -func TestEscape(t *testing.T) { - for _, tt := range escapeTests { - actual := QueryEscape(tt.in) - if tt.out != actual { - t.Errorf("QueryEscape(%q) = %q, want %q", tt.in, actual, tt.out) - } - - // for bonus points, verify that escape:unescape is an identity. - roundtrip, err := url.QueryUnescape(actual) - if roundtrip != tt.in || err != nil { - t.Errorf("QueryUnescape(%q) = %q, %s; want %q, %s", actual, roundtrip, err, tt.in, "[no error]") - } - } -} - -var resolveReferenceTests = []struct { - base, rel, expected string -}{ - // Absolute URL references - {"http://foo.com?a=b", "https://bar.com/", "https://bar.com/"}, - {"http://foo.com/", "https://bar.com/?a=b", "https://bar.com/?a=b"}, - {"http://foo.com/bar", "mailto:foo@example.com", "mailto:foo@example.com"}, - - // Path-absolute references - {"http://foo.com/bar", "/baz", "http://foo.com/baz"}, - {"http://foo.com/bar?a=b#f", "/baz", "http://foo.com/baz"}, - {"http://foo.com/bar?a=b", "/baz?c=d", "http://foo.com/baz?c=d"}, - - // Scheme-relative - {"https://foo.com/bar?a=b", "//bar.com/quux", "https://bar.com/quux"}, - - // Path-relative references: - - // ... current directory - {"http://foo.com", ".", "http://foo.com/"}, - {"http://foo.com/bar", ".", "http://foo.com/"}, - {"http://foo.com/bar/", ".", "http://foo.com/bar/"}, - - // ... going down - {"http://foo.com", "bar", "http://foo.com/bar"}, - {"http://foo.com/", "bar", "http://foo.com/bar"}, - {"http://foo.com/bar/baz", "quux", "http://foo.com/bar/quux"}, - - // ... going up - {"http://foo.com/bar/baz", "../quux", "http://foo.com/quux"}, - {"http://foo.com/bar/baz", "../../../../../quux", "http://foo.com/quux"}, - {"http://foo.com/bar", "..", "http://foo.com/"}, - {"http://foo.com/bar/baz", "./..", "http://foo.com/"}, - // ".." in the middle (issue 3560) - {"http://foo.com/bar/baz", "quux/dotdot/../tail", "http://foo.com/bar/quux/tail"}, - {"http://foo.com/bar/baz", "quux/./dotdot/../tail", "http://foo.com/bar/quux/tail"}, - {"http://foo.com/bar/baz", "quux/./dotdot/.././tail", "http://foo.com/bar/quux/tail"}, - {"http://foo.com/bar/baz", "quux/./dotdot/./../tail", "http://foo.com/bar/quux/tail"}, - {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/././../../tail", "http://foo.com/bar/quux/tail"}, - {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/./.././../tail", "http://foo.com/bar/quux/tail"}, - {"http://foo.com/bar/baz", "quux/./dotdot/dotdot/dotdot/./../../.././././tail", "http://foo.com/bar/quux/tail"}, - {"http://foo.com/bar/baz", "quux/./dotdot/../dotdot/../dot/./tail/..", "http://foo.com/bar/quux/dot/"}, - - // Remove any dot-segments prior to forming the target URI. - // http://tools.ietf.org/html/rfc3986#section-5.2.4 - {"http://foo.com/dot/./dotdot/../foo/bar", "../baz", "http://foo.com/dot/baz"}, - - // Triple dot isn't special - {"http://foo.com/bar", "...", "http://foo.com/..."}, - - // Fragment - {"http://foo.com/bar", ".#frag", "http://foo.com/#frag"}, - - // RFC 3986: Normal Examples - // http://tools.ietf.org/html/rfc3986#section-5.4.1 - {"http://a/b/c/d;p?q", "g:h", "g:h"}, - {"http://a/b/c/d;p?q", "g", "http://a/b/c/g"}, - {"http://a/b/c/d;p?q", "./g", "http://a/b/c/g"}, - {"http://a/b/c/d;p?q", "g/", "http://a/b/c/g/"}, - {"http://a/b/c/d;p?q", "/g", "http://a/g"}, - {"http://a/b/c/d;p?q", "//g", "http://g"}, - {"http://a/b/c/d;p?q", "?y", "http://a/b/c/d;p?y"}, - {"http://a/b/c/d;p?q", "g?y", "http://a/b/c/g?y"}, - {"http://a/b/c/d;p?q", "#s", "http://a/b/c/d;p?q#s"}, - {"http://a/b/c/d;p?q", "g#s", "http://a/b/c/g#s"}, - {"http://a/b/c/d;p?q", "g?y#s", "http://a/b/c/g?y#s"}, - {"http://a/b/c/d;p?q", ";x", "http://a/b/c/;x"}, - {"http://a/b/c/d;p?q", "g;x", "http://a/b/c/g;x"}, - {"http://a/b/c/d;p?q", "g;x?y#s", "http://a/b/c/g;x?y#s"}, - {"http://a/b/c/d;p?q", "", "http://a/b/c/d;p?q"}, - {"http://a/b/c/d;p?q", ".", "http://a/b/c/"}, - {"http://a/b/c/d;p?q", "./", "http://a/b/c/"}, - {"http://a/b/c/d;p?q", "..", "http://a/b/"}, - {"http://a/b/c/d;p?q", "../", "http://a/b/"}, - {"http://a/b/c/d;p?q", "../g", "http://a/b/g"}, - {"http://a/b/c/d;p?q", "../..", "http://a/"}, - {"http://a/b/c/d;p?q", "../../", "http://a/"}, - {"http://a/b/c/d;p?q", "../../g", "http://a/g"}, - - // RFC 3986: Abnormal Examples - // http://tools.ietf.org/html/rfc3986#section-5.4.2 - {"http://a/b/c/d;p?q", "../../../g", "http://a/g"}, - {"http://a/b/c/d;p?q", "../../../../g", "http://a/g"}, - {"http://a/b/c/d;p?q", "/./g", "http://a/g"}, - {"http://a/b/c/d;p?q", "/../g", "http://a/g"}, - {"http://a/b/c/d;p?q", "g.", "http://a/b/c/g."}, - {"http://a/b/c/d;p?q", ".g", "http://a/b/c/.g"}, - {"http://a/b/c/d;p?q", "g..", "http://a/b/c/g.."}, - {"http://a/b/c/d;p?q", "..g", "http://a/b/c/..g"}, - {"http://a/b/c/d;p?q", "./../g", "http://a/b/g"}, - {"http://a/b/c/d;p?q", "./g/.", "http://a/b/c/g/"}, - {"http://a/b/c/d;p?q", "g/./h", "http://a/b/c/g/h"}, - {"http://a/b/c/d;p?q", "g/../h", "http://a/b/c/h"}, - {"http://a/b/c/d;p?q", "g;x=1/./y", "http://a/b/c/g;x=1/y"}, - {"http://a/b/c/d;p?q", "g;x=1/../y", "http://a/b/c/y"}, - {"http://a/b/c/d;p?q", "g?y/./x", "http://a/b/c/g?y/./x"}, - {"http://a/b/c/d;p?q", "g?y/../x", "http://a/b/c/g?y/../x"}, - {"http://a/b/c/d;p?q", "g#s/./x", "http://a/b/c/g#s/./x"}, - {"http://a/b/c/d;p?q", "g#s/../x", "http://a/b/c/g#s/../x"}, - - // Extras. - {"https://a/b/c/d;p?q", "//g?q", "https://g?q"}, - {"https://a/b/c/d;p?q", "//g#s", "https://g#s"}, - {"https://a/b/c/d;p?q", "//g/d/e/f?y#s", "https://g/d/e/f?y#s"}, - {"https://a/b/c/d;p#s", "?y", "https://a/b/c/d;p?y"}, - {"https://a/b/c/d;p?q#s", "?y", "https://a/b/c/d;p?y"}, -} - -func TestResolveReference(t *testing.T) { - mustParse := func(url_ string) *url.URL { - u, err := url.Parse(url_) - if err != nil { - t.Fatalf("Expected URL to parse: %q, got error: %v", url_, err) - } - return u - } - opaque := &url.URL{Scheme: "scheme", Opaque: "opaque"} - for _, test := range resolveReferenceTests { - base := mustParse(test.base) - rel := mustParse(test.rel) - url := base.ResolveReference(rel) - if Escape(url) != test.expected { - t.Errorf("URL(%q).ResolveReference(%q) == %q, got %q", test.base, test.rel, test.expected, Escape(url)) - } - // Ensure that new instances are returned. - if base == url { - t.Errorf("Expected URL.ResolveReference to return new URL instance.") - } - // Test the convenience wrapper too. - url, err := base.Parse(test.rel) - if err != nil { - t.Errorf("URL(%q).Parse(%q) failed: %v", test.base, test.rel, err) - } else if Escape(url) != test.expected { - t.Errorf("URL(%q).Parse(%q) == %q, got %q", test.base, test.rel, test.expected, Escape(url)) - } else if base == url { - // Ensure that new instances are returned for the wrapper too. - t.Errorf("Expected URL.Parse to return new URL instance.") - } - // Ensure Opaque resets the URL. - url = base.ResolveReference(opaque) - if *url != *opaque { - t.Errorf("ResolveReference failed to resolve opaque URL: want %#v, got %#v", url, opaque) - } - // Test the convenience wrapper with an opaque URL too. - url, err = base.Parse("scheme:opaque") - if err != nil { - t.Errorf(`URL(%q).Parse("scheme:opaque") failed: %v`, test.base, err) - } else if *url != *opaque { - t.Errorf("Parse failed to resolve opaque URL: want %#v, got %#v", url, opaque) - } else if base == url { - // Ensure that new instances are returned, again. - t.Errorf("Expected URL.Parse to return new URL instance.") - } - } -} - -type shouldEscapeTest struct { - in byte - mode encoding - escape bool -} - -var shouldEscapeTests = []shouldEscapeTest{ - // Unreserved characters (§2.3) - {'a', encodePath, false}, - {'a', encodeUserPassword, false}, - {'a', encodeQueryComponent, false}, - {'a', encodeFragment, false}, - {'z', encodePath, false}, - {'A', encodePath, false}, - {'Z', encodePath, false}, - {'0', encodePath, false}, - {'9', encodePath, false}, - {'-', encodePath, false}, - {'-', encodeUserPassword, false}, - {'-', encodeQueryComponent, false}, - {'-', encodeFragment, false}, - {'.', encodePath, false}, - {'_', encodePath, false}, - {'~', encodePath, false}, - - // User information (§3.2.1) - {':', encodeUserPassword, true}, - {'/', encodeUserPassword, true}, - {'?', encodeUserPassword, true}, - {'@', encodeUserPassword, true}, - {'$', encodeUserPassword, false}, - {'&', encodeUserPassword, false}, - {'+', encodeUserPassword, false}, - {',', encodeUserPassword, false}, - {';', encodeUserPassword, false}, - {'=', encodeUserPassword, false}, -} - -func TestShouldEscape(t *testing.T) { - for _, tt := range shouldEscapeTests { - if shouldEscape(tt.in, tt.mode) != tt.escape { - t.Errorf("shouldEscape(%q, %v) returned %v; expected %v", tt.in, tt.mode, !tt.escape, tt.escape) - } - } -} diff --git a/vendor/github.com/asaskevich/govalidator/.github/ISSUE_TEMPLATE.md b/vendor/github.com/asaskevich/govalidator/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 12acb3e29..000000000 --- a/vendor/github.com/asaskevich/govalidator/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,2 +0,0 @@ - \ No newline at end of file diff --git a/vendor/github.com/asaskevich/govalidator/.travis.yml b/vendor/github.com/asaskevich/govalidator/.travis.yml deleted file mode 100644 index e29f8eef5..000000000 --- a/vendor/github.com/asaskevich/govalidator/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: go - -go: - - 1.1 - - 1.2 - - 1.3 - - 1.4 - - 1.5 - - 1.6 - - tip - -notifications: - email: - - bwatas@gmail.com diff --git a/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md b/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md deleted file mode 100644 index f0f7e3a8a..000000000 --- a/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md +++ /dev/null @@ -1,63 +0,0 @@ -#### Support -If you do have a contribution to the package, feel free to create a Pull Request or an Issue. - -#### What to contribute -If you don't know what to do, there are some features and functions that need to be done - -- [ ] Refactor code -- [ ] Edit docs and [README](https://github.com/asaskevich/govalidator/README.md): spellcheck, grammar and typo check -- [ ] Create actual list of contributors and projects that currently using this package -- [ ] Resolve [issues and bugs](https://github.com/asaskevich/govalidator/issues) -- [ ] Update actual [list of functions](https://github.com/asaskevich/govalidator#list-of-functions) -- [ ] Update [list of validators](https://github.com/asaskevich/govalidator#validatestruct-2) that available for `ValidateStruct` and add new -- [ ] Implement new validators: `IsFQDN`, `IsIMEI`, `IsPostalCode`, `IsISIN`, `IsISRC` etc -- [ ] Implement [validation by maps](https://github.com/asaskevich/govalidator/issues/224) -- [ ] Implement fuzzing testing -- [ ] Implement some struct/map/array utilities -- [ ] Implement map/array validation -- [ ] Implement benchmarking -- [ ] Implement batch of examples -- [ ] Look at forks for new features and fixes - -#### Advice -Feel free to create what you want, but keep in mind when you implement new features: -- Code must be clear and readable, names of variables/constants clearly describes what they are doing -- Public functions must be documented and described in source file and added to README.md to the list of available functions -- There are must be unit-tests for any new functions and improvements - -## Financial contributions - -We also welcome financial contributions in full transparency on our [open collective](https://opencollective.com/govalidator). -Anyone can file an expense. If the expense makes sense for the development of the community, it will be "merged" in the ledger of our open collective by the core contributors and the person who filed the expense will be reimbursed. - - -## Credits - - -### Contributors - -Thank you to all the people who have already contributed to govalidator! - - - -### Backers - -Thank you to all our backers! [[Become a backer](https://opencollective.com/govalidator#backer)] - - - - -### Sponsors - -Thank you to all our sponsors! (please ask your company to also support this open source project by [becoming a sponsor](https://opencollective.com/govalidator#sponsor)) - - - - - - - - - - - \ No newline at end of file diff --git a/vendor/github.com/asaskevich/govalidator/LICENSE b/vendor/github.com/asaskevich/govalidator/LICENSE deleted file mode 100644 index 2f9a31fad..000000000 --- a/vendor/github.com/asaskevich/govalidator/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Alex Saskevich - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/asaskevich/govalidator/README.md b/vendor/github.com/asaskevich/govalidator/README.md deleted file mode 100644 index efd8e64aa..000000000 --- a/vendor/github.com/asaskevich/govalidator/README.md +++ /dev/null @@ -1,490 +0,0 @@ -govalidator -=========== -[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/asaskevich/govalidator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![GoDoc](https://godoc.org/github.com/asaskevich/govalidator?status.png)](https://godoc.org/github.com/asaskevich/govalidator) [![Coverage Status](https://img.shields.io/coveralls/asaskevich/govalidator.svg)](https://coveralls.io/r/asaskevich/govalidator?branch=master) [![wercker status](https://app.wercker.com/status/1ec990b09ea86c910d5f08b0e02c6043/s "wercker status")](https://app.wercker.com/project/bykey/1ec990b09ea86c910d5f08b0e02c6043) -[![Build Status](https://travis-ci.org/asaskevich/govalidator.svg?branch=master)](https://travis-ci.org/asaskevich/govalidator) [![Go Report Card](https://goreportcard.com/badge/github.com/asaskevich/govalidator)](https://goreportcard.com/report/github.com/asaskevich/govalidator) [![GoSearch](http://go-search.org/badge?id=github.com%2Fasaskevich%2Fgovalidator)](http://go-search.org/view?id=github.com%2Fasaskevich%2Fgovalidator) [![Backers on Open Collective](https://opencollective.com/govalidator/backers/badge.svg)](#backers) [![Sponsors on Open Collective](https://opencollective.com/govalidator/sponsors/badge.svg)](#sponsors) - -A package of validators and sanitizers for strings, structs and collections. Based on [validator.js](https://github.com/chriso/validator.js). - -#### Installation -Make sure that Go is installed on your computer. -Type the following command in your terminal: - - go get github.com/asaskevich/govalidator - -or you can get specified release of the package with `gopkg.in`: - - go get gopkg.in/asaskevich/govalidator.v4 - -After it the package is ready to use. - - -#### Import package in your project -Add following line in your `*.go` file: -```go -import "github.com/asaskevich/govalidator" -``` -If you are unhappy to use long `govalidator`, you can do something like this: -```go -import ( - valid "github.com/asaskevich/govalidator" -) -``` - -#### Activate behavior to require all fields have a validation tag by default -`SetFieldsRequiredByDefault` causes validation to fail when struct fields do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). A good place to activate this is a package init function or the main() function. - -```go -import "github.com/asaskevich/govalidator" - -func init() { - govalidator.SetFieldsRequiredByDefault(true) -} -``` - -Here's some code to explain it: -```go -// this struct definition will fail govalidator.ValidateStruct() (and the field values do not matter): -type exampleStruct struct { - Name string `` - Email string `valid:"email"` -} - -// this, however, will only fail when Email is empty or an invalid email address: -type exampleStruct2 struct { - Name string `valid:"-"` - Email string `valid:"email"` -} - -// lastly, this will only fail when Email is an invalid email address but not when it's empty: -type exampleStruct2 struct { - Name string `valid:"-"` - Email string `valid:"email,optional"` -} -``` - -#### Recent breaking changes (see [#123](https://github.com/asaskevich/govalidator/pull/123)) -##### Custom validator function signature -A context was added as the second parameter, for structs this is the object being validated – this makes dependent validation possible. -```go -import "github.com/asaskevich/govalidator" - -// old signature -func(i interface{}) bool - -// new signature -func(i interface{}, o interface{}) bool -``` - -##### Adding a custom validator -This was changed to prevent data races when accessing custom validators. -```go -import "github.com/asaskevich/govalidator" - -// before -govalidator.CustomTypeTagMap["customByteArrayValidator"] = CustomTypeValidator(func(i interface{}, o interface{}) bool { - // ... -}) - -// after -govalidator.CustomTypeTagMap.Set("customByteArrayValidator", CustomTypeValidator(func(i interface{}, o interface{}) bool { - // ... -})) -``` - -#### List of functions: -```go -func Abs(value float64) float64 -func BlackList(str, chars string) string -func ByteLength(str string, params ...string) bool -func CamelCaseToUnderscore(str string) string -func Contains(str, substring string) bool -func Count(array []interface{}, iterator ConditionIterator) int -func Each(array []interface{}, iterator Iterator) -func ErrorByField(e error, field string) string -func ErrorsByField(e error) map[string]string -func Filter(array []interface{}, iterator ConditionIterator) []interface{} -func Find(array []interface{}, iterator ConditionIterator) interface{} -func GetLine(s string, index int) (string, error) -func GetLines(s string) []string -func InRange(value, left, right float64) bool -func IsASCII(str string) bool -func IsAlpha(str string) bool -func IsAlphanumeric(str string) bool -func IsBase64(str string) bool -func IsByteLength(str string, min, max int) bool -func IsCIDR(str string) bool -func IsCreditCard(str string) bool -func IsDNSName(str string) bool -func IsDataURI(str string) bool -func IsDialString(str string) bool -func IsDivisibleBy(str, num string) bool -func IsEmail(str string) bool -func IsFilePath(str string) (bool, int) -func IsFloat(str string) bool -func IsFullWidth(str string) bool -func IsHalfWidth(str string) bool -func IsHexadecimal(str string) bool -func IsHexcolor(str string) bool -func IsHost(str string) bool -func IsIP(str string) bool -func IsIPv4(str string) bool -func IsIPv6(str string) bool -func IsISBN(str string, version int) bool -func IsISBN10(str string) bool -func IsISBN13(str string) bool -func IsISO3166Alpha2(str string) bool -func IsISO3166Alpha3(str string) bool -func IsISO693Alpha2(str string) bool -func IsISO693Alpha3b(str string) bool -func IsISO4217(str string) bool -func IsIn(str string, params ...string) bool -func IsInt(str string) bool -func IsJSON(str string) bool -func IsLatitude(str string) bool -func IsLongitude(str string) bool -func IsLowerCase(str string) bool -func IsMAC(str string) bool -func IsMongoID(str string) bool -func IsMultibyte(str string) bool -func IsNatural(value float64) bool -func IsNegative(value float64) bool -func IsNonNegative(value float64) bool -func IsNonPositive(value float64) bool -func IsNull(str string) bool -func IsNumeric(str string) bool -func IsPort(str string) bool -func IsPositive(value float64) bool -func IsPrintableASCII(str string) bool -func IsRFC3339(str string) bool -func IsRFC3339WithoutZone(str string) bool -func IsRGBcolor(str string) bool -func IsRequestURI(rawurl string) bool -func IsRequestURL(rawurl string) bool -func IsSSN(str string) bool -func IsSemver(str string) bool -func IsTime(str string, format string) bool -func IsURL(str string) bool -func IsUTFDigit(str string) bool -func IsUTFLetter(str string) bool -func IsUTFLetterNumeric(str string) bool -func IsUTFNumeric(str string) bool -func IsUUID(str string) bool -func IsUUIDv3(str string) bool -func IsUUIDv4(str string) bool -func IsUUIDv5(str string) bool -func IsUpperCase(str string) bool -func IsVariableWidth(str string) bool -func IsWhole(value float64) bool -func LeftTrim(str, chars string) string -func Map(array []interface{}, iterator ResultIterator) []interface{} -func Matches(str, pattern string) bool -func NormalizeEmail(str string) (string, error) -func PadBoth(str string, padStr string, padLen int) string -func PadLeft(str string, padStr string, padLen int) string -func PadRight(str string, padStr string, padLen int) string -func Range(str string, params ...string) bool -func RemoveTags(s string) string -func ReplacePattern(str, pattern, replace string) string -func Reverse(s string) string -func RightTrim(str, chars string) string -func RuneLength(str string, params ...string) bool -func SafeFileName(str string) string -func SetFieldsRequiredByDefault(value bool) -func Sign(value float64) float64 -func StringLength(str string, params ...string) bool -func StringMatches(s string, params ...string) bool -func StripLow(str string, keepNewLines bool) string -func ToBoolean(str string) (bool, error) -func ToFloat(str string) (float64, error) -func ToInt(str string) (int64, error) -func ToJSON(obj interface{}) (string, error) -func ToString(obj interface{}) string -func Trim(str, chars string) string -func Truncate(str string, length int, ending string) string -func UnderscoreToCamelCase(s string) string -func ValidateStruct(s interface{}) (bool, error) -func WhiteList(str, chars string) string -type ConditionIterator -type CustomTypeValidator -type Error -func (e Error) Error() string -type Errors -func (es Errors) Error() string -func (es Errors) Errors() []error -type ISO3166Entry -type Iterator -type ParamValidator -type ResultIterator -type UnsupportedTypeError -func (e *UnsupportedTypeError) Error() string -type Validator -``` - -#### Examples -###### IsURL -```go -println(govalidator.IsURL(`http://user@pass:domain.com/path/page`)) -``` -###### ToString -```go -type User struct { - FirstName string - LastName string -} - -str := govalidator.ToString(&User{"John", "Juan"}) -println(str) -``` -###### Each, Map, Filter, Count for slices -Each iterates over the slice/array and calls Iterator for every item -```go -data := []interface{}{1, 2, 3, 4, 5} -var fn govalidator.Iterator = func(value interface{}, index int) { - println(value.(int)) -} -govalidator.Each(data, fn) -``` -```go -data := []interface{}{1, 2, 3, 4, 5} -var fn govalidator.ResultIterator = func(value interface{}, index int) interface{} { - return value.(int) * 3 -} -_ = govalidator.Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15} -``` -```go -data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} -var fn govalidator.ConditionIterator = func(value interface{}, index int) bool { - return value.(int)%2 == 0 -} -_ = govalidator.Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10} -_ = govalidator.Count(data, fn) // result = 5 -``` -###### ValidateStruct [#2](https://github.com/asaskevich/govalidator/pull/2) -If you want to validate structs, you can use tag `valid` for any field in your structure. All validators used with this field in one tag are separated by comma. If you want to skip validation, place `-` in your tag. If you need a validator that is not on the list below, you can add it like this: -```go -govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool { - return str == "duck" -}) -``` -For completely custom validators (interface-based), see below. - -Here is a list of available validators for struct fields (validator - used function): -```go -"email": IsEmail, -"url": IsURL, -"dialstring": IsDialString, -"requrl": IsRequestURL, -"requri": IsRequestURI, -"alpha": IsAlpha, -"utfletter": IsUTFLetter, -"alphanum": IsAlphanumeric, -"utfletternum": IsUTFLetterNumeric, -"numeric": IsNumeric, -"utfnumeric": IsUTFNumeric, -"utfdigit": IsUTFDigit, -"hexadecimal": IsHexadecimal, -"hexcolor": IsHexcolor, -"rgbcolor": IsRGBcolor, -"lowercase": IsLowerCase, -"uppercase": IsUpperCase, -"int": IsInt, -"float": IsFloat, -"null": IsNull, -"uuid": IsUUID, -"uuidv3": IsUUIDv3, -"uuidv4": IsUUIDv4, -"uuidv5": IsUUIDv5, -"creditcard": IsCreditCard, -"isbn10": IsISBN10, -"isbn13": IsISBN13, -"json": IsJSON, -"multibyte": IsMultibyte, -"ascii": IsASCII, -"printableascii": IsPrintableASCII, -"fullwidth": IsFullWidth, -"halfwidth": IsHalfWidth, -"variablewidth": IsVariableWidth, -"base64": IsBase64, -"datauri": IsDataURI, -"ip": IsIP, -"port": IsPort, -"ipv4": IsIPv4, -"ipv6": IsIPv6, -"dns": IsDNSName, -"host": IsHost, -"mac": IsMAC, -"latitude": IsLatitude, -"longitude": IsLongitude, -"ssn": IsSSN, -"semver": IsSemver, -"rfc3339": IsRFC3339, -"rfc3339WithoutZone": IsRFC3339WithoutZone, -"ISO3166Alpha2": IsISO3166Alpha2, -"ISO3166Alpha3": IsISO3166Alpha3, -``` -Validators with parameters - -```go -"range(min|max)": Range, -"length(min|max)": ByteLength, -"runelength(min|max)": RuneLength, -"matches(pattern)": StringMatches, -"in(string1|string2|...|stringN)": IsIn, -``` - -And here is small example of usage: -```go -type Post struct { - Title string `valid:"alphanum,required"` - Message string `valid:"duck,ascii"` - AuthorIP string `valid:"ipv4"` - Date string `valid:"-"` -} -post := &Post{ - Title: "My Example Post", - Message: "duck", - AuthorIP: "123.234.54.3", -} - -// Add your own struct validation tags -govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool { - return str == "duck" -}) - -result, err := govalidator.ValidateStruct(post) -if err != nil { - println("error: " + err.Error()) -} -println(result) -``` -###### WhiteList -```go -// Remove all characters from string ignoring characters between "a" and "z" -println(govalidator.WhiteList("a3a43a5a4a3a2a23a4a5a4a3a4", "a-z") == "aaaaaaaaaaaa") -``` - -###### Custom validation functions -Custom validation using your own domain specific validators is also available - here's an example of how to use it: -```go -import "github.com/asaskevich/govalidator" - -type CustomByteArray [6]byte // custom types are supported and can be validated - -type StructWithCustomByteArray struct { - ID CustomByteArray `valid:"customByteArrayValidator,customMinLengthValidator"` // multiple custom validators are possible as well and will be evaluated in sequence - Email string `valid:"email"` - CustomMinLength int `valid:"-"` -} - -govalidator.CustomTypeTagMap.Set("customByteArrayValidator", CustomTypeValidator(func(i interface{}, context interface{}) bool { - switch v := context.(type) { // you can type switch on the context interface being validated - case StructWithCustomByteArray: - // you can check and validate against some other field in the context, - // return early or not validate against the context at all – your choice - case SomeOtherType: - // ... - default: - // expecting some other type? Throw/panic here or continue - } - - switch v := i.(type) { // type switch on the struct field being validated - case CustomByteArray: - for _, e := range v { // this validator checks that the byte array is not empty, i.e. not all zeroes - if e != 0 { - return true - } - } - } - return false -})) -govalidator.CustomTypeTagMap.Set("customMinLengthValidator", CustomTypeValidator(func(i interface{}, context interface{}) bool { - switch v := context.(type) { // this validates a field against the value in another field, i.e. dependent validation - case StructWithCustomByteArray: - return len(v.ID) >= v.CustomMinLength - } - return false -})) -``` - -###### Custom error messages -Custom error messages are supported via annotations by adding the `~` separator - here's an example of how to use it: -```go -type Ticket struct { - Id int64 `json:"id"` - FirstName string `json:"firstname" valid:"required~First name is blank"` -} -``` - -#### Notes -Documentation is available here: [godoc.org](https://godoc.org/github.com/asaskevich/govalidator). -Full information about code coverage is also available here: [govalidator on gocover.io](http://gocover.io/github.com/asaskevich/govalidator). - -#### Support -If you do have a contribution to the package, feel free to create a Pull Request or an Issue. - -#### What to contribute -If you don't know what to do, there are some features and functions that need to be done - -- [ ] Refactor code -- [ ] Edit docs and [README](https://github.com/asaskevich/govalidator/README.md): spellcheck, grammar and typo check -- [ ] Create actual list of contributors and projects that currently using this package -- [ ] Resolve [issues and bugs](https://github.com/asaskevich/govalidator/issues) -- [ ] Update actual [list of functions](https://github.com/asaskevich/govalidator#list-of-functions) -- [ ] Update [list of validators](https://github.com/asaskevich/govalidator#validatestruct-2) that available for `ValidateStruct` and add new -- [ ] Implement new validators: `IsFQDN`, `IsIMEI`, `IsPostalCode`, `IsISIN`, `IsISRC` etc -- [ ] Implement [validation by maps](https://github.com/asaskevich/govalidator/issues/224) -- [ ] Implement fuzzing testing -- [ ] Implement some struct/map/array utilities -- [ ] Implement map/array validation -- [ ] Implement benchmarking -- [ ] Implement batch of examples -- [ ] Look at forks for new features and fixes - -#### Advice -Feel free to create what you want, but keep in mind when you implement new features: -- Code must be clear and readable, names of variables/constants clearly describes what they are doing -- Public functions must be documented and described in source file and added to README.md to the list of available functions -- There are must be unit-tests for any new functions and improvements - -## Credits -### Contributors - -This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)]. - -#### Special thanks to [contributors](https://github.com/asaskevich/govalidator/graphs/contributors) -* [Daniel Lohse](https://github.com/annismckenzie) -* [Attila Oláh](https://github.com/attilaolah) -* [Daniel Korner](https://github.com/Dadie) -* [Steven Wilkin](https://github.com/stevenwilkin) -* [Deiwin Sarjas](https://github.com/deiwin) -* [Noah Shibley](https://github.com/slugmobile) -* [Nathan Davies](https://github.com/nathj07) -* [Matt Sanford](https://github.com/mzsanford) -* [Simon ccl1115](https://github.com/ccl1115) - - - - -### Backers - -Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/govalidator#backer)] - - - - -### Sponsors - -Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/govalidator#sponsor)] - - - - - - - - - - - - - diff --git a/vendor/github.com/asaskevich/govalidator/arrays.go b/vendor/github.com/asaskevich/govalidator/arrays.go deleted file mode 100644 index 5bace2654..000000000 --- a/vendor/github.com/asaskevich/govalidator/arrays.go +++ /dev/null @@ -1,58 +0,0 @@ -package govalidator - -// Iterator is the function that accepts element of slice/array and its index -type Iterator func(interface{}, int) - -// ResultIterator is the function that accepts element of slice/array and its index and returns any result -type ResultIterator func(interface{}, int) interface{} - -// ConditionIterator is the function that accepts element of slice/array and its index and returns boolean -type ConditionIterator func(interface{}, int) bool - -// Each iterates over the slice and apply Iterator to every item -func Each(array []interface{}, iterator Iterator) { - for index, data := range array { - iterator(data, index) - } -} - -// Map iterates over the slice and apply ResultIterator to every item. Returns new slice as a result. -func Map(array []interface{}, iterator ResultIterator) []interface{} { - var result = make([]interface{}, len(array)) - for index, data := range array { - result[index] = iterator(data, index) - } - return result -} - -// Find iterates over the slice and apply ConditionIterator to every item. Returns first item that meet ConditionIterator or nil otherwise. -func Find(array []interface{}, iterator ConditionIterator) interface{} { - for index, data := range array { - if iterator(data, index) { - return data - } - } - return nil -} - -// Filter iterates over the slice and apply ConditionIterator to every item. Returns new slice. -func Filter(array []interface{}, iterator ConditionIterator) []interface{} { - var result = make([]interface{}, 0) - for index, data := range array { - if iterator(data, index) { - result = append(result, data) - } - } - return result -} - -// Count iterates over the slice and apply ConditionIterator to every item. Returns count of items that meets ConditionIterator. -func Count(array []interface{}, iterator ConditionIterator) int { - count := 0 - for index, data := range array { - if iterator(data, index) { - count = count + 1 - } - } - return count -} diff --git a/vendor/github.com/asaskevich/govalidator/arrays_test.go b/vendor/github.com/asaskevich/govalidator/arrays_test.go deleted file mode 100644 index 1a9ac6696..000000000 --- a/vendor/github.com/asaskevich/govalidator/arrays_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package govalidator - -import "testing" - -func TestEach(t *testing.T) { - // TODO Maybe refactor? - t.Parallel() - acc := 0 - data := []interface{}{1, 2, 3, 4, 5} - var fn Iterator = func(value interface{}, index int) { - acc = acc + value.(int) - } - Each(data, fn) - if acc != 15 { - t.Errorf("Expected Each(..) to be %v, got %v", 15, acc) - } -} - -func ExampleEach() { - data := []interface{}{1, 2, 3, 4, 5} - var fn Iterator = func(value interface{}, index int) { - println(value.(int)) - } - Each(data, fn) -} - -func TestMap(t *testing.T) { - // TODO Maybe refactor? - t.Parallel() - data := []interface{}{1, 2, 3, 4, 5} - var fn ResultIterator = func(value interface{}, index int) interface{} { - return value.(int) * 3 - } - result := Map(data, fn) - for i, d := range result { - if d != fn(data[i], i) { - t.Errorf("Expected Map(..) to be %v, got %v", fn(data[i], i), d) - } - } -} - -func ExampleMap() { - data := []interface{}{1, 2, 3, 4, 5} - var fn ResultIterator = func(value interface{}, index int) interface{} { - return value.(int) * 3 - } - _ = Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15} -} - -func TestFind(t *testing.T) { - // TODO Maybe refactor? - t.Parallel() - findElement := 96 - data := []interface{}{1, 2, 3, 4, findElement, 5} - var fn1 ConditionIterator = func(value interface{}, index int) bool { - return value.(int) == findElement - } - var fn2 ConditionIterator = func(value interface{}, index int) bool { - value, _ = value.(string) - return value == "govalidator" - } - val1 := Find(data, fn1) - val2 := Find(data, fn2) - if val1 != findElement { - t.Errorf("Expected Find(..) to be %v, got %v", findElement, val1) - } - if val2 != nil { - t.Errorf("Expected Find(..) to be %v, got %v", nil, val2) - } -} - -func TestFilter(t *testing.T) { - // TODO Maybe refactor? - t.Parallel() - data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} - answer := []interface{}{2, 4, 6, 8, 10} - var fn ConditionIterator = func(value interface{}, index int) bool { - return value.(int)%2 == 0 - } - result := Filter(data, fn) - for i := range result { - if result[i] != answer[i] { - t.Errorf("Expected Filter(..) to be %v, got %v", answer[i], result[i]) - } - } -} - -func ExampleFilter() { - data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} - var fn ConditionIterator = func(value interface{}, index int) bool { - return value.(int)%2 == 0 - } - _ = Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10} -} - -func TestCount(t *testing.T) { - // TODO Maybe refactor? - t.Parallel() - data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} - count := 5 - var fn ConditionIterator = func(value interface{}, index int) bool { - return value.(int)%2 == 0 - } - result := Count(data, fn) - if result != count { - t.Errorf("Expected Count(..) to be %v, got %v", count, result) - } -} - -func ExampleCount() { - data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} - var fn ConditionIterator = func(value interface{}, index int) bool { - return value.(int)%2 == 0 - } - _ = Count(data, fn) // result = 5 -} diff --git a/vendor/github.com/asaskevich/govalidator/converter.go b/vendor/github.com/asaskevich/govalidator/converter.go deleted file mode 100644 index cf1e5d569..000000000 --- a/vendor/github.com/asaskevich/govalidator/converter.go +++ /dev/null @@ -1,64 +0,0 @@ -package govalidator - -import ( - "encoding/json" - "fmt" - "reflect" - "strconv" -) - -// ToString convert the input to a string. -func ToString(obj interface{}) string { - res := fmt.Sprintf("%v", obj) - return string(res) -} - -// ToJSON convert the input to a valid JSON string -func ToJSON(obj interface{}) (string, error) { - res, err := json.Marshal(obj) - if err != nil { - res = []byte("") - } - return string(res), err -} - -// ToFloat convert the input string to a float, or 0.0 if the input is not a float. -func ToFloat(str string) (float64, error) { - res, err := strconv.ParseFloat(str, 64) - if err != nil { - res = 0.0 - } - return res, err -} - -// ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer. -func ToInt(value interface{}) (res int64, err error) { - val := reflect.ValueOf(value) - - switch value.(type) { - case int, int8, int16, int32, int64: - res = val.Int() - case uint, uint8, uint16, uint32, uint64: - res = int64(val.Uint()) - case string: - if IsInt(val.String()) { - res, err = strconv.ParseInt(val.String(), 0, 64) - if err != nil { - res = 0 - } - } else { - err = fmt.Errorf("math: square root of negative number %g", value) - res = 0 - } - default: - err = fmt.Errorf("math: square root of negative number %g", value) - res = 0 - } - - return -} - -// ToBoolean convert the input string to a boolean. -func ToBoolean(str string) (bool, error) { - return strconv.ParseBool(str) -} diff --git a/vendor/github.com/asaskevich/govalidator/converter_test.go b/vendor/github.com/asaskevich/govalidator/converter_test.go deleted file mode 100644 index ecc457be8..000000000 --- a/vendor/github.com/asaskevich/govalidator/converter_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package govalidator - -import ( - "fmt" - "testing" -) - -func TestToInt(t *testing.T) { - tests := []string{"1000", "-123", "abcdef", "100000000000000000000000000000000000000000000"} - expected := []int64{1000, -123, 0, 0} - for i := 0; i < len(tests); i++ { - result, _ := ToInt(tests[i]) - if result != expected[i] { - t.Log("Case ", i, ": expected ", expected[i], " when result is ", result) - t.FailNow() - } - } -} - -func TestToBoolean(t *testing.T) { - tests := []string{"true", "1", "True", "false", "0", "abcdef"} - expected := []bool{true, true, true, false, false, false} - for i := 0; i < len(tests); i++ { - res, _ := ToBoolean(tests[i]) - if res != expected[i] { - t.Log("Case ", i, ": expected ", expected[i], " when result is ", res) - t.FailNow() - } - } -} - -func toString(t *testing.T, test interface{}, expected string) { - res := ToString(test) - if res != expected { - t.Log("Case ToString: expected ", expected, " when result is ", res) - t.FailNow() - } -} - -func TestToString(t *testing.T) { - toString(t, "str123", "str123") - toString(t, 123, "123") - toString(t, 12.3, "12.3") - toString(t, true, "true") - toString(t, 1.5+10i, "(1.5+10i)") - // Sprintf function not guarantee that maps with equal keys always will be equal in string representation - //toString(t, struct{ Keys map[int]int }{Keys: map[int]int{1: 2, 3: 4}}, "{map[1:2 3:4]}") -} - -func TestToFloat(t *testing.T) { - tests := []string{"", "123", "-.01", "10.", "string", "1.23e3", ".23e10"} - expected := []float64{0, 123, -0.01, 10.0, 0, 1230, 0.23e10} - for i := 0; i < len(tests); i++ { - res, _ := ToFloat(tests[i]) - if res != expected[i] { - t.Log("Case ", i, ": expected ", expected[i], " when result is ", res) - t.FailNow() - } - } -} - -func TestToJSON(t *testing.T) { - tests := []interface{}{"test", map[string]string{"a": "b", "b": "c"}, func() error { return fmt.Errorf("Error") }} - expected := [][]string{ - {"\"test\"", ""}, - {"{\"a\":\"b\",\"b\":\"c\"}", ""}, - {"", "json: unsupported type: func() error"}, - } - for i, test := range tests { - actual, err := ToJSON(test) - if actual != expected[i][0] { - t.Errorf("Expected toJSON(%v) to return '%v', got '%v'", test, expected[i][0], actual) - } - if fmt.Sprintf("%v", err) != expected[i][1] { - t.Errorf("Expected error returned from toJSON(%v) to return '%v', got '%v'", test, expected[i][1], fmt.Sprintf("%v", err)) - } - } -} diff --git a/vendor/github.com/asaskevich/govalidator/error.go b/vendor/github.com/asaskevich/govalidator/error.go deleted file mode 100644 index b9c32079b..000000000 --- a/vendor/github.com/asaskevich/govalidator/error.go +++ /dev/null @@ -1,36 +0,0 @@ -package govalidator - -import "strings" - -// Errors is an array of multiple errors and conforms to the error interface. -type Errors []error - -// Errors returns itself. -func (es Errors) Errors() []error { - return es -} - -func (es Errors) Error() string { - var errs []string - for _, e := range es { - errs = append(errs, e.Error()) - } - return strings.Join(errs, ";") -} - -// Error encapsulates a name, an error and whether there's a custom error message or not. -type Error struct { - Name string - Err error - CustomErrorMessageExists bool - - // Validator indicates the name of the validator that failed - Validator string -} - -func (e Error) Error() string { - if e.CustomErrorMessageExists { - return e.Err.Error() - } - return e.Name + ": " + e.Err.Error() -} diff --git a/vendor/github.com/asaskevich/govalidator/error_test.go b/vendor/github.com/asaskevich/govalidator/error_test.go deleted file mode 100644 index e673f2824..000000000 --- a/vendor/github.com/asaskevich/govalidator/error_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package govalidator - -import ( - "fmt" - "testing" -) - -func TestErrorsToString(t *testing.T) { - t.Parallel() - customErr := &Error{Name: "Custom Error Name", Err: fmt.Errorf("stdlib error")} - customErrWithCustomErrorMessage := &Error{Name: "Custom Error Name 2", Err: fmt.Errorf("Bad stuff happened"), CustomErrorMessageExists: true} - - var tests = []struct { - param1 Errors - expected string - }{ - {Errors{}, ""}, - {Errors{fmt.Errorf("Error 1")}, "Error 1"}, - {Errors{fmt.Errorf("Error 1"), fmt.Errorf("Error 2")}, "Error 1;Error 2"}, - {Errors{customErr, fmt.Errorf("Error 2")}, "Custom Error Name: stdlib error;Error 2"}, - {Errors{fmt.Errorf("Error 123"), customErrWithCustomErrorMessage}, "Error 123;Bad stuff happened"}, - } - for _, test := range tests { - actual := test.param1.Error() - if actual != test.expected { - t.Errorf("Expected Error() to return '%v', got '%v'", test.expected, actual) - } - } -} diff --git a/vendor/github.com/asaskevich/govalidator/numerics.go b/vendor/github.com/asaskevich/govalidator/numerics.go deleted file mode 100644 index 7e6c652e1..000000000 --- a/vendor/github.com/asaskevich/govalidator/numerics.go +++ /dev/null @@ -1,97 +0,0 @@ -package govalidator - -import ( - "math" - "reflect" -) - -// Abs returns absolute value of number -func Abs(value float64) float64 { - return math.Abs(value) -} - -// Sign returns signum of number: 1 in case of value > 0, -1 in case of value < 0, 0 otherwise -func Sign(value float64) float64 { - if value > 0 { - return 1 - } else if value < 0 { - return -1 - } else { - return 0 - } -} - -// IsNegative returns true if value < 0 -func IsNegative(value float64) bool { - return value < 0 -} - -// IsPositive returns true if value > 0 -func IsPositive(value float64) bool { - return value > 0 -} - -// IsNonNegative returns true if value >= 0 -func IsNonNegative(value float64) bool { - return value >= 0 -} - -// IsNonPositive returns true if value <= 0 -func IsNonPositive(value float64) bool { - return value <= 0 -} - -// InRange returns true if value lies between left and right border -func InRangeInt(value, left, right interface{}) bool { - value64, _ := ToInt(value) - left64, _ := ToInt(left) - right64, _ := ToInt(right) - if left64 > right64 { - left64, right64 = right64, left64 - } - return value64 >= left64 && value64 <= right64 -} - -// InRange returns true if value lies between left and right border -func InRangeFloat32(value, left, right float32) bool { - if left > right { - left, right = right, left - } - return value >= left && value <= right -} - -// InRange returns true if value lies between left and right border -func InRangeFloat64(value, left, right float64) bool { - if left > right { - left, right = right, left - } - return value >= left && value <= right -} - -// InRange returns true if value lies between left and right border, generic type to handle int, float32 or float64, all types must the same type -func InRange(value interface{}, left interface{}, right interface{}) bool { - - reflectValue := reflect.TypeOf(value).Kind() - reflectLeft := reflect.TypeOf(left).Kind() - reflectRight := reflect.TypeOf(right).Kind() - - if reflectValue == reflect.Int && reflectLeft == reflect.Int && reflectRight == reflect.Int { - return InRangeInt(value.(int), left.(int), right.(int)) - } else if reflectValue == reflect.Float32 && reflectLeft == reflect.Float32 && reflectRight == reflect.Float32 { - return InRangeFloat32(value.(float32), left.(float32), right.(float32)) - } else if reflectValue == reflect.Float64 && reflectLeft == reflect.Float64 && reflectRight == reflect.Float64 { - return InRangeFloat64(value.(float64), left.(float64), right.(float64)) - } else { - return false - } -} - -// IsWhole returns true if value is whole number -func IsWhole(value float64) bool { - return math.Remainder(value, 1) == 0 -} - -// IsNatural returns true if value is natural number (positive and whole) -func IsNatural(value float64) bool { - return IsWhole(value) && IsPositive(value) -} diff --git a/vendor/github.com/asaskevich/govalidator/numerics_test.go b/vendor/github.com/asaskevich/govalidator/numerics_test.go deleted file mode 100644 index 8a28415de..000000000 --- a/vendor/github.com/asaskevich/govalidator/numerics_test.go +++ /dev/null @@ -1,549 +0,0 @@ -package govalidator - -import "testing" - -func TestAbs(t *testing.T) { - t.Parallel() - - var tests = []struct { - param float64 - expected float64 - }{ - {0, 0}, - {-1, 1}, - {10, 10}, - {3.14, 3.14}, - {-96, 96}, - {-10e-12, 10e-12}, - } - for _, test := range tests { - actual := Abs(test.param) - if actual != test.expected { - t.Errorf("Expected Abs(%v) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestSign(t *testing.T) { - t.Parallel() - - var tests = []struct { - param float64 - expected float64 - }{ - {0, 0}, - {-1, -1}, - {10, 1}, - {3.14, 1}, - {-96, -1}, - {-10e-12, -1}, - } - for _, test := range tests { - actual := Sign(test.param) - if actual != test.expected { - t.Errorf("Expected Sign(%v) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsNegative(t *testing.T) { - t.Parallel() - - var tests = []struct { - param float64 - expected bool - }{ - {0, false}, - {-1, true}, - {10, false}, - {3.14, false}, - {-96, true}, - {-10e-12, true}, - } - for _, test := range tests { - actual := IsNegative(test.param) - if actual != test.expected { - t.Errorf("Expected IsNegative(%v) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsNonNegative(t *testing.T) { - t.Parallel() - - var tests = []struct { - param float64 - expected bool - }{ - {0, true}, - {-1, false}, - {10, true}, - {3.14, true}, - {-96, false}, - {-10e-12, false}, - } - for _, test := range tests { - actual := IsNonNegative(test.param) - if actual != test.expected { - t.Errorf("Expected IsNonNegative(%v) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsPositive(t *testing.T) { - t.Parallel() - - var tests = []struct { - param float64 - expected bool - }{ - {0, false}, - {-1, false}, - {10, true}, - {3.14, true}, - {-96, false}, - {-10e-12, false}, - } - for _, test := range tests { - actual := IsPositive(test.param) - if actual != test.expected { - t.Errorf("Expected IsPositive(%v) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsNonPositive(t *testing.T) { - t.Parallel() - - var tests = []struct { - param float64 - expected bool - }{ - {0, true}, - {-1, true}, - {10, false}, - {3.14, false}, - {-96, true}, - {-10e-12, true}, - } - for _, test := range tests { - actual := IsNonPositive(test.param) - if actual != test.expected { - t.Errorf("Expected IsNonPositive(%v) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsWhole(t *testing.T) { - t.Parallel() - - var tests = []struct { - param float64 - expected bool - }{ - {0, true}, - {-1, true}, - {10, true}, - {3.14, false}, - {-96, true}, - {-10e-12, false}, - } - for _, test := range tests { - actual := IsWhole(test.param) - if actual != test.expected { - t.Errorf("Expected IsWhole(%v) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsNatural(t *testing.T) { - t.Parallel() - - var tests = []struct { - param float64 - expected bool - }{ - {0, false}, - {-1, false}, - {10, true}, - {3.14, false}, - {96, true}, - {-10e-12, false}, - } - for _, test := range tests { - actual := IsNatural(test.param) - if actual != test.expected { - t.Errorf("Expected IsNatural(%v) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestInRangeInt(t *testing.T) { - t.Parallel() - - var testAsInts = []struct { - param int - left int - right int - expected bool - }{ - {0, 0, 0, true}, - {1, 0, 0, false}, - {-1, 0, 0, false}, - {0, -1, 1, true}, - {0, 0, 1, true}, - {0, -1, 0, true}, - {0, 0, -1, true}, - {0, 10, 5, false}, - } - for _, test := range testAsInts { - actual := InRangeInt(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRangeInt(%v, %v, %v) to be %v, got %v using type int", test.param, test.left, test.right, test.expected, actual) - } - } - - var testAsInt8s = []struct { - param int8 - left int8 - right int8 - expected bool - }{ - {0, 0, 0, true}, - {1, 0, 0, false}, - {-1, 0, 0, false}, - {0, -1, 1, true}, - {0, 0, 1, true}, - {0, -1, 0, true}, - {0, 0, -1, true}, - {0, 10, 5, false}, - } - for _, test := range testAsInt8s { - actual := InRangeInt(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRangeInt(%v, %v, %v) to be %v, got %v using type int8", test.param, test.left, test.right, test.expected, actual) - } - } - - var testAsInt16s = []struct { - param int16 - left int16 - right int16 - expected bool - }{ - {0, 0, 0, true}, - {1, 0, 0, false}, - {-1, 0, 0, false}, - {0, -1, 1, true}, - {0, 0, 1, true}, - {0, -1, 0, true}, - {0, 0, -1, true}, - {0, 10, 5, false}, - } - for _, test := range testAsInt16s { - actual := InRangeInt(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRangeInt(%v, %v, %v) to be %v, got %v using type int16", test.param, test.left, test.right, test.expected, actual) - } - } - - var testAsInt32s = []struct { - param int32 - left int32 - right int32 - expected bool - }{ - {0, 0, 0, true}, - {1, 0, 0, false}, - {-1, 0, 0, false}, - {0, -1, 1, true}, - {0, 0, 1, true}, - {0, -1, 0, true}, - {0, 0, -1, true}, - {0, 10, 5, false}, - } - for _, test := range testAsInt32s { - actual := InRangeInt(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRangeInt(%v, %v, %v) to be %v, got %v using type int32", test.param, test.left, test.right, test.expected, actual) - } - } - - var testAsInt64s = []struct { - param int64 - left int64 - right int64 - expected bool - }{ - {0, 0, 0, true}, - {1, 0, 0, false}, - {-1, 0, 0, false}, - {0, -1, 1, true}, - {0, 0, 1, true}, - {0, -1, 0, true}, - {0, 0, -1, true}, - {0, 10, 5, false}, - } - for _, test := range testAsInt64s { - actual := InRangeInt(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRangeInt(%v, %v, %v) to be %v, got %v using type int64", test.param, test.left, test.right, test.expected, actual) - } - } - - var testAsUInts = []struct { - param uint - left uint - right uint - expected bool - }{ - {0, 0, 0, true}, - {1, 0, 0, false}, - {0, 0, 1, true}, - {0, 10, 5, false}, - } - for _, test := range testAsUInts { - actual := InRangeInt(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRangeInt(%v, %v, %v) to be %v, got %v using type uint", test.param, test.left, test.right, test.expected, actual) - } - } - - var testAsUInt8s = []struct { - param uint8 - left uint8 - right uint8 - expected bool - }{ - {0, 0, 0, true}, - {1, 0, 0, false}, - {0, 0, 1, true}, - {0, 10, 5, false}, - } - for _, test := range testAsUInt8s { - actual := InRangeInt(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRangeInt(%v, %v, %v) to be %v, got %v using type uint", test.param, test.left, test.right, test.expected, actual) - } - } - - var testAsUInt16s = []struct { - param uint16 - left uint16 - right uint16 - expected bool - }{ - {0, 0, 0, true}, - {1, 0, 0, false}, - {0, 0, 1, true}, - {0, 10, 5, false}, - } - for _, test := range testAsUInt16s { - actual := InRangeInt(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRangeInt(%v, %v, %v) to be %v, got %v using type uint", test.param, test.left, test.right, test.expected, actual) - } - } - - var testAsUInt32s = []struct { - param uint32 - left uint32 - right uint32 - expected bool - }{ - {0, 0, 0, true}, - {1, 0, 0, false}, - {0, 0, 1, true}, - {0, 10, 5, false}, - } - for _, test := range testAsUInt32s { - actual := InRangeInt(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRangeInt(%v, %v, %v) to be %v, got %v using type uint", test.param, test.left, test.right, test.expected, actual) - } - } - - var testAsUInt64s = []struct { - param uint64 - left uint64 - right uint64 - expected bool - }{ - {0, 0, 0, true}, - {1, 0, 0, false}, - {0, 0, 1, true}, - {0, 10, 5, false}, - } - for _, test := range testAsUInt64s { - actual := InRangeInt(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRangeInt(%v, %v, %v) to be %v, got %v using type uint", test.param, test.left, test.right, test.expected, actual) - } - } - - var testAsStrings = []struct { - param string - left string - right string - expected bool - }{ - {"0", "0", "0", true}, - {"1", "0", "0", false}, - {"-1", "0", "0", false}, - {"0", "-1", "1", true}, - {"0", "0", "1", true}, - {"0", "-1", "0", true}, - {"0", "0", "-1", true}, - {"0", "10", "5", false}, - } - for _, test := range testAsStrings { - actual := InRangeInt(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRangeInt(%v, %v, %v) to be %v, got %v using type string", test.param, test.left, test.right, test.expected, actual) - } - } -} - -func TestInRangeFloat32(t *testing.T) { - t.Parallel() - - var tests = []struct { - param float32 - left float32 - right float32 - expected bool - }{ - {0, 0, 0, true}, - {1, 0, 0, false}, - {-1, 0, 0, false}, - {0, -1, 1, true}, - {0, 0, 1, true}, - {0, -1, 0, true}, - {0, 0, -1, true}, - {0, 10, 5, false}, - } - for _, test := range tests { - actual := InRangeFloat32(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRangeFloat32(%v, %v, %v) to be %v, got %v", test.param, test.left, test.right, test.expected, actual) - } - } -} - -func TestInRangeFloat64(t *testing.T) { - t.Parallel() - - var tests = []struct { - param float64 - left float64 - right float64 - expected bool - }{ - {0, 0, 0, true}, - {1, 0, 0, false}, - {-1, 0, 0, false}, - {0, -1, 1, true}, - {0, 0, 1, true}, - {0, -1, 0, true}, - {0, 0, -1, true}, - {0, 10, 5, false}, - } - for _, test := range tests { - actual := InRangeFloat64(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRangeFloat64(%v, %v, %v) to be %v, got %v", test.param, test.left, test.right, test.expected, actual) - } - } -} - -func TestInRange(t *testing.T) { - t.Parallel() - - var testsInt = []struct { - param int - left int - right int - expected bool - }{ - {0, 0, 0, true}, - {1, 0, 0, false}, - {-1, 0, 0, false}, - {0, -1, 1, true}, - {0, 0, 1, true}, - {0, -1, 0, true}, - {0, 0, -1, true}, - {0, 10, 5, false}, - } - for _, test := range testsInt { - actual := InRange(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRange(%v, %v, %v) to be %v, got %v", test.param, test.left, test.right, test.expected, actual) - } - } - - var testsFloat32 = []struct { - param float32 - left float32 - right float32 - expected bool - }{ - {0, 0, 0, true}, - {1, 0, 0, false}, - {-1, 0, 0, false}, - {0, -1, 1, true}, - {0, 0, 1, true}, - {0, -1, 0, true}, - {0, 0, -1, true}, - {0, 10, 5, false}, - } - for _, test := range testsFloat32 { - actual := InRange(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRange(%v, %v, %v) to be %v, got %v", test.param, test.left, test.right, test.expected, actual) - } - } - - var testsFloat64 = []struct { - param float64 - left float64 - right float64 - expected bool - }{ - {0, 0, 0, true}, - {1, 0, 0, false}, - {-1, 0, 0, false}, - {0, -1, 1, true}, - {0, 0, 1, true}, - {0, -1, 0, true}, - {0, 0, -1, true}, - {0, 10, 5, false}, - } - for _, test := range testsFloat64 { - actual := InRange(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRange(%v, %v, %v) to be %v, got %v", test.param, test.left, test.right, test.expected, actual) - } - } - - var testsTypeMix = []struct { - param int - left float64 - right float64 - expected bool - }{ - {0, 0, 0, false}, - {1, 0, 0, false}, - {-1, 0, 0, false}, - {0, -1, 1, false}, - {0, 0, 1, false}, - {0, -1, 0, false}, - {0, 0, -1, false}, - {0, 10, 5, false}, - } - for _, test := range testsTypeMix { - actual := InRange(test.param, test.left, test.right) - if actual != test.expected { - t.Errorf("Expected InRange(%v, %v, %v) to be %v, got %v", test.param, test.left, test.right, test.expected, actual) - } - } -} diff --git a/vendor/github.com/asaskevich/govalidator/patterns.go b/vendor/github.com/asaskevich/govalidator/patterns.go deleted file mode 100644 index 8609cd22f..000000000 --- a/vendor/github.com/asaskevich/govalidator/patterns.go +++ /dev/null @@ -1,97 +0,0 @@ -package govalidator - -import "regexp" - -// Basic regular expressions for validating strings -const ( - //Email string = "^(((([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$" - CreditCard string = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$" - ISBN10 string = "^(?:[0-9]{9}X|[0-9]{10})$" - ISBN13 string = "^(?:[0-9]{13})$" - UUID3 string = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$" - UUID4 string = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" - UUID5 string = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" - UUID string = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" - Alpha string = "^[a-zA-Z]+$" - Alphanumeric string = "^[a-zA-Z0-9]+$" - Numeric string = "^[0-9]+$" - Int string = "^(?:[-+]?(?:0|[1-9][0-9]*))$" - Float string = "^(?:[-+]?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$" - Hexadecimal string = "^[0-9a-fA-F]+$" - Hexcolor string = "^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" - RGBcolor string = "^rgb\\(\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*\\)$" - ASCII string = "^[\x00-\x7F]+$" - Multibyte string = "[^\x00-\x7F]" - FullWidth string = "[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]" - HalfWidth string = "[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]" - Base64 string = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$" - PrintableASCII string = "^[\x20-\x7E]+$" - DataURI string = "^data:.+\\/(.+);base64$" - Latitude string = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$" - Longitude string = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$" - DNSName string = `^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$` - IP string = `(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))` - URLSchema string = `((ftp|tcp|udp|wss?|https?):\/\/)` - URLUsername string = `(\S+(:\S*)?@)` - URLPath string = `((\/|\?|#)[^\s]*)` - URLPort string = `(:(\d{1,5}))` - URLIP string = `([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))` - URLSubdomain string = `((www\.)|([a-zA-Z0-9]([-\.][-\._a-zA-Z0-9]+)*))` - URL string = `^` + URLSchema + `?` + URLUsername + `?` + `((` + URLIP + `|(\[` + IP + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-_]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + URLSubdomain + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))\.?` + URLPort + `?` + URLPath + `?$` - SSN string = `^\d{3}[- ]?\d{2}[- ]?\d{4}$` - WinPath string = `^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$` - UnixPath string = `^(/[^/\x00]*)+/?$` - Semver string = "^v?(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(-(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(\\.(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\\+[0-9a-zA-Z-]+(\\.[0-9a-zA-Z-]+)*)?$" - tagName string = "valid" - hasLowerCase string = ".*[[:lower:]]" - hasUpperCase string = ".*[[:upper:]]" -) - -// Used by IsFilePath func -const ( - // Unknown is unresolved OS type - Unknown = iota - // Win is Windows type - Win - // Unix is *nix OS types - Unix -) - -var ( - userRegexp = regexp.MustCompile("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+$") - hostRegexp = regexp.MustCompile("^[^\\s]+\\.[^\\s]+$") - userDotRegexp = regexp.MustCompile("(^[.]{1})|([.]{1}$)|([.]{2,})") - //rxEmail = regexp.MustCompile(Email) - rxCreditCard = regexp.MustCompile(CreditCard) - rxISBN10 = regexp.MustCompile(ISBN10) - rxISBN13 = regexp.MustCompile(ISBN13) - rxUUID3 = regexp.MustCompile(UUID3) - rxUUID4 = regexp.MustCompile(UUID4) - rxUUID5 = regexp.MustCompile(UUID5) - rxUUID = regexp.MustCompile(UUID) - rxAlpha = regexp.MustCompile(Alpha) - rxAlphanumeric = regexp.MustCompile(Alphanumeric) - rxNumeric = regexp.MustCompile(Numeric) - rxInt = regexp.MustCompile(Int) - rxFloat = regexp.MustCompile(Float) - rxHexadecimal = regexp.MustCompile(Hexadecimal) - rxHexcolor = regexp.MustCompile(Hexcolor) - rxRGBcolor = regexp.MustCompile(RGBcolor) - rxASCII = regexp.MustCompile(ASCII) - rxPrintableASCII = regexp.MustCompile(PrintableASCII) - rxMultibyte = regexp.MustCompile(Multibyte) - rxFullWidth = regexp.MustCompile(FullWidth) - rxHalfWidth = regexp.MustCompile(HalfWidth) - rxBase64 = regexp.MustCompile(Base64) - rxDataURI = regexp.MustCompile(DataURI) - rxLatitude = regexp.MustCompile(Latitude) - rxLongitude = regexp.MustCompile(Longitude) - rxDNSName = regexp.MustCompile(DNSName) - rxURL = regexp.MustCompile(URL) - rxSSN = regexp.MustCompile(SSN) - rxWinPath = regexp.MustCompile(WinPath) - rxUnixPath = regexp.MustCompile(UnixPath) - rxSemver = regexp.MustCompile(Semver) - rxHasLowerCase = regexp.MustCompile(hasLowerCase) - rxHasUpperCase = regexp.MustCompile(hasUpperCase) -) diff --git a/vendor/github.com/asaskevich/govalidator/types.go b/vendor/github.com/asaskevich/govalidator/types.go deleted file mode 100644 index ddd30b122..000000000 --- a/vendor/github.com/asaskevich/govalidator/types.go +++ /dev/null @@ -1,616 +0,0 @@ -package govalidator - -import ( - "reflect" - "regexp" - "sync" -) - -// Validator is a wrapper for a validator function that returns bool and accepts string. -type Validator func(str string) bool - -// CustomTypeValidator is a wrapper for validator functions that returns bool and accepts any type. -// The second parameter should be the context (in the case of validating a struct: the whole object being validated). -type CustomTypeValidator func(i interface{}, o interface{}) bool - -// ParamValidator is a wrapper for validator functions that accepts additional parameters. -type ParamValidator func(str string, params ...string) bool -type tagOptionsMap map[string]string - -// UnsupportedTypeError is a wrapper for reflect.Type -type UnsupportedTypeError struct { - Type reflect.Type -} - -// stringValues is a slice of reflect.Value holding *reflect.StringValue. -// It implements the methods to sort by string. -type stringValues []reflect.Value - -// ParamTagMap is a map of functions accept variants parameters -var ParamTagMap = map[string]ParamValidator{ - "length": ByteLength, - "range": Range, - "runelength": RuneLength, - "stringlength": StringLength, - "matches": StringMatches, - "in": isInRaw, - "rsapub": IsRsaPub, -} - -// ParamTagRegexMap maps param tags to their respective regexes. -var ParamTagRegexMap = map[string]*regexp.Regexp{ - "range": regexp.MustCompile("^range\\((\\d+)\\|(\\d+)\\)$"), - "length": regexp.MustCompile("^length\\((\\d+)\\|(\\d+)\\)$"), - "runelength": regexp.MustCompile("^runelength\\((\\d+)\\|(\\d+)\\)$"), - "stringlength": regexp.MustCompile("^stringlength\\((\\d+)\\|(\\d+)\\)$"), - "in": regexp.MustCompile(`^in\((.*)\)`), - "matches": regexp.MustCompile(`^matches\((.+)\)$`), - "rsapub": regexp.MustCompile("^rsapub\\((\\d+)\\)$"), -} - -type customTypeTagMap struct { - validators map[string]CustomTypeValidator - - sync.RWMutex -} - -func (tm *customTypeTagMap) Get(name string) (CustomTypeValidator, bool) { - tm.RLock() - defer tm.RUnlock() - v, ok := tm.validators[name] - return v, ok -} - -func (tm *customTypeTagMap) Set(name string, ctv CustomTypeValidator) { - tm.Lock() - defer tm.Unlock() - tm.validators[name] = ctv -} - -// CustomTypeTagMap is a map of functions that can be used as tags for ValidateStruct function. -// Use this to validate compound or custom types that need to be handled as a whole, e.g. -// `type UUID [16]byte` (this would be handled as an array of bytes). -var CustomTypeTagMap = &customTypeTagMap{validators: make(map[string]CustomTypeValidator)} - -// TagMap is a map of functions, that can be used as tags for ValidateStruct function. -var TagMap = map[string]Validator{ - "email": IsEmail, - "url": IsURL, - "dialstring": IsDialString, - "requrl": IsRequestURL, - "requri": IsRequestURI, - "alpha": IsAlpha, - "utfletter": IsUTFLetter, - "alphanum": IsAlphanumeric, - "utfletternum": IsUTFLetterNumeric, - "numeric": IsNumeric, - "utfnumeric": IsUTFNumeric, - "utfdigit": IsUTFDigit, - "hexadecimal": IsHexadecimal, - "hexcolor": IsHexcolor, - "rgbcolor": IsRGBcolor, - "lowercase": IsLowerCase, - "uppercase": IsUpperCase, - "int": IsInt, - "float": IsFloat, - "null": IsNull, - "uuid": IsUUID, - "uuidv3": IsUUIDv3, - "uuidv4": IsUUIDv4, - "uuidv5": IsUUIDv5, - "creditcard": IsCreditCard, - "isbn10": IsISBN10, - "isbn13": IsISBN13, - "json": IsJSON, - "multibyte": IsMultibyte, - "ascii": IsASCII, - "printableascii": IsPrintableASCII, - "fullwidth": IsFullWidth, - "halfwidth": IsHalfWidth, - "variablewidth": IsVariableWidth, - "base64": IsBase64, - "datauri": IsDataURI, - "ip": IsIP, - "port": IsPort, - "ipv4": IsIPv4, - "ipv6": IsIPv6, - "dns": IsDNSName, - "host": IsHost, - "mac": IsMAC, - "latitude": IsLatitude, - "longitude": IsLongitude, - "ssn": IsSSN, - "semver": IsSemver, - "rfc3339": IsRFC3339, - "rfc3339WithoutZone": IsRFC3339WithoutZone, - "ISO3166Alpha2": IsISO3166Alpha2, - "ISO3166Alpha3": IsISO3166Alpha3, - "ISO4217": IsISO4217, -} - -// ISO3166Entry stores country codes -type ISO3166Entry struct { - EnglishShortName string - FrenchShortName string - Alpha2Code string - Alpha3Code string - Numeric string -} - -//ISO3166List based on https://www.iso.org/obp/ui/#search/code/ Code Type "Officially Assigned Codes" -var ISO3166List = []ISO3166Entry{ - {"Afghanistan", "Afghanistan (l')", "AF", "AFG", "004"}, - {"Albania", "Albanie (l')", "AL", "ALB", "008"}, - {"Antarctica", "Antarctique (l')", "AQ", "ATA", "010"}, - {"Algeria", "Algérie (l')", "DZ", "DZA", "012"}, - {"American Samoa", "Samoa américaines (les)", "AS", "ASM", "016"}, - {"Andorra", "Andorre (l')", "AD", "AND", "020"}, - {"Angola", "Angola (l')", "AO", "AGO", "024"}, - {"Antigua and Barbuda", "Antigua-et-Barbuda", "AG", "ATG", "028"}, - {"Azerbaijan", "Azerbaïdjan (l')", "AZ", "AZE", "031"}, - {"Argentina", "Argentine (l')", "AR", "ARG", "032"}, - {"Australia", "Australie (l')", "AU", "AUS", "036"}, - {"Austria", "Autriche (l')", "AT", "AUT", "040"}, - {"Bahamas (the)", "Bahamas (les)", "BS", "BHS", "044"}, - {"Bahrain", "Bahreïn", "BH", "BHR", "048"}, - {"Bangladesh", "Bangladesh (le)", "BD", "BGD", "050"}, - {"Armenia", "Arménie (l')", "AM", "ARM", "051"}, - {"Barbados", "Barbade (la)", "BB", "BRB", "052"}, - {"Belgium", "Belgique (la)", "BE", "BEL", "056"}, - {"Bermuda", "Bermudes (les)", "BM", "BMU", "060"}, - {"Bhutan", "Bhoutan (le)", "BT", "BTN", "064"}, - {"Bolivia (Plurinational State of)", "Bolivie (État plurinational de)", "BO", "BOL", "068"}, - {"Bosnia and Herzegovina", "Bosnie-Herzégovine (la)", "BA", "BIH", "070"}, - {"Botswana", "Botswana (le)", "BW", "BWA", "072"}, - {"Bouvet Island", "Bouvet (l'Île)", "BV", "BVT", "074"}, - {"Brazil", "Brésil (le)", "BR", "BRA", "076"}, - {"Belize", "Belize (le)", "BZ", "BLZ", "084"}, - {"British Indian Ocean Territory (the)", "Indien (le Territoire britannique de l'océan)", "IO", "IOT", "086"}, - {"Solomon Islands", "Salomon (Îles)", "SB", "SLB", "090"}, - {"Virgin Islands (British)", "Vierges britanniques (les Îles)", "VG", "VGB", "092"}, - {"Brunei Darussalam", "Brunéi Darussalam (le)", "BN", "BRN", "096"}, - {"Bulgaria", "Bulgarie (la)", "BG", "BGR", "100"}, - {"Myanmar", "Myanmar (le)", "MM", "MMR", "104"}, - {"Burundi", "Burundi (le)", "BI", "BDI", "108"}, - {"Belarus", "Bélarus (le)", "BY", "BLR", "112"}, - {"Cambodia", "Cambodge (le)", "KH", "KHM", "116"}, - {"Cameroon", "Cameroun (le)", "CM", "CMR", "120"}, - {"Canada", "Canada (le)", "CA", "CAN", "124"}, - {"Cabo Verde", "Cabo Verde", "CV", "CPV", "132"}, - {"Cayman Islands (the)", "Caïmans (les Îles)", "KY", "CYM", "136"}, - {"Central African Republic (the)", "République centrafricaine (la)", "CF", "CAF", "140"}, - {"Sri Lanka", "Sri Lanka", "LK", "LKA", "144"}, - {"Chad", "Tchad (le)", "TD", "TCD", "148"}, - {"Chile", "Chili (le)", "CL", "CHL", "152"}, - {"China", "Chine (la)", "CN", "CHN", "156"}, - {"Taiwan (Province of China)", "Taïwan (Province de Chine)", "TW", "TWN", "158"}, - {"Christmas Island", "Christmas (l'Île)", "CX", "CXR", "162"}, - {"Cocos (Keeling) Islands (the)", "Cocos (les Îles)/ Keeling (les Îles)", "CC", "CCK", "166"}, - {"Colombia", "Colombie (la)", "CO", "COL", "170"}, - {"Comoros (the)", "Comores (les)", "KM", "COM", "174"}, - {"Mayotte", "Mayotte", "YT", "MYT", "175"}, - {"Congo (the)", "Congo (le)", "CG", "COG", "178"}, - {"Congo (the Democratic Republic of the)", "Congo (la République démocratique du)", "CD", "COD", "180"}, - {"Cook Islands (the)", "Cook (les Îles)", "CK", "COK", "184"}, - {"Costa Rica", "Costa Rica (le)", "CR", "CRI", "188"}, - {"Croatia", "Croatie (la)", "HR", "HRV", "191"}, - {"Cuba", "Cuba", "CU", "CUB", "192"}, - {"Cyprus", "Chypre", "CY", "CYP", "196"}, - {"Czech Republic (the)", "tchèque (la République)", "CZ", "CZE", "203"}, - {"Benin", "Bénin (le)", "BJ", "BEN", "204"}, - {"Denmark", "Danemark (le)", "DK", "DNK", "208"}, - {"Dominica", "Dominique (la)", "DM", "DMA", "212"}, - {"Dominican Republic (the)", "dominicaine (la République)", "DO", "DOM", "214"}, - {"Ecuador", "Équateur (l')", "EC", "ECU", "218"}, - {"El Salvador", "El Salvador", "SV", "SLV", "222"}, - {"Equatorial Guinea", "Guinée équatoriale (la)", "GQ", "GNQ", "226"}, - {"Ethiopia", "Éthiopie (l')", "ET", "ETH", "231"}, - {"Eritrea", "Érythrée (l')", "ER", "ERI", "232"}, - {"Estonia", "Estonie (l')", "EE", "EST", "233"}, - {"Faroe Islands (the)", "Féroé (les Îles)", "FO", "FRO", "234"}, - {"Falkland Islands (the) [Malvinas]", "Falkland (les Îles)/Malouines (les Îles)", "FK", "FLK", "238"}, - {"South Georgia and the South Sandwich Islands", "Géorgie du Sud-et-les Îles Sandwich du Sud (la)", "GS", "SGS", "239"}, - {"Fiji", "Fidji (les)", "FJ", "FJI", "242"}, - {"Finland", "Finlande (la)", "FI", "FIN", "246"}, - {"Åland Islands", "Åland(les Îles)", "AX", "ALA", "248"}, - {"France", "France (la)", "FR", "FRA", "250"}, - {"French Guiana", "Guyane française (la )", "GF", "GUF", "254"}, - {"French Polynesia", "Polynésie française (la)", "PF", "PYF", "258"}, - {"French Southern Territories (the)", "Terres australes françaises (les)", "TF", "ATF", "260"}, - {"Djibouti", "Djibouti", "DJ", "DJI", "262"}, - {"Gabon", "Gabon (le)", "GA", "GAB", "266"}, - {"Georgia", "Géorgie (la)", "GE", "GEO", "268"}, - {"Gambia (the)", "Gambie (la)", "GM", "GMB", "270"}, - {"Palestine, State of", "Palestine, État de", "PS", "PSE", "275"}, - {"Germany", "Allemagne (l')", "DE", "DEU", "276"}, - {"Ghana", "Ghana (le)", "GH", "GHA", "288"}, - {"Gibraltar", "Gibraltar", "GI", "GIB", "292"}, - {"Kiribati", "Kiribati", "KI", "KIR", "296"}, - {"Greece", "Grèce (la)", "GR", "GRC", "300"}, - {"Greenland", "Groenland (le)", "GL", "GRL", "304"}, - {"Grenada", "Grenade (la)", "GD", "GRD", "308"}, - {"Guadeloupe", "Guadeloupe (la)", "GP", "GLP", "312"}, - {"Guam", "Guam", "GU", "GUM", "316"}, - {"Guatemala", "Guatemala (le)", "GT", "GTM", "320"}, - {"Guinea", "Guinée (la)", "GN", "GIN", "324"}, - {"Guyana", "Guyana (le)", "GY", "GUY", "328"}, - {"Haiti", "Haïti", "HT", "HTI", "332"}, - {"Heard Island and McDonald Islands", "Heard-et-Îles MacDonald (l'Île)", "HM", "HMD", "334"}, - {"Holy See (the)", "Saint-Siège (le)", "VA", "VAT", "336"}, - {"Honduras", "Honduras (le)", "HN", "HND", "340"}, - {"Hong Kong", "Hong Kong", "HK", "HKG", "344"}, - {"Hungary", "Hongrie (la)", "HU", "HUN", "348"}, - {"Iceland", "Islande (l')", "IS", "ISL", "352"}, - {"India", "Inde (l')", "IN", "IND", "356"}, - {"Indonesia", "Indonésie (l')", "ID", "IDN", "360"}, - {"Iran (Islamic Republic of)", "Iran (République Islamique d')", "IR", "IRN", "364"}, - {"Iraq", "Iraq (l')", "IQ", "IRQ", "368"}, - {"Ireland", "Irlande (l')", "IE", "IRL", "372"}, - {"Israel", "Israël", "IL", "ISR", "376"}, - {"Italy", "Italie (l')", "IT", "ITA", "380"}, - {"Côte d'Ivoire", "Côte d'Ivoire (la)", "CI", "CIV", "384"}, - {"Jamaica", "Jamaïque (la)", "JM", "JAM", "388"}, - {"Japan", "Japon (le)", "JP", "JPN", "392"}, - {"Kazakhstan", "Kazakhstan (le)", "KZ", "KAZ", "398"}, - {"Jordan", "Jordanie (la)", "JO", "JOR", "400"}, - {"Kenya", "Kenya (le)", "KE", "KEN", "404"}, - {"Korea (the Democratic People's Republic of)", "Corée (la République populaire démocratique de)", "KP", "PRK", "408"}, - {"Korea (the Republic of)", "Corée (la République de)", "KR", "KOR", "410"}, - {"Kuwait", "Koweït (le)", "KW", "KWT", "414"}, - {"Kyrgyzstan", "Kirghizistan (le)", "KG", "KGZ", "417"}, - {"Lao People's Democratic Republic (the)", "Lao, République démocratique populaire", "LA", "LAO", "418"}, - {"Lebanon", "Liban (le)", "LB", "LBN", "422"}, - {"Lesotho", "Lesotho (le)", "LS", "LSO", "426"}, - {"Latvia", "Lettonie (la)", "LV", "LVA", "428"}, - {"Liberia", "Libéria (le)", "LR", "LBR", "430"}, - {"Libya", "Libye (la)", "LY", "LBY", "434"}, - {"Liechtenstein", "Liechtenstein (le)", "LI", "LIE", "438"}, - {"Lithuania", "Lituanie (la)", "LT", "LTU", "440"}, - {"Luxembourg", "Luxembourg (le)", "LU", "LUX", "442"}, - {"Macao", "Macao", "MO", "MAC", "446"}, - {"Madagascar", "Madagascar", "MG", "MDG", "450"}, - {"Malawi", "Malawi (le)", "MW", "MWI", "454"}, - {"Malaysia", "Malaisie (la)", "MY", "MYS", "458"}, - {"Maldives", "Maldives (les)", "MV", "MDV", "462"}, - {"Mali", "Mali (le)", "ML", "MLI", "466"}, - {"Malta", "Malte", "MT", "MLT", "470"}, - {"Martinique", "Martinique (la)", "MQ", "MTQ", "474"}, - {"Mauritania", "Mauritanie (la)", "MR", "MRT", "478"}, - {"Mauritius", "Maurice", "MU", "MUS", "480"}, - {"Mexico", "Mexique (le)", "MX", "MEX", "484"}, - {"Monaco", "Monaco", "MC", "MCO", "492"}, - {"Mongolia", "Mongolie (la)", "MN", "MNG", "496"}, - {"Moldova (the Republic of)", "Moldova , République de", "MD", "MDA", "498"}, - {"Montenegro", "Monténégro (le)", "ME", "MNE", "499"}, - {"Montserrat", "Montserrat", "MS", "MSR", "500"}, - {"Morocco", "Maroc (le)", "MA", "MAR", "504"}, - {"Mozambique", "Mozambique (le)", "MZ", "MOZ", "508"}, - {"Oman", "Oman", "OM", "OMN", "512"}, - {"Namibia", "Namibie (la)", "NA", "NAM", "516"}, - {"Nauru", "Nauru", "NR", "NRU", "520"}, - {"Nepal", "Népal (le)", "NP", "NPL", "524"}, - {"Netherlands (the)", "Pays-Bas (les)", "NL", "NLD", "528"}, - {"Curaçao", "Curaçao", "CW", "CUW", "531"}, - {"Aruba", "Aruba", "AW", "ABW", "533"}, - {"Sint Maarten (Dutch part)", "Saint-Martin (partie néerlandaise)", "SX", "SXM", "534"}, - {"Bonaire, Sint Eustatius and Saba", "Bonaire, Saint-Eustache et Saba", "BQ", "BES", "535"}, - {"New Caledonia", "Nouvelle-Calédonie (la)", "NC", "NCL", "540"}, - {"Vanuatu", "Vanuatu (le)", "VU", "VUT", "548"}, - {"New Zealand", "Nouvelle-Zélande (la)", "NZ", "NZL", "554"}, - {"Nicaragua", "Nicaragua (le)", "NI", "NIC", "558"}, - {"Niger (the)", "Niger (le)", "NE", "NER", "562"}, - {"Nigeria", "Nigéria (le)", "NG", "NGA", "566"}, - {"Niue", "Niue", "NU", "NIU", "570"}, - {"Norfolk Island", "Norfolk (l'Île)", "NF", "NFK", "574"}, - {"Norway", "Norvège (la)", "NO", "NOR", "578"}, - {"Northern Mariana Islands (the)", "Mariannes du Nord (les Îles)", "MP", "MNP", "580"}, - {"United States Minor Outlying Islands (the)", "Îles mineures éloignées des États-Unis (les)", "UM", "UMI", "581"}, - {"Micronesia (Federated States of)", "Micronésie (États fédérés de)", "FM", "FSM", "583"}, - {"Marshall Islands (the)", "Marshall (Îles)", "MH", "MHL", "584"}, - {"Palau", "Palaos (les)", "PW", "PLW", "585"}, - {"Pakistan", "Pakistan (le)", "PK", "PAK", "586"}, - {"Panama", "Panama (le)", "PA", "PAN", "591"}, - {"Papua New Guinea", "Papouasie-Nouvelle-Guinée (la)", "PG", "PNG", "598"}, - {"Paraguay", "Paraguay (le)", "PY", "PRY", "600"}, - {"Peru", "Pérou (le)", "PE", "PER", "604"}, - {"Philippines (the)", "Philippines (les)", "PH", "PHL", "608"}, - {"Pitcairn", "Pitcairn", "PN", "PCN", "612"}, - {"Poland", "Pologne (la)", "PL", "POL", "616"}, - {"Portugal", "Portugal (le)", "PT", "PRT", "620"}, - {"Guinea-Bissau", "Guinée-Bissau (la)", "GW", "GNB", "624"}, - {"Timor-Leste", "Timor-Leste (le)", "TL", "TLS", "626"}, - {"Puerto Rico", "Porto Rico", "PR", "PRI", "630"}, - {"Qatar", "Qatar (le)", "QA", "QAT", "634"}, - {"Réunion", "Réunion (La)", "RE", "REU", "638"}, - {"Romania", "Roumanie (la)", "RO", "ROU", "642"}, - {"Russian Federation (the)", "Russie (la Fédération de)", "RU", "RUS", "643"}, - {"Rwanda", "Rwanda (le)", "RW", "RWA", "646"}, - {"Saint Barthélemy", "Saint-Barthélemy", "BL", "BLM", "652"}, - {"Saint Helena, Ascension and Tristan da Cunha", "Sainte-Hélène, Ascension et Tristan da Cunha", "SH", "SHN", "654"}, - {"Saint Kitts and Nevis", "Saint-Kitts-et-Nevis", "KN", "KNA", "659"}, - {"Anguilla", "Anguilla", "AI", "AIA", "660"}, - {"Saint Lucia", "Sainte-Lucie", "LC", "LCA", "662"}, - {"Saint Martin (French part)", "Saint-Martin (partie française)", "MF", "MAF", "663"}, - {"Saint Pierre and Miquelon", "Saint-Pierre-et-Miquelon", "PM", "SPM", "666"}, - {"Saint Vincent and the Grenadines", "Saint-Vincent-et-les Grenadines", "VC", "VCT", "670"}, - {"San Marino", "Saint-Marin", "SM", "SMR", "674"}, - {"Sao Tome and Principe", "Sao Tomé-et-Principe", "ST", "STP", "678"}, - {"Saudi Arabia", "Arabie saoudite (l')", "SA", "SAU", "682"}, - {"Senegal", "Sénégal (le)", "SN", "SEN", "686"}, - {"Serbia", "Serbie (la)", "RS", "SRB", "688"}, - {"Seychelles", "Seychelles (les)", "SC", "SYC", "690"}, - {"Sierra Leone", "Sierra Leone (la)", "SL", "SLE", "694"}, - {"Singapore", "Singapour", "SG", "SGP", "702"}, - {"Slovakia", "Slovaquie (la)", "SK", "SVK", "703"}, - {"Viet Nam", "Viet Nam (le)", "VN", "VNM", "704"}, - {"Slovenia", "Slovénie (la)", "SI", "SVN", "705"}, - {"Somalia", "Somalie (la)", "SO", "SOM", "706"}, - {"South Africa", "Afrique du Sud (l')", "ZA", "ZAF", "710"}, - {"Zimbabwe", "Zimbabwe (le)", "ZW", "ZWE", "716"}, - {"Spain", "Espagne (l')", "ES", "ESP", "724"}, - {"South Sudan", "Soudan du Sud (le)", "SS", "SSD", "728"}, - {"Sudan (the)", "Soudan (le)", "SD", "SDN", "729"}, - {"Western Sahara*", "Sahara occidental (le)*", "EH", "ESH", "732"}, - {"Suriname", "Suriname (le)", "SR", "SUR", "740"}, - {"Svalbard and Jan Mayen", "Svalbard et l'Île Jan Mayen (le)", "SJ", "SJM", "744"}, - {"Swaziland", "Swaziland (le)", "SZ", "SWZ", "748"}, - {"Sweden", "Suède (la)", "SE", "SWE", "752"}, - {"Switzerland", "Suisse (la)", "CH", "CHE", "756"}, - {"Syrian Arab Republic", "République arabe syrienne (la)", "SY", "SYR", "760"}, - {"Tajikistan", "Tadjikistan (le)", "TJ", "TJK", "762"}, - {"Thailand", "Thaïlande (la)", "TH", "THA", "764"}, - {"Togo", "Togo (le)", "TG", "TGO", "768"}, - {"Tokelau", "Tokelau (les)", "TK", "TKL", "772"}, - {"Tonga", "Tonga (les)", "TO", "TON", "776"}, - {"Trinidad and Tobago", "Trinité-et-Tobago (la)", "TT", "TTO", "780"}, - {"United Arab Emirates (the)", "Émirats arabes unis (les)", "AE", "ARE", "784"}, - {"Tunisia", "Tunisie (la)", "TN", "TUN", "788"}, - {"Turkey", "Turquie (la)", "TR", "TUR", "792"}, - {"Turkmenistan", "Turkménistan (le)", "TM", "TKM", "795"}, - {"Turks and Caicos Islands (the)", "Turks-et-Caïcos (les Îles)", "TC", "TCA", "796"}, - {"Tuvalu", "Tuvalu (les)", "TV", "TUV", "798"}, - {"Uganda", "Ouganda (l')", "UG", "UGA", "800"}, - {"Ukraine", "Ukraine (l')", "UA", "UKR", "804"}, - {"Macedonia (the former Yugoslav Republic of)", "Macédoine (l'ex‑République yougoslave de)", "MK", "MKD", "807"}, - {"Egypt", "Égypte (l')", "EG", "EGY", "818"}, - {"United Kingdom of Great Britain and Northern Ireland (the)", "Royaume-Uni de Grande-Bretagne et d'Irlande du Nord (le)", "GB", "GBR", "826"}, - {"Guernsey", "Guernesey", "GG", "GGY", "831"}, - {"Jersey", "Jersey", "JE", "JEY", "832"}, - {"Isle of Man", "Île de Man", "IM", "IMN", "833"}, - {"Tanzania, United Republic of", "Tanzanie, République-Unie de", "TZ", "TZA", "834"}, - {"United States of America (the)", "États-Unis d'Amérique (les)", "US", "USA", "840"}, - {"Virgin Islands (U.S.)", "Vierges des États-Unis (les Îles)", "VI", "VIR", "850"}, - {"Burkina Faso", "Burkina Faso (le)", "BF", "BFA", "854"}, - {"Uruguay", "Uruguay (l')", "UY", "URY", "858"}, - {"Uzbekistan", "Ouzbékistan (l')", "UZ", "UZB", "860"}, - {"Venezuela (Bolivarian Republic of)", "Venezuela (République bolivarienne du)", "VE", "VEN", "862"}, - {"Wallis and Futuna", "Wallis-et-Futuna", "WF", "WLF", "876"}, - {"Samoa", "Samoa (le)", "WS", "WSM", "882"}, - {"Yemen", "Yémen (le)", "YE", "YEM", "887"}, - {"Zambia", "Zambie (la)", "ZM", "ZMB", "894"}, -} - -// ISO4217List is the list of ISO currency codes -var ISO4217List = []string{ - "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", - "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", - "CAD", "CDF", "CHE", "CHF", "CHW", "CLF", "CLP", "CNY", "COP", "COU", "CRC", "CUC", "CUP", "CVE", "CZK", - "DJF", "DKK", "DOP", "DZD", - "EGP", "ERN", "ETB", "EUR", - "FJD", "FKP", - "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", - "HKD", "HNL", "HRK", "HTG", "HUF", - "IDR", "ILS", "INR", "IQD", "IRR", "ISK", - "JMD", "JOD", "JPY", - "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", - "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", - "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRO", "MUR", "MVR", "MWK", "MXN", "MXV", "MYR", "MZN", - "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", - "OMR", - "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", - "QAR", - "RON", "RSD", "RUB", "RWF", - "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STD", "SVC", "SYP", "SZL", - "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", - "UAH", "UGX", "USD", "USN", "UYI", "UYU", "UZS", - "VEF", "VND", "VUV", - "WST", - "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XOF", "XPD", "XPF", "XPT", "XSU", "XTS", "XUA", "XXX", - "YER", - "ZAR", "ZMW", "ZWL", -} - -// ISO693Entry stores ISO language codes -type ISO693Entry struct { - Alpha3bCode string - Alpha2Code string - English string -} - -//ISO693List based on http://data.okfn.org/data/core/language-codes/r/language-codes-3b2.json -var ISO693List = []ISO693Entry{ - {Alpha3bCode: "aar", Alpha2Code: "aa", English: "Afar"}, - {Alpha3bCode: "abk", Alpha2Code: "ab", English: "Abkhazian"}, - {Alpha3bCode: "afr", Alpha2Code: "af", English: "Afrikaans"}, - {Alpha3bCode: "aka", Alpha2Code: "ak", English: "Akan"}, - {Alpha3bCode: "alb", Alpha2Code: "sq", English: "Albanian"}, - {Alpha3bCode: "amh", Alpha2Code: "am", English: "Amharic"}, - {Alpha3bCode: "ara", Alpha2Code: "ar", English: "Arabic"}, - {Alpha3bCode: "arg", Alpha2Code: "an", English: "Aragonese"}, - {Alpha3bCode: "arm", Alpha2Code: "hy", English: "Armenian"}, - {Alpha3bCode: "asm", Alpha2Code: "as", English: "Assamese"}, - {Alpha3bCode: "ava", Alpha2Code: "av", English: "Avaric"}, - {Alpha3bCode: "ave", Alpha2Code: "ae", English: "Avestan"}, - {Alpha3bCode: "aym", Alpha2Code: "ay", English: "Aymara"}, - {Alpha3bCode: "aze", Alpha2Code: "az", English: "Azerbaijani"}, - {Alpha3bCode: "bak", Alpha2Code: "ba", English: "Bashkir"}, - {Alpha3bCode: "bam", Alpha2Code: "bm", English: "Bambara"}, - {Alpha3bCode: "baq", Alpha2Code: "eu", English: "Basque"}, - {Alpha3bCode: "bel", Alpha2Code: "be", English: "Belarusian"}, - {Alpha3bCode: "ben", Alpha2Code: "bn", English: "Bengali"}, - {Alpha3bCode: "bih", Alpha2Code: "bh", English: "Bihari languages"}, - {Alpha3bCode: "bis", Alpha2Code: "bi", English: "Bislama"}, - {Alpha3bCode: "bos", Alpha2Code: "bs", English: "Bosnian"}, - {Alpha3bCode: "bre", Alpha2Code: "br", English: "Breton"}, - {Alpha3bCode: "bul", Alpha2Code: "bg", English: "Bulgarian"}, - {Alpha3bCode: "bur", Alpha2Code: "my", English: "Burmese"}, - {Alpha3bCode: "cat", Alpha2Code: "ca", English: "Catalan; Valencian"}, - {Alpha3bCode: "cha", Alpha2Code: "ch", English: "Chamorro"}, - {Alpha3bCode: "che", Alpha2Code: "ce", English: "Chechen"}, - {Alpha3bCode: "chi", Alpha2Code: "zh", English: "Chinese"}, - {Alpha3bCode: "chu", Alpha2Code: "cu", English: "Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic"}, - {Alpha3bCode: "chv", Alpha2Code: "cv", English: "Chuvash"}, - {Alpha3bCode: "cor", Alpha2Code: "kw", English: "Cornish"}, - {Alpha3bCode: "cos", Alpha2Code: "co", English: "Corsican"}, - {Alpha3bCode: "cre", Alpha2Code: "cr", English: "Cree"}, - {Alpha3bCode: "cze", Alpha2Code: "cs", English: "Czech"}, - {Alpha3bCode: "dan", Alpha2Code: "da", English: "Danish"}, - {Alpha3bCode: "div", Alpha2Code: "dv", English: "Divehi; Dhivehi; Maldivian"}, - {Alpha3bCode: "dut", Alpha2Code: "nl", English: "Dutch; Flemish"}, - {Alpha3bCode: "dzo", Alpha2Code: "dz", English: "Dzongkha"}, - {Alpha3bCode: "eng", Alpha2Code: "en", English: "English"}, - {Alpha3bCode: "epo", Alpha2Code: "eo", English: "Esperanto"}, - {Alpha3bCode: "est", Alpha2Code: "et", English: "Estonian"}, - {Alpha3bCode: "ewe", Alpha2Code: "ee", English: "Ewe"}, - {Alpha3bCode: "fao", Alpha2Code: "fo", English: "Faroese"}, - {Alpha3bCode: "fij", Alpha2Code: "fj", English: "Fijian"}, - {Alpha3bCode: "fin", Alpha2Code: "fi", English: "Finnish"}, - {Alpha3bCode: "fre", Alpha2Code: "fr", English: "French"}, - {Alpha3bCode: "fry", Alpha2Code: "fy", English: "Western Frisian"}, - {Alpha3bCode: "ful", Alpha2Code: "ff", English: "Fulah"}, - {Alpha3bCode: "geo", Alpha2Code: "ka", English: "Georgian"}, - {Alpha3bCode: "ger", Alpha2Code: "de", English: "German"}, - {Alpha3bCode: "gla", Alpha2Code: "gd", English: "Gaelic; Scottish Gaelic"}, - {Alpha3bCode: "gle", Alpha2Code: "ga", English: "Irish"}, - {Alpha3bCode: "glg", Alpha2Code: "gl", English: "Galician"}, - {Alpha3bCode: "glv", Alpha2Code: "gv", English: "Manx"}, - {Alpha3bCode: "gre", Alpha2Code: "el", English: "Greek, Modern (1453-)"}, - {Alpha3bCode: "grn", Alpha2Code: "gn", English: "Guarani"}, - {Alpha3bCode: "guj", Alpha2Code: "gu", English: "Gujarati"}, - {Alpha3bCode: "hat", Alpha2Code: "ht", English: "Haitian; Haitian Creole"}, - {Alpha3bCode: "hau", Alpha2Code: "ha", English: "Hausa"}, - {Alpha3bCode: "heb", Alpha2Code: "he", English: "Hebrew"}, - {Alpha3bCode: "her", Alpha2Code: "hz", English: "Herero"}, - {Alpha3bCode: "hin", Alpha2Code: "hi", English: "Hindi"}, - {Alpha3bCode: "hmo", Alpha2Code: "ho", English: "Hiri Motu"}, - {Alpha3bCode: "hrv", Alpha2Code: "hr", English: "Croatian"}, - {Alpha3bCode: "hun", Alpha2Code: "hu", English: "Hungarian"}, - {Alpha3bCode: "ibo", Alpha2Code: "ig", English: "Igbo"}, - {Alpha3bCode: "ice", Alpha2Code: "is", English: "Icelandic"}, - {Alpha3bCode: "ido", Alpha2Code: "io", English: "Ido"}, - {Alpha3bCode: "iii", Alpha2Code: "ii", English: "Sichuan Yi; Nuosu"}, - {Alpha3bCode: "iku", Alpha2Code: "iu", English: "Inuktitut"}, - {Alpha3bCode: "ile", Alpha2Code: "ie", English: "Interlingue; Occidental"}, - {Alpha3bCode: "ina", Alpha2Code: "ia", English: "Interlingua (International Auxiliary Language Association)"}, - {Alpha3bCode: "ind", Alpha2Code: "id", English: "Indonesian"}, - {Alpha3bCode: "ipk", Alpha2Code: "ik", English: "Inupiaq"}, - {Alpha3bCode: "ita", Alpha2Code: "it", English: "Italian"}, - {Alpha3bCode: "jav", Alpha2Code: "jv", English: "Javanese"}, - {Alpha3bCode: "jpn", Alpha2Code: "ja", English: "Japanese"}, - {Alpha3bCode: "kal", Alpha2Code: "kl", English: "Kalaallisut; Greenlandic"}, - {Alpha3bCode: "kan", Alpha2Code: "kn", English: "Kannada"}, - {Alpha3bCode: "kas", Alpha2Code: "ks", English: "Kashmiri"}, - {Alpha3bCode: "kau", Alpha2Code: "kr", English: "Kanuri"}, - {Alpha3bCode: "kaz", Alpha2Code: "kk", English: "Kazakh"}, - {Alpha3bCode: "khm", Alpha2Code: "km", English: "Central Khmer"}, - {Alpha3bCode: "kik", Alpha2Code: "ki", English: "Kikuyu; Gikuyu"}, - {Alpha3bCode: "kin", Alpha2Code: "rw", English: "Kinyarwanda"}, - {Alpha3bCode: "kir", Alpha2Code: "ky", English: "Kirghiz; Kyrgyz"}, - {Alpha3bCode: "kom", Alpha2Code: "kv", English: "Komi"}, - {Alpha3bCode: "kon", Alpha2Code: "kg", English: "Kongo"}, - {Alpha3bCode: "kor", Alpha2Code: "ko", English: "Korean"}, - {Alpha3bCode: "kua", Alpha2Code: "kj", English: "Kuanyama; Kwanyama"}, - {Alpha3bCode: "kur", Alpha2Code: "ku", English: "Kurdish"}, - {Alpha3bCode: "lao", Alpha2Code: "lo", English: "Lao"}, - {Alpha3bCode: "lat", Alpha2Code: "la", English: "Latin"}, - {Alpha3bCode: "lav", Alpha2Code: "lv", English: "Latvian"}, - {Alpha3bCode: "lim", Alpha2Code: "li", English: "Limburgan; Limburger; Limburgish"}, - {Alpha3bCode: "lin", Alpha2Code: "ln", English: "Lingala"}, - {Alpha3bCode: "lit", Alpha2Code: "lt", English: "Lithuanian"}, - {Alpha3bCode: "ltz", Alpha2Code: "lb", English: "Luxembourgish; Letzeburgesch"}, - {Alpha3bCode: "lub", Alpha2Code: "lu", English: "Luba-Katanga"}, - {Alpha3bCode: "lug", Alpha2Code: "lg", English: "Ganda"}, - {Alpha3bCode: "mac", Alpha2Code: "mk", English: "Macedonian"}, - {Alpha3bCode: "mah", Alpha2Code: "mh", English: "Marshallese"}, - {Alpha3bCode: "mal", Alpha2Code: "ml", English: "Malayalam"}, - {Alpha3bCode: "mao", Alpha2Code: "mi", English: "Maori"}, - {Alpha3bCode: "mar", Alpha2Code: "mr", English: "Marathi"}, - {Alpha3bCode: "may", Alpha2Code: "ms", English: "Malay"}, - {Alpha3bCode: "mlg", Alpha2Code: "mg", English: "Malagasy"}, - {Alpha3bCode: "mlt", Alpha2Code: "mt", English: "Maltese"}, - {Alpha3bCode: "mon", Alpha2Code: "mn", English: "Mongolian"}, - {Alpha3bCode: "nau", Alpha2Code: "na", English: "Nauru"}, - {Alpha3bCode: "nav", Alpha2Code: "nv", English: "Navajo; Navaho"}, - {Alpha3bCode: "nbl", Alpha2Code: "nr", English: "Ndebele, South; South Ndebele"}, - {Alpha3bCode: "nde", Alpha2Code: "nd", English: "Ndebele, North; North Ndebele"}, - {Alpha3bCode: "ndo", Alpha2Code: "ng", English: "Ndonga"}, - {Alpha3bCode: "nep", Alpha2Code: "ne", English: "Nepali"}, - {Alpha3bCode: "nno", Alpha2Code: "nn", English: "Norwegian Nynorsk; Nynorsk, Norwegian"}, - {Alpha3bCode: "nob", Alpha2Code: "nb", English: "Bokmål, Norwegian; Norwegian Bokmål"}, - {Alpha3bCode: "nor", Alpha2Code: "no", English: "Norwegian"}, - {Alpha3bCode: "nya", Alpha2Code: "ny", English: "Chichewa; Chewa; Nyanja"}, - {Alpha3bCode: "oci", Alpha2Code: "oc", English: "Occitan (post 1500); Provençal"}, - {Alpha3bCode: "oji", Alpha2Code: "oj", English: "Ojibwa"}, - {Alpha3bCode: "ori", Alpha2Code: "or", English: "Oriya"}, - {Alpha3bCode: "orm", Alpha2Code: "om", English: "Oromo"}, - {Alpha3bCode: "oss", Alpha2Code: "os", English: "Ossetian; Ossetic"}, - {Alpha3bCode: "pan", Alpha2Code: "pa", English: "Panjabi; Punjabi"}, - {Alpha3bCode: "per", Alpha2Code: "fa", English: "Persian"}, - {Alpha3bCode: "pli", Alpha2Code: "pi", English: "Pali"}, - {Alpha3bCode: "pol", Alpha2Code: "pl", English: "Polish"}, - {Alpha3bCode: "por", Alpha2Code: "pt", English: "Portuguese"}, - {Alpha3bCode: "pus", Alpha2Code: "ps", English: "Pushto; Pashto"}, - {Alpha3bCode: "que", Alpha2Code: "qu", English: "Quechua"}, - {Alpha3bCode: "roh", Alpha2Code: "rm", English: "Romansh"}, - {Alpha3bCode: "rum", Alpha2Code: "ro", English: "Romanian; Moldavian; Moldovan"}, - {Alpha3bCode: "run", Alpha2Code: "rn", English: "Rundi"}, - {Alpha3bCode: "rus", Alpha2Code: "ru", English: "Russian"}, - {Alpha3bCode: "sag", Alpha2Code: "sg", English: "Sango"}, - {Alpha3bCode: "san", Alpha2Code: "sa", English: "Sanskrit"}, - {Alpha3bCode: "sin", Alpha2Code: "si", English: "Sinhala; Sinhalese"}, - {Alpha3bCode: "slo", Alpha2Code: "sk", English: "Slovak"}, - {Alpha3bCode: "slv", Alpha2Code: "sl", English: "Slovenian"}, - {Alpha3bCode: "sme", Alpha2Code: "se", English: "Northern Sami"}, - {Alpha3bCode: "smo", Alpha2Code: "sm", English: "Samoan"}, - {Alpha3bCode: "sna", Alpha2Code: "sn", English: "Shona"}, - {Alpha3bCode: "snd", Alpha2Code: "sd", English: "Sindhi"}, - {Alpha3bCode: "som", Alpha2Code: "so", English: "Somali"}, - {Alpha3bCode: "sot", Alpha2Code: "st", English: "Sotho, Southern"}, - {Alpha3bCode: "spa", Alpha2Code: "es", English: "Spanish; Castilian"}, - {Alpha3bCode: "srd", Alpha2Code: "sc", English: "Sardinian"}, - {Alpha3bCode: "srp", Alpha2Code: "sr", English: "Serbian"}, - {Alpha3bCode: "ssw", Alpha2Code: "ss", English: "Swati"}, - {Alpha3bCode: "sun", Alpha2Code: "su", English: "Sundanese"}, - {Alpha3bCode: "swa", Alpha2Code: "sw", English: "Swahili"}, - {Alpha3bCode: "swe", Alpha2Code: "sv", English: "Swedish"}, - {Alpha3bCode: "tah", Alpha2Code: "ty", English: "Tahitian"}, - {Alpha3bCode: "tam", Alpha2Code: "ta", English: "Tamil"}, - {Alpha3bCode: "tat", Alpha2Code: "tt", English: "Tatar"}, - {Alpha3bCode: "tel", Alpha2Code: "te", English: "Telugu"}, - {Alpha3bCode: "tgk", Alpha2Code: "tg", English: "Tajik"}, - {Alpha3bCode: "tgl", Alpha2Code: "tl", English: "Tagalog"}, - {Alpha3bCode: "tha", Alpha2Code: "th", English: "Thai"}, - {Alpha3bCode: "tib", Alpha2Code: "bo", English: "Tibetan"}, - {Alpha3bCode: "tir", Alpha2Code: "ti", English: "Tigrinya"}, - {Alpha3bCode: "ton", Alpha2Code: "to", English: "Tonga (Tonga Islands)"}, - {Alpha3bCode: "tsn", Alpha2Code: "tn", English: "Tswana"}, - {Alpha3bCode: "tso", Alpha2Code: "ts", English: "Tsonga"}, - {Alpha3bCode: "tuk", Alpha2Code: "tk", English: "Turkmen"}, - {Alpha3bCode: "tur", Alpha2Code: "tr", English: "Turkish"}, - {Alpha3bCode: "twi", Alpha2Code: "tw", English: "Twi"}, - {Alpha3bCode: "uig", Alpha2Code: "ug", English: "Uighur; Uyghur"}, - {Alpha3bCode: "ukr", Alpha2Code: "uk", English: "Ukrainian"}, - {Alpha3bCode: "urd", Alpha2Code: "ur", English: "Urdu"}, - {Alpha3bCode: "uzb", Alpha2Code: "uz", English: "Uzbek"}, - {Alpha3bCode: "ven", Alpha2Code: "ve", English: "Venda"}, - {Alpha3bCode: "vie", Alpha2Code: "vi", English: "Vietnamese"}, - {Alpha3bCode: "vol", Alpha2Code: "vo", English: "Volapük"}, - {Alpha3bCode: "wel", Alpha2Code: "cy", English: "Welsh"}, - {Alpha3bCode: "wln", Alpha2Code: "wa", English: "Walloon"}, - {Alpha3bCode: "wol", Alpha2Code: "wo", English: "Wolof"}, - {Alpha3bCode: "xho", Alpha2Code: "xh", English: "Xhosa"}, - {Alpha3bCode: "yid", Alpha2Code: "yi", English: "Yiddish"}, - {Alpha3bCode: "yor", Alpha2Code: "yo", English: "Yoruba"}, - {Alpha3bCode: "zha", Alpha2Code: "za", English: "Zhuang; Chuang"}, - {Alpha3bCode: "zul", Alpha2Code: "zu", English: "Zulu"}, -} diff --git a/vendor/github.com/asaskevich/govalidator/utils.go b/vendor/github.com/asaskevich/govalidator/utils.go deleted file mode 100644 index 6a8871c1c..000000000 --- a/vendor/github.com/asaskevich/govalidator/utils.go +++ /dev/null @@ -1,264 +0,0 @@ -package govalidator - -import ( - "errors" - "fmt" - "html" - "math" - "path" - "regexp" - "strings" - "unicode" - "unicode/utf8" -) - -// Contains check if the string contains the substring. -func Contains(str, substring string) bool { - return strings.Contains(str, substring) -} - -// Matches check if string matches the pattern (pattern is regular expression) -// In case of error return false -func Matches(str, pattern string) bool { - match, _ := regexp.MatchString(pattern, str) - return match -} - -// LeftTrim trim characters from the left-side of the input. -// If second argument is empty, it's will be remove leading spaces. -func LeftTrim(str, chars string) string { - if chars == "" { - return strings.TrimLeftFunc(str, unicode.IsSpace) - } - r, _ := regexp.Compile("^[" + chars + "]+") - return r.ReplaceAllString(str, "") -} - -// RightTrim trim characters from the right-side of the input. -// If second argument is empty, it's will be remove spaces. -func RightTrim(str, chars string) string { - if chars == "" { - return strings.TrimRightFunc(str, unicode.IsSpace) - } - r, _ := regexp.Compile("[" + chars + "]+$") - return r.ReplaceAllString(str, "") -} - -// Trim trim characters from both sides of the input. -// If second argument is empty, it's will be remove spaces. -func Trim(str, chars string) string { - return LeftTrim(RightTrim(str, chars), chars) -} - -// WhiteList remove characters that do not appear in the whitelist. -func WhiteList(str, chars string) string { - pattern := "[^" + chars + "]+" - r, _ := regexp.Compile(pattern) - return r.ReplaceAllString(str, "") -} - -// BlackList remove characters that appear in the blacklist. -func BlackList(str, chars string) string { - pattern := "[" + chars + "]+" - r, _ := regexp.Compile(pattern) - return r.ReplaceAllString(str, "") -} - -// StripLow remove characters with a numerical value < 32 and 127, mostly control characters. -// If keep_new_lines is true, newline characters are preserved (\n and \r, hex 0xA and 0xD). -func StripLow(str string, keepNewLines bool) string { - chars := "" - if keepNewLines { - chars = "\x00-\x09\x0B\x0C\x0E-\x1F\x7F" - } else { - chars = "\x00-\x1F\x7F" - } - return BlackList(str, chars) -} - -// ReplacePattern replace regular expression pattern in string -func ReplacePattern(str, pattern, replace string) string { - r, _ := regexp.Compile(pattern) - return r.ReplaceAllString(str, replace) -} - -// Escape replace <, >, & and " with HTML entities. -var Escape = html.EscapeString - -func addSegment(inrune, segment []rune) []rune { - if len(segment) == 0 { - return inrune - } - if len(inrune) != 0 { - inrune = append(inrune, '_') - } - inrune = append(inrune, segment...) - return inrune -} - -// UnderscoreToCamelCase converts from underscore separated form to camel case form. -// Ex.: my_func => MyFunc -func UnderscoreToCamelCase(s string) string { - return strings.Replace(strings.Title(strings.Replace(strings.ToLower(s), "_", " ", -1)), " ", "", -1) -} - -// CamelCaseToUnderscore converts from camel case form to underscore separated form. -// Ex.: MyFunc => my_func -func CamelCaseToUnderscore(str string) string { - var output []rune - var segment []rune - for _, r := range str { - - // not treat number as separate segment - if !unicode.IsLower(r) && string(r) != "_" && !unicode.IsNumber(r) { - output = addSegment(output, segment) - segment = nil - } - segment = append(segment, unicode.ToLower(r)) - } - output = addSegment(output, segment) - return string(output) -} - -// Reverse return reversed string -func Reverse(s string) string { - r := []rune(s) - for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { - r[i], r[j] = r[j], r[i] - } - return string(r) -} - -// GetLines split string by "\n" and return array of lines -func GetLines(s string) []string { - return strings.Split(s, "\n") -} - -// GetLine return specified line of multiline string -func GetLine(s string, index int) (string, error) { - lines := GetLines(s) - if index < 0 || index >= len(lines) { - return "", errors.New("line index out of bounds") - } - return lines[index], nil -} - -// RemoveTags remove all tags from HTML string -func RemoveTags(s string) string { - return ReplacePattern(s, "<[^>]*>", "") -} - -// SafeFileName return safe string that can be used in file names -func SafeFileName(str string) string { - name := strings.ToLower(str) - name = path.Clean(path.Base(name)) - name = strings.Trim(name, " ") - separators, err := regexp.Compile(`[ &_=+:]`) - if err == nil { - name = separators.ReplaceAllString(name, "-") - } - legal, err := regexp.Compile(`[^[:alnum:]-.]`) - if err == nil { - name = legal.ReplaceAllString(name, "") - } - for strings.Contains(name, "--") { - name = strings.Replace(name, "--", "-", -1) - } - return name -} - -// NormalizeEmail canonicalize an email address. -// The local part of the email address is lowercased for all domains; the hostname is always lowercased and -// the local part of the email address is always lowercased for hosts that are known to be case-insensitive (currently only GMail). -// Normalization follows special rules for known providers: currently, GMail addresses have dots removed in the local part and -// are stripped of tags (e.g. some.one+tag@gmail.com becomes someone@gmail.com) and all @googlemail.com addresses are -// normalized to @gmail.com. -func NormalizeEmail(str string) (string, error) { - if !IsEmail(str) { - return "", fmt.Errorf("%s is not an email", str) - } - parts := strings.Split(str, "@") - parts[0] = strings.ToLower(parts[0]) - parts[1] = strings.ToLower(parts[1]) - if parts[1] == "gmail.com" || parts[1] == "googlemail.com" { - parts[1] = "gmail.com" - parts[0] = strings.Split(ReplacePattern(parts[0], `\.`, ""), "+")[0] - } - return strings.Join(parts, "@"), nil -} - -// Truncate a string to the closest length without breaking words. -func Truncate(str string, length int, ending string) string { - var aftstr, befstr string - if len(str) > length { - words := strings.Fields(str) - before, present := 0, 0 - for i := range words { - befstr = aftstr - before = present - aftstr = aftstr + words[i] + " " - present = len(aftstr) - if present > length && i != 0 { - if (length - before) < (present - length) { - return Trim(befstr, " /\\.,\"'#!?&@+-") + ending - } - return Trim(aftstr, " /\\.,\"'#!?&@+-") + ending - } - } - } - - return str -} - -// PadLeft pad left side of string if size of string is less then indicated pad length -func PadLeft(str string, padStr string, padLen int) string { - return buildPadStr(str, padStr, padLen, true, false) -} - -// PadRight pad right side of string if size of string is less then indicated pad length -func PadRight(str string, padStr string, padLen int) string { - return buildPadStr(str, padStr, padLen, false, true) -} - -// PadBoth pad sides of string if size of string is less then indicated pad length -func PadBoth(str string, padStr string, padLen int) string { - return buildPadStr(str, padStr, padLen, true, true) -} - -// PadString either left, right or both sides, not the padding string can be unicode and more then one -// character -func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string { - - // When padded length is less then the current string size - if padLen < utf8.RuneCountInString(str) { - return str - } - - padLen -= utf8.RuneCountInString(str) - - targetLen := padLen - - targetLenLeft := targetLen - targetLenRight := targetLen - if padLeft && padRight { - targetLenLeft = padLen / 2 - targetLenRight = padLen - targetLenLeft - } - - strToRepeatLen := utf8.RuneCountInString(padStr) - - repeatTimes := int(math.Ceil(float64(targetLen) / float64(strToRepeatLen))) - repeatedString := strings.Repeat(padStr, repeatTimes) - - leftSide := "" - if padLeft { - leftSide = repeatedString[0:targetLenLeft] - } - - rightSide := "" - if padRight { - rightSide = repeatedString[0:targetLenRight] - } - - return leftSide + str + rightSide -} diff --git a/vendor/github.com/asaskevich/govalidator/utils_benchmark_test.go b/vendor/github.com/asaskevich/govalidator/utils_benchmark_test.go deleted file mode 100644 index 2ac4b6102..000000000 --- a/vendor/github.com/asaskevich/govalidator/utils_benchmark_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package govalidator - -import "testing" - -func BenchmarkContains(b *testing.B) { - b.ResetTimer() - for n := 0; n < b.N; n++ { - Contains("a0b01c012deffghijklmnopqrstu0123456vwxyz", "0123456789") - } -} - -func BenchmarkMatches(b *testing.B) { - b.ResetTimer() - for n := 0; n < b.N; n++ { - Matches("alfkjl12309fdjldfsa209jlksdfjLAKJjs9uJH234", "[\\w\\d]+") - } -} diff --git a/vendor/github.com/asaskevich/govalidator/utils_test.go b/vendor/github.com/asaskevich/govalidator/utils_test.go deleted file mode 100644 index 97c97a534..000000000 --- a/vendor/github.com/asaskevich/govalidator/utils_test.go +++ /dev/null @@ -1,502 +0,0 @@ -package govalidator - -import ( - "reflect" - "testing" -) - -func TestContains(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 string - expected bool - }{ - {"abacada", "", true}, - {"abacada", "ritir", false}, - {"abacada", "a", true}, - {"abacada", "aca", true}, - } - for _, test := range tests { - actual := Contains(test.param1, test.param2) - if actual != test.expected { - t.Errorf("Expected Contains(%q,%q) to be %v, got %v", test.param1, test.param2, test.expected, actual) - } - } -} - -func TestMatches(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 string - expected bool - }{ - {"123456789", "[0-9]+", true}, - {"abacada", "cab$", false}, - {"111222333", "((111|222|333)+)+", true}, - {"abacaba", "((123+]", false}, - } - for _, test := range tests { - actual := Matches(test.param1, test.param2) - if actual != test.expected { - t.Errorf("Expected Matches(%q,%q) to be %v, got %v", test.param1, test.param2, test.expected, actual) - } - } -} - -func TestLeftTrim(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 string - expected string - }{ - {" \r\n\tfoo \r\n\t ", "", "foo \r\n\t "}, - {"010100201000", "01", "201000"}, - } - for _, test := range tests { - actual := LeftTrim(test.param1, test.param2) - if actual != test.expected { - t.Errorf("Expected LeftTrim(%q,%q) to be %v, got %v", test.param1, test.param2, test.expected, actual) - } - } -} - -func TestRightTrim(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 string - expected string - }{ - {" \r\n\tfoo \r\n\t ", "", " \r\n\tfoo"}, - {"010100201000", "01", "0101002"}, - } - for _, test := range tests { - actual := RightTrim(test.param1, test.param2) - if actual != test.expected { - t.Errorf("Expected RightTrim(%q,%q) to be %v, got %v", test.param1, test.param2, test.expected, actual) - } - } -} - -func TestTrim(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 string - expected string - }{ - {" \r\n\tfoo \r\n\t ", "", "foo"}, - {"010100201000", "01", "2"}, - {"1234567890987654321", "1-8", "909"}, - } - for _, test := range tests { - actual := Trim(test.param1, test.param2) - if actual != test.expected { - t.Errorf("Expected Trim(%q,%q) to be %v, got %v", test.param1, test.param2, test.expected, actual) - } - } -} - -// This small example illustrate how to work with Trim function. -func ExampleTrim() { - // Remove from left and right spaces and "\r", "\n", "\t" characters - println(Trim(" \r\r\ntext\r \t\n", "") == "text") - // Remove from left and right characters that are between "1" and "8". - // "1-8" is like full list "12345678". - println(Trim("1234567890987654321", "1-8") == "909") -} - -func TestWhiteList(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 string - expected string - }{ - {"abcdef", "abc", "abc"}, - {"aaaaaaaaaabbbbbbbbbb", "abc", "aaaaaaaaaabbbbbbbbbb"}, - {"a1b2c3", "abc", "abc"}, - {" ", "abc", ""}, - {"a3a43a5a4a3a2a23a4a5a4a3a4", "a-z", "aaaaaaaaaaaa"}, - } - for _, test := range tests { - actual := WhiteList(test.param1, test.param2) - if actual != test.expected { - t.Errorf("Expected WhiteList(%q,%q) to be %v, got %v", test.param1, test.param2, test.expected, actual) - } - } -} - -// This small example illustrate how to work with WhiteList function. -func ExampleWhiteList() { - // Remove all characters from string ignoring characters between "a" and "z" - println(WhiteList("a3a43a5a4a3a2a23a4a5a4a3a4", "a-z") == "aaaaaaaaaaaa") -} - -func TestBlackList(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 string - expected string - }{ - {"abcdef", "abc", "def"}, - {"aaaaaaaaaabbbbbbbbbb", "abc", ""}, - {"a1b2c3", "abc", "123"}, - {" ", "abc", " "}, - {"a3a43a5a4a3a2a23a4a5a4a3a4", "a-z", "34354322345434"}, - } - for _, test := range tests { - actual := BlackList(test.param1, test.param2) - if actual != test.expected { - t.Errorf("Expected BlackList(%q,%q) to be %v, got %v", test.param1, test.param2, test.expected, actual) - } - } -} - -func TestStripLow(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 bool - expected string - }{ - {"foo\x00", false, "foo"}, - {"\x7Ffoo\x02", false, "foo"}, - {"\x01\x09", false, ""}, - {"foo\x0A\x0D", false, "foo"}, - {"perch\u00e9", false, "perch\u00e9"}, - {"\u20ac", false, "\u20ac"}, - {"\u2206\x0A", false, "\u2206"}, - {"foo\x0A\x0D", true, "foo\x0A\x0D"}, - {"\x03foo\x0A\x0D", true, "foo\x0A\x0D"}, - } - for _, test := range tests { - actual := StripLow(test.param1, test.param2) - if actual != test.expected { - t.Errorf("Expected StripLow(%q,%t) to be %v, got %v", test.param1, test.param2, test.expected, actual) - } - } -} - -func TestReplacePattern(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 string - param3 string - expected string - }{ - {"ab123ba", "[0-9]+", "aca", "abacaba"}, - {"abacaba", "[0-9]+", "aca", "abacaba"}, - {"httpftp://github.comio", "(ftp|io)", "", "http://github.com"}, - {"aaaaaaaaaa", "a", "", ""}, - {"http123123ftp://git534543hub.comio", "(ftp|io|[0-9]+)", "", "http://github.com"}, - } - for _, test := range tests { - actual := ReplacePattern(test.param1, test.param2, test.param3) - if actual != test.expected { - t.Errorf("Expected ReplacePattern(%q,%q,%q) to be %v, got %v", test.param1, test.param2, test.param3, test.expected, actual) - } - } -} - -// This small example illustrate how to work with ReplacePattern function. -func ExampleReplacePattern() { - // Replace in "http123123ftp://git534543hub.comio" following (pattern "(ftp|io|[0-9]+)"): - // - Sequence "ftp". - // - Sequence "io". - // - Sequence of digits. - // with empty string. - println(ReplacePattern("http123123ftp://git534543hub.comio", "(ftp|io|[0-9]+)", "") == "http://github.com") -} - -func TestEscape(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected string - }{ - {`foo&bar`, "<img alt="foo&bar">"}, - } - for _, test := range tests { - actual := Escape(test.param) - if actual != test.expected { - t.Errorf("Expected Escape(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestUnderscoreToCamelCase(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected string - }{ - {"a_b_c", "ABC"}, - {"my_func", "MyFunc"}, - {"1ab_cd", "1abCd"}, - } - for _, test := range tests { - actual := UnderscoreToCamelCase(test.param) - if actual != test.expected { - t.Errorf("Expected UnderscoreToCamelCase(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestCamelCaseToUnderscore(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected string - }{ - {"MyFunc", "my_func"}, - {"ABC", "a_b_c"}, - {"1B", "1_b"}, - {"foo_bar", "foo_bar"}, - {"FooV2Bar", "foo_v2_bar"}, - } - for _, test := range tests { - actual := CamelCaseToUnderscore(test.param) - if actual != test.expected { - t.Errorf("Expected CamelCaseToUnderscore(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestReverse(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected string - }{ - {"abc", "cba"}, - {"カタカナ", "ナカタカ"}, - } - for _, test := range tests { - actual := Reverse(test.param) - if actual != test.expected { - t.Errorf("Expected Reverse(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestGetLines(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected []string - }{ - {"abc", []string{"abc"}}, - {"a\nb\nc", []string{"a", "b", "c"}}, - } - for _, test := range tests { - actual := GetLines(test.param) - if !reflect.DeepEqual(actual, test.expected) { - t.Errorf("Expected GetLines(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestGetLine(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 int - expected string - }{ - {"abc", 0, "abc"}, - {"a\nb\nc", 0, "a"}, - {"abc", -1, ""}, - {"abacaba\n", 1, ""}, - {"abc", 3, ""}, - } - for _, test := range tests { - actual, _ := GetLine(test.param1, test.param2) - if actual != test.expected { - t.Errorf("Expected GetLine(%q, %d) to be %v, got %v", test.param1, test.param2, test.expected, actual) - } - } -} - -func TestRemoveTags(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected string - }{ - {"abc", "abc"}, - {"", ""}, - {"

Text

", "Text"}, - {`Link`, "Link"}, - } - for _, test := range tests { - actual := RemoveTags(test.param) - if actual != test.expected { - t.Errorf("Expected RemoveTags(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestSafeFileName(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected string - }{ - {"abc", "abc"}, - {"123456789 '_-?ASDF@£$%£%^é.html", "123456789-asdf.html"}, - {"ReadMe.md", "readme.md"}, - {"file:///c:/test.go", "test.go"}, - {"../../../Hello World!.txt", "hello-world.txt"}, - } - for _, test := range tests { - actual := SafeFileName(test.param) - if actual != test.expected { - t.Errorf("Expected SafeFileName(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestNormalizeEmail(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected string - }{ - {`test@me.com`, `test@me.com`}, - {`some.name@gmail.com`, `somename@gmail.com`}, - {`some.name@googlemail.com`, `somename@gmail.com`}, - {`some.name+extension@gmail.com`, `somename@gmail.com`}, - {`some.name+extension@googlemail.com`, `somename@gmail.com`}, - {`some.name.middlename+extension@gmail.com`, `somenamemiddlename@gmail.com`}, - {`some.name.middlename+extension@googlemail.com`, `somenamemiddlename@gmail.com`}, - {`some.name.midd.lena.me.+extension@gmail.com`, `somenamemiddlename@gmail.com`}, - {`some.name.midd.lena.me.+extension@googlemail.com`, `somenamemiddlename@gmail.com`}, - {`some.name+extension@unknown.com`, `some.name+extension@unknown.com`}, - // TODO: {`hans@m端ller.com`, `hans@m端ller.com`}, - {`hans`, ``}, - } - for _, test := range tests { - actual, err := NormalizeEmail(test.param) - if actual != test.expected { - t.Errorf("Expected NormalizeEmail(%q) to be %v, got %v, err %v", test.param, test.expected, actual, err) - } - } -} - -func TestTruncate(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 int - param3 string - expected string - }{ - {`Lorem ipsum dolor sit amet, consectetur adipiscing elit.`, 25, `...`, `Lorem ipsum dolor sit amet...`}, - {`Measuring programming progress by lines of code is like measuring aircraft building progress by weight.`, 35, ` new born babies!`, `Measuring programming progress by new born babies!`}, - {`Testestestestestestestestestest testestestestestestestestest`, 7, `...`, `Testestestestestestestestestest...`}, - {`Testing`, 7, `...`, `Testing`}, - } - for _, test := range tests { - actual := Truncate(test.param1, test.param2, test.param3) - if actual != test.expected { - t.Errorf("Expected Truncate(%q, %d, %q) to be %v, got %v", test.param1, test.param2, test.param3, test.expected, actual) - } - } -} - -func TestPadLeft(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 string - param3 int - expected string - }{ - {"こんにちは", "xyz", 12, "xyzxyzxこんにちは"}, - {"こんにちは", "xyz", 11, "xyzxyzこんにちは"}, - {"abc", "x", 5, "xxabc"}, - {"abc", "xyz", 5, "xyabc"}, - {"abcde", "xyz", 5, "abcde"}, - {"abcde", "xyz", 4, "abcde"}, - } - for _, test := range tests { - actual := PadLeft(test.param1, test.param2, test.param3) - if actual != test.expected { - t.Errorf("Expected PadLeft(%q,%q,%q) to be %v, got %v", test.param1, test.param2, test.param3, test.expected, actual) - } - } -} - -func TestPadRight(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 string - param3 int - expected string - }{ - {"こんにちは", "xyz", 12, "こんにちはxyzxyzx"}, - {"こんにちは", "xyz", 11, "こんにちはxyzxyz"}, - {"abc", "x", 5, "abcxx"}, - {"abc", "xyz", 5, "abcxy"}, - {"abcde", "xyz", 5, "abcde"}, - {"abcde", "xyz", 4, "abcde"}, - } - for _, test := range tests { - actual := PadRight(test.param1, test.param2, test.param3) - if actual != test.expected { - t.Errorf("Expected PadRight(%q,%q,%q) to be %v, got %v", test.param1, test.param2, test.param3, test.expected, actual) - } - } -} - -func TestPadBoth(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 string - param3 int - expected string - }{ - {"こんにちは", "xyz", 12, "xyzこんにちはxyzx"}, - {"こんにちは", "xyz", 11, "xyzこんにちはxyz"}, - {"abc", "x", 5, "xabcx"}, - {"abc", "xyz", 5, "xabcx"}, - {"abcde", "xyz", 5, "abcde"}, - {"abcde", "xyz", 4, "abcde"}, - } - for _, test := range tests { - actual := PadBoth(test.param1, test.param2, test.param3) - if actual != test.expected { - t.Errorf("Expected PadBoth(%q,%q,%q) to be %v, got %v", test.param1, test.param2, test.param3, test.expected, actual) - } - } -} diff --git a/vendor/github.com/asaskevich/govalidator/validator.go b/vendor/github.com/asaskevich/govalidator/validator.go deleted file mode 100644 index 071f43c09..000000000 --- a/vendor/github.com/asaskevich/govalidator/validator.go +++ /dev/null @@ -1,1213 +0,0 @@ -// Package govalidator is package of validators and sanitizers for strings, structs and collections. -package govalidator - -import ( - "bytes" - "crypto/rsa" - "crypto/x509" - "encoding/base64" - "encoding/json" - "encoding/pem" - "fmt" - "io/ioutil" - "net" - "net/url" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - "time" - "unicode" - "unicode/utf8" -) - -var ( - fieldsRequiredByDefault bool - notNumberRegexp = regexp.MustCompile("[^0-9]+") - whiteSpacesAndMinus = regexp.MustCompile("[\\s-]+") - paramsRegexp = regexp.MustCompile("\\(.*\\)$") -) - -const maxURLRuneCount = 2083 -const minURLRuneCount = 3 -const RF3339WithoutZone = "2006-01-02T15:04:05" - -// SetFieldsRequiredByDefault causes validation to fail when struct fields -// do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). -// This struct definition will fail govalidator.ValidateStruct() (and the field values do not matter): -// type exampleStruct struct { -// Name string `` -// Email string `valid:"email"` -// This, however, will only fail when Email is empty or an invalid email address: -// type exampleStruct2 struct { -// Name string `valid:"-"` -// Email string `valid:"email"` -// Lastly, this will only fail when Email is an invalid email address but not when it's empty: -// type exampleStruct2 struct { -// Name string `valid:"-"` -// Email string `valid:"email,optional"` -func SetFieldsRequiredByDefault(value bool) { - fieldsRequiredByDefault = value -} - -// IsEmail check if the string is an email. -func IsEmail(email string) bool { - if len(email) < 6 || len(email) > 254 { - return false - } - at := strings.LastIndex(email, "@") - if at <= 0 || at > len(email)-3 { - return false - } - user := email[:at] - host := email[at+1:] - if len(user) > 64 { - return false - } - if userDotRegexp.MatchString(user) || !userRegexp.MatchString(user) || !hostRegexp.MatchString(host) { - return false - } - switch host { - case "localhost", "example.com": - return true - } - if _, err := net.LookupMX(host); err != nil { - if _, err := net.LookupIP(host); err != nil { - return false - } - } - - return true -} - -// IsURL check if the string is an URL. -func IsURL(str string) bool { - if str == "" || utf8.RuneCountInString(str) >= maxURLRuneCount || len(str) <= minURLRuneCount || strings.HasPrefix(str, ".") { - return false - } - strTemp := str - if strings.Index(str, ":") >= 0 && strings.Index(str, "://") == -1 { - // support no indicated urlscheme but with colon for port number - // http:// is appended so url.Parse will succeed, strTemp used so it does not impact rxURL.MatchString - strTemp = "http://" + str - } - u, err := url.Parse(strTemp) - if err != nil { - return false - } - if strings.HasPrefix(u.Host, ".") { - return false - } - if u.Host == "" && (u.Path != "" && !strings.Contains(u.Path, ".")) { - return false - } - return rxURL.MatchString(str) -} - -// IsRequestURL check if the string rawurl, assuming -// it was received in an HTTP request, is a valid -// URL confirm to RFC 3986 -func IsRequestURL(rawurl string) bool { - url, err := url.ParseRequestURI(rawurl) - if err != nil { - return false //Couldn't even parse the rawurl - } - if len(url.Scheme) == 0 { - return false //No Scheme found - } - return true -} - -// IsRequestURI check if the string rawurl, assuming -// it was received in an HTTP request, is an -// absolute URI or an absolute path. -func IsRequestURI(rawurl string) bool { - _, err := url.ParseRequestURI(rawurl) - return err == nil -} - -// IsAlpha check if the string contains only letters (a-zA-Z). Empty string is valid. -func IsAlpha(str string) bool { - if IsNull(str) { - return true - } - return rxAlpha.MatchString(str) -} - -//IsUTFLetter check if the string contains only unicode letter characters. -//Similar to IsAlpha but for all languages. Empty string is valid. -func IsUTFLetter(str string) bool { - if IsNull(str) { - return true - } - - for _, c := range str { - if !unicode.IsLetter(c) { - return false - } - } - return true - -} - -// IsAlphanumeric check if the string contains only letters and numbers. Empty string is valid. -func IsAlphanumeric(str string) bool { - if IsNull(str) { - return true - } - return rxAlphanumeric.MatchString(str) -} - -// IsUTFLetterNumeric check if the string contains only unicode letters and numbers. Empty string is valid. -func IsUTFLetterNumeric(str string) bool { - if IsNull(str) { - return true - } - for _, c := range str { - if !unicode.IsLetter(c) && !unicode.IsNumber(c) { //letters && numbers are ok - return false - } - } - return true - -} - -// IsNumeric check if the string contains only numbers. Empty string is valid. -func IsNumeric(str string) bool { - if IsNull(str) { - return true - } - return rxNumeric.MatchString(str) -} - -// IsUTFNumeric check if the string contains only unicode numbers of any kind. -// Numbers can be 0-9 but also Fractions ¾,Roman Ⅸ and Hangzhou 〩. Empty string is valid. -func IsUTFNumeric(str string) bool { - if IsNull(str) { - return true - } - if strings.IndexAny(str, "+-") > 0 { - return false - } - if len(str) > 1 { - str = strings.TrimPrefix(str, "-") - str = strings.TrimPrefix(str, "+") - } - for _, c := range str { - if unicode.IsNumber(c) == false { //numbers && minus sign are ok - return false - } - } - return true - -} - -// IsUTFDigit check if the string contains only unicode radix-10 decimal digits. Empty string is valid. -func IsUTFDigit(str string) bool { - if IsNull(str) { - return true - } - if strings.IndexAny(str, "+-") > 0 { - return false - } - if len(str) > 1 { - str = strings.TrimPrefix(str, "-") - str = strings.TrimPrefix(str, "+") - } - for _, c := range str { - if !unicode.IsDigit(c) { //digits && minus sign are ok - return false - } - } - return true - -} - -// IsHexadecimal check if the string is a hexadecimal number. -func IsHexadecimal(str string) bool { - return rxHexadecimal.MatchString(str) -} - -// IsHexcolor check if the string is a hexadecimal color. -func IsHexcolor(str string) bool { - return rxHexcolor.MatchString(str) -} - -// IsRGBcolor check if the string is a valid RGB color in form rgb(RRR, GGG, BBB). -func IsRGBcolor(str string) bool { - return rxRGBcolor.MatchString(str) -} - -// IsLowerCase check if the string is lowercase. Empty string is valid. -func IsLowerCase(str string) bool { - if IsNull(str) { - return true - } - return str == strings.ToLower(str) -} - -// IsUpperCase check if the string is uppercase. Empty string is valid. -func IsUpperCase(str string) bool { - if IsNull(str) { - return true - } - return str == strings.ToUpper(str) -} - -// HasLowerCase check if the string contains at least 1 lowercase. Empty string is valid. -func HasLowerCase(str string) bool { - if IsNull(str) { - return true - } - return rxHasLowerCase.MatchString(str) -} - -// HasUpperCase check if the string contians as least 1 uppercase. Empty string is valid. -func HasUpperCase(str string) bool { - if IsNull(str) { - return true - } - return rxHasUpperCase.MatchString(str) -} - -// IsInt check if the string is an integer. Empty string is valid. -func IsInt(str string) bool { - if IsNull(str) { - return true - } - return rxInt.MatchString(str) -} - -// IsFloat check if the string is a float. -func IsFloat(str string) bool { - return str != "" && rxFloat.MatchString(str) -} - -// IsDivisibleBy check if the string is a number that's divisible by another. -// If second argument is not valid integer or zero, it's return false. -// Otherwise, if first argument is not valid integer or zero, it's return true (Invalid string converts to zero). -func IsDivisibleBy(str, num string) bool { - f, _ := ToFloat(str) - p := int64(f) - q, _ := ToInt(num) - if q == 0 { - return false - } - return (p == 0) || (p%q == 0) -} - -// IsNull check if the string is null. -func IsNull(str string) bool { - return len(str) == 0 -} - -// IsByteLength check if the string's length (in bytes) falls in a range. -func IsByteLength(str string, min, max int) bool { - return len(str) >= min && len(str) <= max -} - -// IsUUIDv3 check if the string is a UUID version 3. -func IsUUIDv3(str string) bool { - return rxUUID3.MatchString(str) -} - -// IsUUIDv4 check if the string is a UUID version 4. -func IsUUIDv4(str string) bool { - return rxUUID4.MatchString(str) -} - -// IsUUIDv5 check if the string is a UUID version 5. -func IsUUIDv5(str string) bool { - return rxUUID5.MatchString(str) -} - -// IsUUID check if the string is a UUID (version 3, 4 or 5). -func IsUUID(str string) bool { - return rxUUID.MatchString(str) -} - -// IsCreditCard check if the string is a credit card. -func IsCreditCard(str string) bool { - sanitized := notNumberRegexp.ReplaceAllString(str, "") - if !rxCreditCard.MatchString(sanitized) { - return false - } - var sum int64 - var digit string - var tmpNum int64 - var shouldDouble bool - for i := len(sanitized) - 1; i >= 0; i-- { - digit = sanitized[i:(i + 1)] - tmpNum, _ = ToInt(digit) - if shouldDouble { - tmpNum *= 2 - if tmpNum >= 10 { - sum += ((tmpNum % 10) + 1) - } else { - sum += tmpNum - } - } else { - sum += tmpNum - } - shouldDouble = !shouldDouble - } - - if sum%10 == 0 { - return true - } - return false -} - -// IsISBN10 check if the string is an ISBN version 10. -func IsISBN10(str string) bool { - return IsISBN(str, 10) -} - -// IsISBN13 check if the string is an ISBN version 13. -func IsISBN13(str string) bool { - return IsISBN(str, 13) -} - -// IsISBN check if the string is an ISBN (version 10 or 13). -// If version value is not equal to 10 or 13, it will be check both variants. -func IsISBN(str string, version int) bool { - sanitized := whiteSpacesAndMinus.ReplaceAllString(str, "") - var checksum int32 - var i int32 - if version == 10 { - if !rxISBN10.MatchString(sanitized) { - return false - } - for i = 0; i < 9; i++ { - checksum += (i + 1) * int32(sanitized[i]-'0') - } - if sanitized[9] == 'X' { - checksum += 10 * 10 - } else { - checksum += 10 * int32(sanitized[9]-'0') - } - if checksum%11 == 0 { - return true - } - return false - } else if version == 13 { - if !rxISBN13.MatchString(sanitized) { - return false - } - factor := []int32{1, 3} - for i = 0; i < 12; i++ { - checksum += factor[i%2] * int32(sanitized[i]-'0') - } - if (int32(sanitized[12]-'0'))-((10-(checksum%10))%10) == 0 { - return true - } - return false - } - return IsISBN(str, 10) || IsISBN(str, 13) -} - -// IsJSON check if the string is valid JSON (note: uses json.Unmarshal). -func IsJSON(str string) bool { - var js json.RawMessage - return json.Unmarshal([]byte(str), &js) == nil -} - -// IsMultibyte check if the string contains one or more multibyte chars. Empty string is valid. -func IsMultibyte(str string) bool { - if IsNull(str) { - return true - } - return rxMultibyte.MatchString(str) -} - -// IsASCII check if the string contains ASCII chars only. Empty string is valid. -func IsASCII(str string) bool { - if IsNull(str) { - return true - } - return rxASCII.MatchString(str) -} - -// IsPrintableASCII check if the string contains printable ASCII chars only. Empty string is valid. -func IsPrintableASCII(str string) bool { - if IsNull(str) { - return true - } - return rxPrintableASCII.MatchString(str) -} - -// IsFullWidth check if the string contains any full-width chars. Empty string is valid. -func IsFullWidth(str string) bool { - if IsNull(str) { - return true - } - return rxFullWidth.MatchString(str) -} - -// IsHalfWidth check if the string contains any half-width chars. Empty string is valid. -func IsHalfWidth(str string) bool { - if IsNull(str) { - return true - } - return rxHalfWidth.MatchString(str) -} - -// IsVariableWidth check if the string contains a mixture of full and half-width chars. Empty string is valid. -func IsVariableWidth(str string) bool { - if IsNull(str) { - return true - } - return rxHalfWidth.MatchString(str) && rxFullWidth.MatchString(str) -} - -// IsBase64 check if a string is base64 encoded. -func IsBase64(str string) bool { - return rxBase64.MatchString(str) -} - -// IsFilePath check is a string is Win or Unix file path and returns it's type. -func IsFilePath(str string) (bool, int) { - if rxWinPath.MatchString(str) { - //check windows path limit see: - // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath - if len(str[3:]) > 32767 { - return false, Win - } - return true, Win - } else if rxUnixPath.MatchString(str) { - return true, Unix - } - return false, Unknown -} - -// IsDataURI checks if a string is base64 encoded data URI such as an image -func IsDataURI(str string) bool { - dataURI := strings.Split(str, ",") - if !rxDataURI.MatchString(dataURI[0]) { - return false - } - return IsBase64(dataURI[1]) -} - -// IsISO3166Alpha2 checks if a string is valid two-letter country code -func IsISO3166Alpha2(str string) bool { - for _, entry := range ISO3166List { - if str == entry.Alpha2Code { - return true - } - } - return false -} - -// IsISO3166Alpha3 checks if a string is valid three-letter country code -func IsISO3166Alpha3(str string) bool { - for _, entry := range ISO3166List { - if str == entry.Alpha3Code { - return true - } - } - return false -} - -// IsISO693Alpha2 checks if a string is valid two-letter language code -func IsISO693Alpha2(str string) bool { - for _, entry := range ISO693List { - if str == entry.Alpha2Code { - return true - } - } - return false -} - -// IsISO693Alpha3b checks if a string is valid three-letter language code -func IsISO693Alpha3b(str string) bool { - for _, entry := range ISO693List { - if str == entry.Alpha3bCode { - return true - } - } - return false -} - -// IsDNSName will validate the given string as a DNS name -func IsDNSName(str string) bool { - if str == "" || len(strings.Replace(str, ".", "", -1)) > 255 { - // constraints already violated - return false - } - return !IsIP(str) && rxDNSName.MatchString(str) -} - -// IsHash checks if a string is a hash of type algorithm. -// Algorithm is one of ['md4', 'md5', 'sha1', 'sha256', 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b'] -func IsHash(str string, algorithm string) bool { - len := "0" - algo := strings.ToLower(algorithm) - - if algo == "crc32" || algo == "crc32b" { - len = "8" - } else if algo == "md5" || algo == "md4" || algo == "ripemd128" || algo == "tiger128" { - len = "32" - } else if algo == "sha1" || algo == "ripemd160" || algo == "tiger160" { - len = "40" - } else if algo == "tiger192" { - len = "48" - } else if algo == "sha256" { - len = "64" - } else if algo == "sha384" { - len = "96" - } else if algo == "sha512" { - len = "128" - } else { - return false - } - - return Matches(str, "^[a-f0-9]{"+len+"}$") -} - -// IsDialString validates the given string for usage with the various Dial() functions -func IsDialString(str string) bool { - - if h, p, err := net.SplitHostPort(str); err == nil && h != "" && p != "" && (IsDNSName(h) || IsIP(h)) && IsPort(p) { - return true - } - - return false -} - -// IsIP checks if a string is either IP version 4 or 6. -func IsIP(str string) bool { - return net.ParseIP(str) != nil -} - -// IsPort checks if a string represents a valid port -func IsPort(str string) bool { - if i, err := strconv.Atoi(str); err == nil && i > 0 && i < 65536 { - return true - } - return false -} - -// IsIPv4 check if the string is an IP version 4. -func IsIPv4(str string) bool { - ip := net.ParseIP(str) - return ip != nil && strings.Contains(str, ".") -} - -// IsIPv6 check if the string is an IP version 6. -func IsIPv6(str string) bool { - ip := net.ParseIP(str) - return ip != nil && strings.Contains(str, ":") -} - -// IsCIDR check if the string is an valid CIDR notiation (IPV4 & IPV6) -func IsCIDR(str string) bool { - _, _, err := net.ParseCIDR(str) - return err == nil -} - -// IsMAC check if a string is valid MAC address. -// Possible MAC formats: -// 01:23:45:67:89:ab -// 01:23:45:67:89:ab:cd:ef -// 01-23-45-67-89-ab -// 01-23-45-67-89-ab-cd-ef -// 0123.4567.89ab -// 0123.4567.89ab.cdef -func IsMAC(str string) bool { - _, err := net.ParseMAC(str) - return err == nil -} - -// IsHost checks if the string is a valid IP (both v4 and v6) or a valid DNS name -func IsHost(str string) bool { - return IsIP(str) || IsDNSName(str) -} - -// IsMongoID check if the string is a valid hex-encoded representation of a MongoDB ObjectId. -func IsMongoID(str string) bool { - return rxHexadecimal.MatchString(str) && (len(str) == 24) -} - -// IsLatitude check if a string is valid latitude. -func IsLatitude(str string) bool { - return rxLatitude.MatchString(str) -} - -// IsLongitude check if a string is valid longitude. -func IsLongitude(str string) bool { - return rxLongitude.MatchString(str) -} - -// IsRsaPublicKey check if a string is valid public key with provided length -func IsRsaPublicKey(str string, keylen int) bool { - bb := bytes.NewBufferString(str) - pemBytes, err := ioutil.ReadAll(bb) - if err != nil { - return false - } - block, _ := pem.Decode(pemBytes) - if block != nil && block.Type != "PUBLIC KEY" { - return false - } - var der []byte - - if block != nil { - der = block.Bytes - } else { - der, err = base64.StdEncoding.DecodeString(str) - if err != nil { - return false - } - } - - key, err := x509.ParsePKIXPublicKey(der) - if err != nil { - return false - } - pubkey, ok := key.(*rsa.PublicKey) - if !ok { - return false - } - bitlen := len(pubkey.N.Bytes()) * 8 - return bitlen == int(keylen) -} - -func toJSONName(tag string) string { - if tag == "" { - return "" - } - - // JSON name always comes first. If there's no options then split[0] is - // JSON name, if JSON name is not set, then split[0] is an empty string. - split := strings.SplitN(tag, ",", 2) - - name := split[0] - - // However it is possible that the field is skipped when - // (de-)serializing from/to JSON, in which case assume that there is no - // tag name to use - if name == "-" { - return "" - } - return name -} - -// ValidateStruct use tags for fields. -// result will be equal to `false` if there are any errors. -func ValidateStruct(s interface{}) (bool, error) { - if s == nil { - return true, nil - } - result := true - var err error - val := reflect.ValueOf(s) - if val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { - val = val.Elem() - } - // we only accept structs - if val.Kind() != reflect.Struct { - return false, fmt.Errorf("function only accepts structs; got %s", val.Kind()) - } - var errs Errors - for i := 0; i < val.NumField(); i++ { - valueField := val.Field(i) - typeField := val.Type().Field(i) - if typeField.PkgPath != "" { - continue // Private field - } - structResult := true - if (valueField.Kind() == reflect.Struct || - (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) && - typeField.Tag.Get(tagName) != "-" { - var err error - structResult, err = ValidateStruct(valueField.Interface()) - if err != nil { - errs = append(errs, err) - } - } - resultField, err2 := typeCheck(valueField, typeField, val, nil) - if err2 != nil { - - // Replace structure name with JSON name if there is a tag on the variable - jsonTag := toJSONName(typeField.Tag.Get("json")) - if jsonTag != "" { - switch jsonError := err2.(type) { - case Error: - jsonError.Name = jsonTag - err2 = jsonError - case Errors: - for i2, err3 := range jsonError { - switch customErr := err3.(type) { - case Error: - customErr.Name = jsonTag - jsonError[i2] = customErr - } - } - - err2 = jsonError - } - } - - errs = append(errs, err2) - } - result = result && resultField && structResult - } - if len(errs) > 0 { - err = errs - } - return result, err -} - -// parseTagIntoMap parses a struct tag `valid:required~Some error message,length(2|3)` into map[string]string{"required": "Some error message", "length(2|3)": ""} -func parseTagIntoMap(tag string) tagOptionsMap { - optionsMap := make(tagOptionsMap) - options := strings.Split(tag, ",") - - for _, option := range options { - option = strings.TrimSpace(option) - - validationOptions := strings.Split(option, "~") - if !isValidTag(validationOptions[0]) { - continue - } - if len(validationOptions) == 2 { - optionsMap[validationOptions[0]] = validationOptions[1] - } else { - optionsMap[validationOptions[0]] = "" - } - } - return optionsMap -} - -func isValidTag(s string) bool { - if s == "" { - return false - } - for _, c := range s { - switch { - case strings.ContainsRune("\\'\"!#$%&()*+-./:<=>?@[]^_{|}~ ", c): - // Backslash and quote chars are reserved, but - // otherwise any punctuation chars are allowed - // in a tag name. - default: - if !unicode.IsLetter(c) && !unicode.IsDigit(c) { - return false - } - } - } - return true -} - -// IsSSN will validate the given string as a U.S. Social Security Number -func IsSSN(str string) bool { - if str == "" || len(str) != 11 { - return false - } - return rxSSN.MatchString(str) -} - -// IsSemver check if string is valid semantic version -func IsSemver(str string) bool { - return rxSemver.MatchString(str) -} - -// IsTime check if string is valid according to given format -func IsTime(str string, format string) bool { - _, err := time.Parse(format, str) - return err == nil -} - -// IsRFC3339 check if string is valid timestamp value according to RFC3339 -func IsRFC3339(str string) bool { - return IsTime(str, time.RFC3339) -} - -// IsRFC3339WithoutZone check if string is valid timestamp value according to RFC3339 which excludes the timezone. -func IsRFC3339WithoutZone(str string) bool { - return IsTime(str, RF3339WithoutZone) -} - -// IsISO4217 check if string is valid ISO currency code -func IsISO4217(str string) bool { - for _, currency := range ISO4217List { - if str == currency { - return true - } - } - - return false -} - -// ByteLength check string's length -func ByteLength(str string, params ...string) bool { - if len(params) == 2 { - min, _ := ToInt(params[0]) - max, _ := ToInt(params[1]) - return len(str) >= int(min) && len(str) <= int(max) - } - - return false -} - -// RuneLength check string's length -// Alias for StringLength -func RuneLength(str string, params ...string) bool { - return StringLength(str, params...) -} - -// IsRsaPub check whether string is valid RSA key -// Alias for IsRsaPublicKey -func IsRsaPub(str string, params ...string) bool { - if len(params) == 1 { - len, _ := ToInt(params[0]) - return IsRsaPublicKey(str, int(len)) - } - - return false -} - -// StringMatches checks if a string matches a given pattern. -func StringMatches(s string, params ...string) bool { - if len(params) == 1 { - pattern := params[0] - return Matches(s, pattern) - } - return false -} - -// StringLength check string's length (including multi byte strings) -func StringLength(str string, params ...string) bool { - - if len(params) == 2 { - strLength := utf8.RuneCountInString(str) - min, _ := ToInt(params[0]) - max, _ := ToInt(params[1]) - return strLength >= int(min) && strLength <= int(max) - } - - return false -} - -// Range check string's length -func Range(str string, params ...string) bool { - if len(params) == 2 { - value, _ := ToFloat(str) - min, _ := ToFloat(params[0]) - max, _ := ToFloat(params[1]) - return InRange(value, min, max) - } - - return false -} - -func isInRaw(str string, params ...string) bool { - if len(params) == 1 { - rawParams := params[0] - - parsedParams := strings.Split(rawParams, "|") - - return IsIn(str, parsedParams...) - } - - return false -} - -// IsIn check if string str is a member of the set of strings params -func IsIn(str string, params ...string) bool { - for _, param := range params { - if str == param { - return true - } - } - - return false -} - -func checkRequired(v reflect.Value, t reflect.StructField, options tagOptionsMap) (bool, error) { - if requiredOption, isRequired := options["required"]; isRequired { - if len(requiredOption) > 0 { - return false, Error{t.Name, fmt.Errorf(requiredOption), true, "required"} - } - return false, Error{t.Name, fmt.Errorf("non zero value required"), false, "required"} - } else if _, isOptional := options["optional"]; fieldsRequiredByDefault && !isOptional { - return false, Error{t.Name, fmt.Errorf("Missing required field"), false, "required"} - } - // not required and empty is valid - return true, nil -} - -func typeCheck(v reflect.Value, t reflect.StructField, o reflect.Value, options tagOptionsMap) (isValid bool, resultErr error) { - if !v.IsValid() { - return false, nil - } - - tag := t.Tag.Get(tagName) - - // Check if the field should be ignored - switch tag { - case "": - if !fieldsRequiredByDefault { - return true, nil - } - return false, Error{t.Name, fmt.Errorf("All fields are required to at least have one validation defined"), false, "required"} - case "-": - return true, nil - } - - isRootType := false - if options == nil { - isRootType = true - options = parseTagIntoMap(tag) - } - - if isEmptyValue(v) { - // an empty value is not validated, check only required - return checkRequired(v, t, options) - } - - var customTypeErrors Errors - for validatorName, customErrorMessage := range options { - if validatefunc, ok := CustomTypeTagMap.Get(validatorName); ok { - delete(options, validatorName) - - if result := validatefunc(v.Interface(), o.Interface()); !result { - if len(customErrorMessage) > 0 { - customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: fmt.Errorf(customErrorMessage), CustomErrorMessageExists: true, Validator: stripParams(validatorName)}) - continue - } - customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: fmt.Errorf("%s does not validate as %s", fmt.Sprint(v), validatorName), CustomErrorMessageExists: false, Validator: stripParams(validatorName)}) - } - } - } - - if len(customTypeErrors.Errors()) > 0 { - return false, customTypeErrors - } - - if isRootType { - // Ensure that we've checked the value by all specified validators before report that the value is valid - defer func() { - delete(options, "optional") - delete(options, "required") - - if isValid && resultErr == nil && len(options) != 0 { - for validator := range options { - isValid = false - resultErr = Error{t.Name, fmt.Errorf( - "The following validator is invalid or can't be applied to the field: %q", validator), false, stripParams(validator)} - return - } - } - }() - } - - switch v.Kind() { - case reflect.Bool, - reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, - reflect.Float32, reflect.Float64, - reflect.String: - // for each tag option check the map of validator functions - for validatorSpec, customErrorMessage := range options { - var negate bool - validator := validatorSpec - customMsgExists := len(customErrorMessage) > 0 - - // Check whether the tag looks like '!something' or 'something' - if validator[0] == '!' { - validator = validator[1:] - negate = true - } - - // Check for param validators - for key, value := range ParamTagRegexMap { - ps := value.FindStringSubmatch(validator) - if len(ps) == 0 { - continue - } - - validatefunc, ok := ParamTagMap[key] - if !ok { - continue - } - - delete(options, validatorSpec) - - switch v.Kind() { - case reflect.String, - reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, - reflect.Float32, reflect.Float64: - - field := fmt.Sprint(v) // make value into string, then validate with regex - if result := validatefunc(field, ps[1:]...); (!result && !negate) || (result && negate) { - if customMsgExists { - return false, Error{t.Name, fmt.Errorf(customErrorMessage), customMsgExists, stripParams(validatorSpec)} - } - if negate { - return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec)} - } - return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec)} - } - default: - // type not yet supported, fail - return false, Error{t.Name, fmt.Errorf("Validator %s doesn't support kind %s", validator, v.Kind()), false, stripParams(validatorSpec)} - } - } - - if validatefunc, ok := TagMap[validator]; ok { - delete(options, validatorSpec) - - switch v.Kind() { - case reflect.String: - field := fmt.Sprint(v) // make value into string, then validate with regex - if result := validatefunc(field); !result && !negate || result && negate { - if customMsgExists { - return false, Error{t.Name, fmt.Errorf(customErrorMessage), customMsgExists, stripParams(validatorSpec)} - } - if negate { - return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec)} - } - return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec)} - } - default: - //Not Yet Supported Types (Fail here!) - err := fmt.Errorf("Validator %s doesn't support kind %s for value %v", validator, v.Kind(), v) - return false, Error{t.Name, err, false, stripParams(validatorSpec)} - } - } - } - return true, nil - case reflect.Map: - if v.Type().Key().Kind() != reflect.String { - return false, &UnsupportedTypeError{v.Type()} - } - var sv stringValues - sv = v.MapKeys() - sort.Sort(sv) - result := true - for _, k := range sv { - var resultItem bool - var err error - if v.MapIndex(k).Kind() != reflect.Struct { - resultItem, err = typeCheck(v.MapIndex(k), t, o, options) - if err != nil { - return false, err - } - } else { - resultItem, err = ValidateStruct(v.MapIndex(k).Interface()) - if err != nil { - return false, err - } - } - result = result && resultItem - } - return result, nil - case reflect.Slice, reflect.Array: - result := true - for i := 0; i < v.Len(); i++ { - var resultItem bool - var err error - if v.Index(i).Kind() != reflect.Struct { - resultItem, err = typeCheck(v.Index(i), t, o, options) - if err != nil { - return false, err - } - } else { - resultItem, err = ValidateStruct(v.Index(i).Interface()) - if err != nil { - return false, err - } - } - result = result && resultItem - } - return result, nil - case reflect.Interface: - // If the value is an interface then encode its element - if v.IsNil() { - return true, nil - } - return ValidateStruct(v.Interface()) - case reflect.Ptr: - // If the value is a pointer then check its element - if v.IsNil() { - return true, nil - } - return typeCheck(v.Elem(), t, o, options) - case reflect.Struct: - return ValidateStruct(v.Interface()) - default: - return false, &UnsupportedTypeError{v.Type()} - } -} - -func stripParams(validatorString string) string { - return paramsRegexp.ReplaceAllString(validatorString, "") -} - -func isEmptyValue(v reflect.Value) bool { - switch v.Kind() { - case reflect.String, reflect.Array: - return v.Len() == 0 - case reflect.Map, reflect.Slice: - return v.Len() == 0 || v.IsNil() - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - } - - return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) -} - -// ErrorByField returns error for specified field of the struct -// validated by ValidateStruct or empty string if there are no errors -// or this field doesn't exists or doesn't have any errors. -func ErrorByField(e error, field string) string { - if e == nil { - return "" - } - return ErrorsByField(e)[field] -} - -// ErrorsByField returns map of errors of the struct validated -// by ValidateStruct or empty map if there are no errors. -func ErrorsByField(e error) map[string]string { - m := make(map[string]string) - if e == nil { - return m - } - // prototype for ValidateStruct - - switch e.(type) { - case Error: - m[e.(Error).Name] = e.(Error).Err.Error() - case Errors: - for _, item := range e.(Errors).Errors() { - n := ErrorsByField(item) - for k, v := range n { - m[k] = v - } - } - } - - return m -} - -// Error returns string equivalent for reflect.Type -func (e *UnsupportedTypeError) Error() string { - return "validator: unsupported type: " + e.Type.String() -} - -func (sv stringValues) Len() int { return len(sv) } -func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } -func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) } -func (sv stringValues) get(i int) string { return sv[i].String() } diff --git a/vendor/github.com/asaskevich/govalidator/validator_test.go b/vendor/github.com/asaskevich/govalidator/validator_test.go deleted file mode 100644 index 226fc80df..000000000 --- a/vendor/github.com/asaskevich/govalidator/validator_test.go +++ /dev/null @@ -1,3216 +0,0 @@ -package govalidator - -import ( - "fmt" - "strings" - "testing" - "time" -) - -func init() { - CustomTypeTagMap.Set("customFalseValidator", CustomTypeValidator(func(i interface{}, o interface{}) bool { - return false - })) - CustomTypeTagMap.Set("customTrueValidator", CustomTypeValidator(func(i interface{}, o interface{}) bool { - return true - })) -} - -func TestIsAlpha(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"\n", false}, - {"\r", false}, - {"Ⅸ", false}, - {"", true}, - {" fooo ", false}, - {"abc!!!", false}, - {"abc1", false}, - {"abc〩", false}, - {"abc", true}, - {"소주", false}, - {"ABC", true}, - {"FoObAr", true}, - {"소aBC", false}, - {"소", false}, - {"달기&Co.", false}, - {"〩Hours", false}, - {"\ufff0", false}, - {"\u0070", true}, //UTF-8(ASCII): p - {"\u0026", false}, //UTF-8(ASCII): & - {"\u0030", false}, //UTF-8(ASCII): 0 - {"123", false}, - {"0123", false}, - {"-00123", false}, - {"0", false}, - {"-0", false}, - {"123.123", false}, - {" ", false}, - {".", false}, - {"-1¾", false}, - {"1¾", false}, - {"〥〩", false}, - {"모자", false}, - {"ix", true}, - {"۳۵۶۰", false}, - {"1--", false}, - {"1-1", false}, - {"-", false}, - {"--", false}, - {"1++", false}, - {"1+1", false}, - {"+", false}, - {"++", false}, - {"+1", false}, - } - for _, test := range tests { - actual := IsAlpha(test.param) - if actual != test.expected { - t.Errorf("Expected IsAlpha(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsUTFLetter(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"\n", false}, - {"\r", false}, - {"Ⅸ", false}, - {"", true}, - {" fooo ", false}, - {"abc!!!", false}, - {"abc1", false}, - {"abc〩", false}, - {"", true}, - {"abc", true}, - {"소주", true}, - {"ABC", true}, - {"FoObAr", true}, - {"소aBC", true}, - {"소", true}, - {"달기&Co.", false}, - {"〩Hours", false}, - {"\ufff0", false}, - {"\u0070", true}, //UTF-8(ASCII): p - {"\u0026", false}, //UTF-8(ASCII): & - {"\u0030", false}, //UTF-8(ASCII): 0 - {"123", false}, - {"0123", false}, - {"-00123", false}, - {"0", false}, - {"-0", false}, - {"123.123", false}, - {" ", false}, - {".", false}, - {"-1¾", false}, - {"1¾", false}, - {"〥〩", false}, - {"모자", true}, - {"ix", true}, - {"۳۵۶۰", false}, - {"1--", false}, - {"1-1", false}, - {"-", false}, - {"--", false}, - {"1++", false}, - {"1+1", false}, - {"+", false}, - {"++", false}, - {"+1", false}, - } - for _, test := range tests { - actual := IsUTFLetter(test.param) - if actual != test.expected { - t.Errorf("Expected IsUTFLetter(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsAlphanumeric(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"\n", false}, - {"\r", false}, - {"Ⅸ", false}, - {"", true}, - {" fooo ", false}, - {"abc!!!", false}, - {"abc123", true}, - {"ABC111", true}, - {"abc1", true}, - {"abc〩", false}, - {"abc", true}, - {"소주", false}, - {"ABC", true}, - {"FoObAr", true}, - {"소aBC", false}, - {"소", false}, - {"달기&Co.", false}, - {"〩Hours", false}, - {"\ufff0", false}, - {"\u0070", true}, //UTF-8(ASCII): p - {"\u0026", false}, //UTF-8(ASCII): & - {"\u0030", true}, //UTF-8(ASCII): 0 - {"123", true}, - {"0123", true}, - {"-00123", false}, - {"0", true}, - {"-0", false}, - {"123.123", false}, - {" ", false}, - {".", false}, - {"-1¾", false}, - {"1¾", false}, - {"〥〩", false}, - {"모자", false}, - {"ix", true}, - {"۳۵۶۰", false}, - {"1--", false}, - {"1-1", false}, - {"-", false}, - {"--", false}, - {"1++", false}, - {"1+1", false}, - {"+", false}, - {"++", false}, - {"+1", false}, - } - for _, test := range tests { - actual := IsAlphanumeric(test.param) - if actual != test.expected { - t.Errorf("Expected IsAlphanumeric(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsUTFLetterNumeric(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"\n", false}, - {"\r", false}, - {"Ⅸ", true}, - {"", true}, - {" fooo ", false}, - {"abc!!!", false}, - {"abc1", true}, - {"abc〩", true}, - {"abc", true}, - {"소주", true}, - {"ABC", true}, - {"FoObAr", true}, - {"소aBC", true}, - {"소", true}, - {"달기&Co.", false}, - {"〩Hours", true}, - {"\ufff0", false}, - {"\u0070", true}, //UTF-8(ASCII): p - {"\u0026", false}, //UTF-8(ASCII): & - {"\u0030", true}, //UTF-8(ASCII): 0 - {"123", true}, - {"0123", true}, - {"-00123", false}, - {"0", true}, - {"-0", false}, - {"123.123", false}, - {" ", false}, - {".", false}, - {"-1¾", false}, - {"1¾", true}, - {"〥〩", true}, - {"모자", true}, - {"ix", true}, - {"۳۵۶۰", true}, - {"1--", false}, - {"1-1", false}, - {"-", false}, - {"--", false}, - {"1++", false}, - {"1+1", false}, - {"+", false}, - {"++", false}, - {"+1", false}, - } - for _, test := range tests { - actual := IsUTFLetterNumeric(test.param) - if actual != test.expected { - t.Errorf("Expected IsUTFLetterNumeric(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsNumeric(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"\n", false}, - {"\r", false}, - {"Ⅸ", false}, - {"", true}, - {" fooo ", false}, - {"abc!!!", false}, - {"abc1", false}, - {"abc〩", false}, - {"abc", false}, - {"소주", false}, - {"ABC", false}, - {"FoObAr", false}, - {"소aBC", false}, - {"소", false}, - {"달기&Co.", false}, - {"〩Hours", false}, - {"\ufff0", false}, - {"\u0070", false}, //UTF-8(ASCII): p - {"\u0026", false}, //UTF-8(ASCII): & - {"\u0030", true}, //UTF-8(ASCII): 0 - {"123", true}, - {"0123", true}, - {"-00123", false}, - {"+00123", false}, - {"0", true}, - {"-0", false}, - {"123.123", false}, - {" ", false}, - {".", false}, - {"12𐅪3", false}, - {"-1¾", false}, - {"1¾", false}, - {"〥〩", false}, - {"모자", false}, - {"ix", false}, - {"۳۵۶۰", false}, - {"1--", false}, - {"1-1", false}, - {"-", false}, - {"--", false}, - {"1++", false}, - {"1+1", false}, - {"+", false}, - {"++", false}, - {"+1", false}, - } - for _, test := range tests { - actual := IsNumeric(test.param) - if actual != test.expected { - t.Errorf("Expected IsNumeric(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsUTFNumeric(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"\n", false}, - {"\r", false}, - {"Ⅸ", true}, - {"", true}, - {" fooo ", false}, - {"abc!!!", false}, - {"abc1", false}, - {"abc〩", false}, - {"abc", false}, - {"소주", false}, - {"ABC", false}, - {"FoObAr", false}, - {"소aBC", false}, - {"소", false}, - {"달기&Co.", false}, - {"〩Hours", false}, - {"\ufff0", false}, - {"\u0070", false}, //UTF-8(ASCII): p - {"\u0026", false}, //UTF-8(ASCII): & - {"\u0030", true}, //UTF-8(ASCII): 0 - {"123", true}, - {"0123", true}, - {"-00123", true}, - {"0", true}, - {"-0", true}, - {"--0", false}, - {"-0-", false}, - {"123.123", false}, - {" ", false}, - {".", false}, - {"12𐅪3", true}, - {"-1¾", true}, - {"1¾", true}, - {"〥〩", true}, - {"모자", false}, - {"ix", false}, - {"۳۵۶۰", true}, - {"1++", false}, - {"1+1", false}, - {"+", false}, - {"++", false}, - {"+1", true}, - } - for _, test := range tests { - actual := IsUTFNumeric(test.param) - if actual != test.expected { - t.Errorf("Expected IsUTFNumeric(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsUTFDigit(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - - {"\n", false}, - {"\r", false}, - {"Ⅸ", false}, - {"", true}, - {" fooo ", false}, - {"abc!!!", false}, - {"abc1", false}, - {"abc〩", false}, - {"abc", false}, - {"소주", false}, - {"ABC", false}, - {"FoObAr", false}, - {"소aBC", false}, - {"소", false}, - {"달기&Co.", false}, - {"〩Hours", false}, - {"\ufff0", false}, - {"\u0070", false}, //UTF-8(ASCII): p - {"\u0026", false}, //UTF-8(ASCII): & - {"\u0030", true}, //UTF-8(ASCII): 0 - {"123", true}, - {"0123", true}, - {"-00123", true}, - {"0", true}, - {"-0", true}, - {"--0", false}, - {"-0-", false}, - {"123.123", false}, - {" ", false}, - {".", false}, - {"12𐅪3", false}, - {"1483920", true}, - {"", true}, - {"۳۵۶۰", true}, - {"-29", true}, - {"-1¾", false}, - {"1¾", false}, - {"〥〩", false}, - {"모자", false}, - {"ix", false}, - {"۳۵۶۰", true}, - {"1++", false}, - {"1+1", false}, - {"+", false}, - {"++", false}, - {"+1", true}, - } - for _, test := range tests { - actual := IsUTFDigit(test.param) - if actual != test.expected { - t.Errorf("Expected IsUTFDigit(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsLowerCase(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", true}, - {"abc123", true}, - {"abc", true}, - {"a b c", true}, - {"abcß", true}, - {"abcẞ", false}, - {"ABCẞ", false}, - {"tr竪s 端ber", true}, - {"fooBar", false}, - {"123ABC", false}, - {"ABC123", false}, - {"ABC", false}, - {"S T R", false}, - {"fooBar", false}, - {"abacaba123", true}, - } - for _, test := range tests { - actual := IsLowerCase(test.param) - if actual != test.expected { - t.Errorf("Expected IsLowerCase(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsUpperCase(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", true}, - {"abc123", false}, - {"abc", false}, - {"a b c", false}, - {"abcß", false}, - {"abcẞ", false}, - {"ABCẞ", true}, - {"tr竪s 端ber", false}, - {"fooBar", false}, - {"123ABC", true}, - {"ABC123", true}, - {"ABC", true}, - {"S T R", true}, - {"fooBar", false}, - {"abacaba123", false}, - } - for _, test := range tests { - actual := IsUpperCase(test.param) - if actual != test.expected { - t.Errorf("Expected IsUpperCase(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestHasLowerCase(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", true}, - {"abc123", true}, - {"abc", true}, - {"a b c", true}, - {"abcß", true}, - {"abcẞ", true}, - {"ABCẞ", false}, - {"tr竪s 端ber", true}, - {"fooBar", true}, - {"123ABC", false}, - {"ABC123", false}, - {"ABC", false}, - {"S T R", false}, - {"fooBar", true}, - {"abacaba123", true}, - {"FÒÔBÀŘ", false}, - {"fòôbàř", true}, - {"fÒÔBÀŘ", true}, - } - for _, test := range tests { - actual := HasLowerCase(test.param) - if actual != test.expected { - t.Errorf("Expected HasLowerCase(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestHasUpperCase(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", true}, - {"abc123", false}, - {"abc", false}, - {"a b c", false}, - {"abcß", false}, - {"abcẞ", false}, - {"ABCẞ", true}, - {"tr竪s 端ber", false}, - {"fooBar", true}, - {"123ABC", true}, - {"ABC123", true}, - {"ABC", true}, - {"S T R", true}, - {"fooBar", true}, - {"abacaba123", false}, - {"FÒÔBÀŘ", true}, - {"fòôbàř", false}, - {"Fòôbàř", true}, - } - for _, test := range tests { - actual := HasUpperCase(test.param) - if actual != test.expected { - t.Errorf("Expected HasUpperCase(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsInt(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"-2147483648", true}, //Signed 32 Bit Min Int - {"2147483647", true}, //Signed 32 Bit Max Int - {"-2147483649", true}, //Signed 32 Bit Min Int - 1 - {"2147483648", true}, //Signed 32 Bit Max Int + 1 - {"4294967295", true}, //Unsigned 32 Bit Max Int - {"4294967296", true}, //Unsigned 32 Bit Max Int + 1 - {"-9223372036854775808", true}, //Signed 64 Bit Min Int - {"9223372036854775807", true}, //Signed 64 Bit Max Int - {"-9223372036854775809", true}, //Signed 64 Bit Min Int - 1 - {"9223372036854775808", true}, //Signed 64 Bit Max Int + 1 - {"18446744073709551615", true}, //Unsigned 64 Bit Max Int - {"18446744073709551616", true}, //Unsigned 64 Bit Max Int + 1 - {"", true}, - {"123", true}, - {"0", true}, - {"-0", true}, - {"+0", true}, - {"01", false}, - {"123.123", false}, - {" ", false}, - {"000", false}, - } - for _, test := range tests { - actual := IsInt(test.param) - if actual != test.expected { - t.Errorf("Expected IsInt(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsHash(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - algo string - expected bool - }{ - {"3ca25ae354e192b26879f651a51d92aa8a34d8d3", "sha1", true}, - {"3ca25ae354e192b26879f651a51d34d8d3", "sha1", false}, - {"3ca25ae354e192b26879f651a51d92aa8a34d8d3", "Tiger160", true}, - {"3ca25ae354e192b26879f651a51d34d8d3", "ripemd160", false}, - {"579282cfb65ca1f109b78536effaf621b853c9f7079664a3fbe2b519f435898c", "sha256", true}, - {"579282cfb65ca1f109b78536effaf621b853c9f7079664a3fbe2b519f435898casfdsafsadfsdf", "sha256", false}, - {"bf547c3fc5841a377eb1519c2890344dbab15c40ae4150b4b34443d2212e5b04aa9d58865bf03d8ae27840fef430b891", "sha384", true}, - {"579282cfb65ca1f109b78536effaf621b853c9f7079664a3fbe2b519f435898casfdsafsadfsdf", "sha384", false}, - {"45bc5fa8cb45ee408c04b6269e9f1e1c17090c5ce26ffeeda2af097735b29953ce547e40ff3ad0d120e5361cc5f9cee35ea91ecd4077f3f589b4d439168f91b9", "sha512", true}, - {"579282cfb65ca1f109b78536effaf621b853c9f7079664a3fbe2b519f435898casfdsafsadfsdf", "sha512", false}, - {"46fc0125a148788a3ac1d649566fc04eb84a746f1a6e4fa7", "tiger192", true}, - {"46fc0125a148788a3ac1d649566fc04eb84a746f1a6$$%@^", "TIGER192", false}, - {"46fc0125a148788a3ac1d649566fc04eb84a746f1a6$$%@^", "SOMEHASH", false}, - } - for _, test := range tests { - actual := IsHash(test.param, test.algo) - if actual != test.expected { - t.Errorf("Expected IsHash(%q, %q) to be %v, got %v", test.param, test.algo, test.expected, actual) - } - } -} - -func TestIsEmail(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"foo@bar.com", true}, - {"foo@bar.com.au", true}, - {"foo+bar@bar.com", true}, - {"foo@bar.coffee", true}, - {"foo@bar.coffee..coffee", false}, - {"invalidemail@", false}, - {"invalid.com", false}, - {"@invalid.com", false}, - {"NathAn.daVIeS@DomaIn.cOM", true}, - {"NATHAN.DAVIES@DOMAIN.CO.UK", true}, - } - for _, test := range tests { - actual := IsEmail(test.param) - if actual != test.expected { - t.Errorf("Expected IsEmail(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsURL(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"http://foo.bar#com", true}, - {"http://foobar.com", true}, - {"https://foobar.com", true}, - {"foobar.com", true}, - {"http://foobar.coffee/", true}, - {"http://foobar.中文网/", true}, - {"http://foobar.org/", true}, - {"http://foobar.ORG", true}, - {"http://foobar.org:8080/", true}, - {"ftp://foobar.ru/", true}, - {"ftp.foo.bar", true}, - {"http://user:pass@www.foobar.com/", true}, - {"http://user:pass@www.foobar.com/path/file", true}, - {"http://127.0.0.1/", true}, - {"http://duckduckgo.com/?q=%2F", true}, - {"http://localhost:3000/", true}, - {"http://foobar.com/?foo=bar#baz=qux", true}, - {"http://foobar.com?foo=bar", true}, - {"http://www.xn--froschgrn-x9a.net/", true}, - {"http://foobar.com/a-", true}, - {"http://foobar.پاکستان/", true}, - {"http://foobar.c_o_m", false}, - {"", false}, - {"xyz://foobar.com", false}, - // {"invalid.", false}, is it false like "localhost."? - {".com", false}, - {"rtmp://foobar.com", false}, - {"http://www.foo_bar.com/", false}, - {"http://localhost:3000/", true}, - {"http://foobar.com#baz=qux", true}, - {"http://foobar.com/t$-_.+!*\\'(),", true}, - {"http://www.foobar.com/~foobar", true}, - {"http://www.-foobar.com/", false}, - {"http://www.foo---bar.com/", false}, - {"http://r6---snnvoxuioq6.googlevideo.com", true}, - {"mailto:someone@example.com", true}, - {"irc://irc.server.org/channel", false}, - {"irc://#channel@network", true}, - {"/abs/test/dir", false}, - {"./rel/test/dir", false}, - {"http://foo^bar.org", false}, - {"http://foo&*bar.org", false}, - {"http://foo&bar.org", false}, - {"http://foo bar.org", false}, - {"http://foo.bar.org", true}, - {"http://www.foo.bar.org", true}, - {"http://www.foo.co.uk", true}, - {"foo", false}, - {"http://.foo.com", false}, - {"http://,foo.com", false}, - {",foo.com", false}, - {"http://myservice.:9093/", true}, - // according to issues #62 #66 - {"https://pbs.twimg.com/profile_images/560826135676588032/j8fWrmYY_normal.jpeg", true}, - // according to #125 - {"http://prometheus-alertmanager.service.q:9093", true}, - {"aio1_alertmanager_container-63376c45:9093", true}, - {"https://www.logn-123-123.url.with.sigle.letter.d:12345/url/path/foo?bar=zzz#user", true}, - {"http://me.example.com", true}, - {"http://www.me.example.com", true}, - {"https://farm6.static.flickr.com", true}, - {"https://zh.wikipedia.org/wiki/Wikipedia:%E9%A6%96%E9%A1%B5", true}, - {"google", false}, - // According to #87 - {"http://hyphenated-host-name.example.co.in", true}, - {"http://cant-end-with-hyphen-.example.com", false}, - {"http://-cant-start-with-hyphen.example.com", false}, - {"http://www.domain-can-have-dashes.com", true}, - {"http://m.abcd.com/test.html", true}, - {"http://m.abcd.com/a/b/c/d/test.html?args=a&b=c", true}, - {"http://[::1]:9093", true}, - {"http://[::1]:909388", false}, - {"1200::AB00:1234::2552:7777:1313", false}, - {"http://[2001:db8:a0b:12f0::1]/index.html", true}, - {"http://[1200:0000:AB00:1234:0000:2552:7777:1313]", true}, - {"http://user:pass@[::1]:9093/a/b/c/?a=v#abc", true}, - {"https://127.0.0.1/a/b/c?a=v&c=11d", true}, - {"https://foo_bar.example.com", true}, - {"http://foo_bar.example.com", true}, - {"http://foo_bar_fizz_buzz.example.com", true}, - {"http://_cant_start_with_underescore", false}, - {"http://cant_end_with_underescore_", false}, - {"foo_bar.example.com", true}, - {"foo_bar_fizz_buzz.example.com", true}, - {"http://hello_world.example.com", true}, - // According to #212 - {"foo_bar-fizz-buzz:1313", true}, - {"foo_bar-fizz-buzz:13:13", false}, - {"foo_bar-fizz-buzz://1313", false}, - } - for _, test := range tests { - actual := IsURL(test.param) - if actual != test.expected { - t.Errorf("Expected IsURL(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsRequestURL(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"http://foo.bar/#com", true}, - {"http://foobar.com", true}, - {"https://foobar.com", true}, - {"foobar.com", false}, - {"http://foobar.coffee/", true}, - {"http://foobar.中文网/", true}, - {"http://foobar.org/", true}, - {"http://foobar.org:8080/", true}, - {"ftp://foobar.ru/", true}, - {"http://user:pass@www.foobar.com/", true}, - {"http://127.0.0.1/", true}, - {"http://duckduckgo.com/?q=%2F", true}, - {"http://localhost:3000/", true}, - {"http://foobar.com/?foo=bar#baz=qux", true}, - {"http://foobar.com?foo=bar", true}, - {"http://www.xn--froschgrn-x9a.net/", true}, - {"", false}, - {"xyz://foobar.com", true}, - {"invalid.", false}, - {".com", false}, - {"rtmp://foobar.com", true}, - {"http://www.foo_bar.com/", true}, - {"http://localhost:3000/", true}, - {"http://foobar.com/#baz=qux", true}, - {"http://foobar.com/t$-_.+!*\\'(),", true}, - {"http://www.foobar.com/~foobar", true}, - {"http://www.-foobar.com/", true}, - {"http://www.foo---bar.com/", true}, - {"mailto:someone@example.com", true}, - {"irc://irc.server.org/channel", true}, - {"/abs/test/dir", false}, - {"./rel/test/dir", false}, - } - for _, test := range tests { - actual := IsRequestURL(test.param) - if actual != test.expected { - t.Errorf("Expected IsRequestURL(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsRequestURI(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"http://foo.bar/#com", true}, - {"http://foobar.com", true}, - {"https://foobar.com", true}, - {"foobar.com", false}, - {"http://foobar.coffee/", true}, - {"http://foobar.中文网/", true}, - {"http://foobar.org/", true}, - {"http://foobar.org:8080/", true}, - {"ftp://foobar.ru/", true}, - {"http://user:pass@www.foobar.com/", true}, - {"http://127.0.0.1/", true}, - {"http://duckduckgo.com/?q=%2F", true}, - {"http://localhost:3000/", true}, - {"http://foobar.com/?foo=bar#baz=qux", true}, - {"http://foobar.com?foo=bar", true}, - {"http://www.xn--froschgrn-x9a.net/", true}, - {"xyz://foobar.com", true}, - {"invalid.", false}, - {".com", false}, - {"rtmp://foobar.com", true}, - {"http://www.foo_bar.com/", true}, - {"http://localhost:3000/", true}, - {"http://foobar.com/#baz=qux", true}, - {"http://foobar.com/t$-_.+!*\\'(),", true}, - {"http://www.foobar.com/~foobar", true}, - {"http://www.-foobar.com/", true}, - {"http://www.foo---bar.com/", true}, - {"mailto:someone@example.com", true}, - {"irc://irc.server.org/channel", true}, - {"/abs/test/dir", true}, - {"./rel/test/dir", false}, - } - for _, test := range tests { - actual := IsRequestURI(test.param) - if actual != test.expected { - t.Errorf("Expected IsRequestURI(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsFloat(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {" ", false}, - {"-.123", false}, - {"abacaba", false}, - {"1f", false}, - {"-1f", false}, - {"+1f", false}, - {"123", true}, - {"123.", true}, - {"123.123", true}, - {"-123.123", true}, - {"+123.123", true}, - {"0.123", true}, - {"-0.123", true}, - {"+0.123", true}, - {".0", true}, - {"01.123", true}, - {"-0.22250738585072011e-307", true}, - {"+0.22250738585072011e-307", true}, - } - for _, test := range tests { - actual := IsFloat(test.param) - if actual != test.expected { - t.Errorf("Expected IsFloat(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsHexadecimal(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"abcdefg", false}, - {"", false}, - {"..", false}, - {"deadBEEF", true}, - {"ff0044", true}, - } - for _, test := range tests { - actual := IsHexadecimal(test.param) - if actual != test.expected { - t.Errorf("Expected IsHexadecimal(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsHexcolor(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"#ff", false}, - {"fff0", false}, - {"#ff12FG", false}, - {"CCccCC", true}, - {"fff", true}, - {"#f00", true}, - } - for _, test := range tests { - actual := IsHexcolor(test.param) - if actual != test.expected { - t.Errorf("Expected IsHexcolor(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsRGBcolor(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"rgb(0,31,255)", true}, - {"rgb(1,349,275)", false}, - {"rgb(01,31,255)", false}, - {"rgb(0.6,31,255)", false}, - {"rgba(0,31,255)", false}, - {"rgb(0, 31, 255)", true}, - } - for _, test := range tests { - actual := IsRGBcolor(test.param) - if actual != test.expected { - t.Errorf("Expected IsRGBcolor(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsNull(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"abacaba", false}, - {"", true}, - } - for _, test := range tests { - actual := IsNull(test.param) - if actual != test.expected { - t.Errorf("Expected IsNull(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsDivisibleBy(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 string - expected bool - }{ - {"4", "2", true}, - {"100", "10", true}, - {"", "1", true}, - {"123", "foo", false}, - {"123", "0", false}, - } - for _, test := range tests { - actual := IsDivisibleBy(test.param1, test.param2) - if actual != test.expected { - t.Errorf("Expected IsDivisibleBy(%q, %q) to be %v, got %v", test.param1, test.param2, test.expected, actual) - } - } -} - -// This small example illustrate how to work with IsDivisibleBy function. -func ExampleIsDivisibleBy() { - println("1024 is divisible by 64: ", IsDivisibleBy("1024", "64")) -} - -func TestIsByteLength(t *testing.T) { - t.Parallel() - - var tests = []struct { - param1 string - param2 int - param3 int - expected bool - }{ - {"abacaba", 100, -1, false}, - {"abacaba", 1, 3, false}, - {"abacaba", 1, 7, true}, - {"abacaba", 0, 8, true}, - {"\ufff0", 1, 1, false}, - } - for _, test := range tests { - actual := IsByteLength(test.param1, test.param2, test.param3) - if actual != test.expected { - t.Errorf("Expected IsByteLength(%q, %q, %q) to be %v, got %v", test.param1, test.param2, test.param3, test.expected, actual) - } - } -} - -func TestIsJSON(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"145", true}, - {"asdf", false}, - {"123:f00", false}, - {"{\"Name\":\"Alice\",\"Body\":\"Hello\",\"Time\":1294706395881547000}", true}, - {"{}", true}, - {"{\"Key\":{\"Key\":{\"Key\":123}}}", true}, - {"[]", true}, - {"null", true}, - } - for _, test := range tests { - actual := IsJSON(test.param) - if actual != test.expected { - t.Errorf("Expected IsJSON(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsMultibyte(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"abc", false}, - {"123", false}, - {"<>@;.-=", false}, - {"ひらがな・カタカナ、.漢字", true}, - {"あいうえお foobar", true}, - {"test@example.com", true}, - {"test@example.com", true}, - {"1234abcDExyz", true}, - {"カタカナ", true}, - {"", true}, - } - for _, test := range tests { - actual := IsMultibyte(test.param) - if actual != test.expected { - t.Errorf("Expected IsMultibyte(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsASCII(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", true}, - {"foobar", false}, - {"xyz098", false}, - {"123456", false}, - {"カタカナ", false}, - {"foobar", true}, - {"0987654321", true}, - {"test@example.com", true}, - {"1234abcDEF", true}, - {"", true}, - } - for _, test := range tests { - actual := IsASCII(test.param) - if actual != test.expected { - t.Errorf("Expected IsASCII(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsPrintableASCII(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", true}, - {"foobar", false}, - {"xyz098", false}, - {"123456", false}, - {"カタカナ", false}, - {"foobar", true}, - {"0987654321", true}, - {"test@example.com", true}, - {"1234abcDEF", true}, - {"newline\n", false}, - {"\x19test\x7F", false}, - } - for _, test := range tests { - actual := IsPrintableASCII(test.param) - if actual != test.expected { - t.Errorf("Expected IsPrintableASCII(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsFullWidth(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", true}, - {"abc", false}, - {"abc123", false}, - {"!\"#$%&()<>/+=-_? ~^|.,@`{}[]", false}, - {"ひらがな・カタカナ、.漢字", true}, - {"3ー0 a@com", true}, - {"Fカタカナ゙ᆲ", true}, - {"Good=Parts", true}, - {"", true}, - } - for _, test := range tests { - actual := IsFullWidth(test.param) - if actual != test.expected { - t.Errorf("Expected IsFullWidth(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsHalfWidth(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", true}, - {"あいうえお", false}, - {"0011", false}, - {"!\"#$%&()<>/+=-_? ~^|.,@`{}[]", true}, - {"l-btn_02--active", true}, - {"abc123い", true}, - {"カタカナ゙ᆲ←", true}, - {"", true}, - } - for _, test := range tests { - actual := IsHalfWidth(test.param) - if actual != test.expected { - t.Errorf("Expected IsHalfWidth(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsVariableWidth(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", true}, - {"ひらがなカタカナ漢字ABCDE", true}, - {"3ー0123", true}, - {"Fカタカナ゙ᆲ", true}, - {"", true}, - {"Good=Parts", true}, - {"abc", false}, - {"abc123", false}, - {"!\"#$%&()<>/+=-_? ~^|.,@`{}[]", false}, - {"ひらがな・カタカナ、.漢字", false}, - {"123456", false}, - {"カタカナ゙ᆲ", false}, - } - for _, test := range tests { - actual := IsVariableWidth(test.param) - if actual != test.expected { - t.Errorf("Expected IsVariableWidth(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsUUID(t *testing.T) { - t.Parallel() - - // Tests without version - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false}, - {"a987fbc9-4bed-3078-cf07-9141ba07c9f3xxx", false}, - {"a987fbc94bed3078cf079141ba07c9f3", false}, - {"934859", false}, - {"987fbc9-4bed-3078-cf07a-9141ba07c9f3", false}, - {"aaaaaaaa-1111-1111-aaag-111111111111", false}, - {"a987fbc9-4bed-3078-cf07-9141ba07c9f3", true}, - } - for _, test := range tests { - actual := IsUUID(test.param) - if actual != test.expected { - t.Errorf("Expected IsUUID(%q) to be %v, got %v", test.param, test.expected, actual) - } - } - - // UUID ver. 3 - tests = []struct { - param string - expected bool - }{ - {"", false}, - {"412452646", false}, - {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false}, - {"a987fbc9-4bed-4078-8f07-9141ba07c9f3", false}, - {"a987fbc9-4bed-3078-cf07-9141ba07c9f3", true}, - } - for _, test := range tests { - actual := IsUUIDv3(test.param) - if actual != test.expected { - t.Errorf("Expected IsUUIDv3(%q) to be %v, got %v", test.param, test.expected, actual) - } - } - - // UUID ver. 4 - tests = []struct { - param string - expected bool - }{ - {"", false}, - {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false}, - {"a987fbc9-4bed-5078-af07-9141ba07c9f3", false}, - {"934859", false}, - {"57b73598-8764-4ad0-a76a-679bb6640eb1", true}, - {"625e63f3-58f5-40b7-83a1-a72ad31acffb", true}, - } - for _, test := range tests { - actual := IsUUIDv4(test.param) - if actual != test.expected { - t.Errorf("Expected IsUUIDv4(%q) to be %v, got %v", test.param, test.expected, actual) - } - } - - // UUID ver. 5 - tests = []struct { - param string - expected bool - }{ - - {"", false}, - {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false}, - {"9c858901-8a57-4791-81fe-4c455b099bc9", false}, - {"a987fbc9-4bed-3078-cf07-9141ba07c9f3", false}, - {"987fbc97-4bed-5078-af07-9141ba07c9f3", true}, - {"987fbc97-4bed-5078-9f07-9141ba07c9f3", true}, - } - for _, test := range tests { - actual := IsUUIDv5(test.param) - if actual != test.expected { - t.Errorf("Expected IsUUIDv5(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsCreditCard(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"foo", false}, - {"5398228707871528", false}, - {"375556917985515", true}, - {"36050234196908", true}, - {"4716461583322103", true}, - {"4716-2210-5188-5662", true}, - {"4929 7226 5379 7141", true}, - {"5398228707871527", true}, - } - for _, test := range tests { - actual := IsCreditCard(test.param) - if actual != test.expected { - t.Errorf("Expected IsCreditCard(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsISBN(t *testing.T) { - t.Parallel() - - // Without version - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"foo", false}, - {"3836221195", true}, - {"1-61729-085-8", true}, - {"3 423 21412 0", true}, - {"3 401 01319 X", true}, - {"9784873113685", true}, - {"978-4-87311-368-5", true}, - {"978 3401013190", true}, - {"978-3-8362-2119-1", true}, - } - for _, test := range tests { - actual := IsISBN(test.param, -1) - if actual != test.expected { - t.Errorf("Expected IsISBN(%q, -1) to be %v, got %v", test.param, test.expected, actual) - } - } - - // ISBN 10 - tests = []struct { - param string - expected bool - }{ - {"", false}, - {"foo", false}, - {"3423214121", false}, - {"978-3836221191", false}, - {"3-423-21412-1", false}, - {"3 423 21412 1", false}, - {"3836221195", true}, - {"1-61729-085-8", true}, - {"3 423 21412 0", true}, - {"3 401 01319 X", true}, - } - for _, test := range tests { - actual := IsISBN10(test.param) - if actual != test.expected { - t.Errorf("Expected IsISBN10(%q) to be %v, got %v", test.param, test.expected, actual) - } - } - - // ISBN 13 - tests = []struct { - param string - expected bool - }{ - {"", false}, - {"foo", false}, - {"3-8362-2119-5", false}, - {"01234567890ab", false}, - {"978 3 8362 2119 0", false}, - {"9784873113685", true}, - {"978-4-87311-368-5", true}, - {"978 3401013190", true}, - {"978-3-8362-2119-1", true}, - } - for _, test := range tests { - actual := IsISBN13(test.param) - if actual != test.expected { - t.Errorf("Expected IsISBN13(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsDataURI(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"data:image/png;base64,TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4=", true}, - {"data:text/plain;base64,Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIHBvcnRhLg==", true}, - {"image/gif;base64,U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==", false}, - {"data:image/gif;base64,MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuMPNS1Ufof9EW/M98FNw" + - "UAKrwflsqVxaxQjBQnHQmiI7Vac40t8x7pIb8gLGV6wL7sBTJiPovJ0V7y7oc0Ye" + - "rhKh0Rm4skP2z/jHwwZICgGzBvA0rH8xlhUiTvcwDCJ0kc+fh35hNt8srZQM4619" + - "FTgB66Xmp4EtVyhpQV+t02g6NzK72oZI0vnAvqhpkxLeLiMCyrI416wHm5Tkukhx" + - "QmcL2a6hNOyu0ixX/x2kSFXApEnVrJ+/IxGyfyw8kf4N2IZpW5nEP847lpfj0SZZ" + - "Fwrd1mnfnDbYohX2zRptLy2ZUn06Qo9pkG5ntvFEPo9bfZeULtjYzIl6K8gJ2uGZ" + "HQIDAQAB", true}, - {"data:image/png;base64,12345", false}, - {"", false}, - {"data:text,:;base85,U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==", false}, - } - for _, test := range tests { - actual := IsDataURI(test.param) - if actual != test.expected { - t.Errorf("Expected IsDataURI(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsBase64(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4=", true}, - {"Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIHBvcnRhLg==", true}, - {"U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==", true}, - {"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuMPNS1Ufof9EW/M98FNw" + - "UAKrwflsqVxaxQjBQnHQmiI7Vac40t8x7pIb8gLGV6wL7sBTJiPovJ0V7y7oc0Ye" + - "rhKh0Rm4skP2z/jHwwZICgGzBvA0rH8xlhUiTvcwDCJ0kc+fh35hNt8srZQM4619" + - "FTgB66Xmp4EtVyhpQV+t02g6NzK72oZI0vnAvqhpkxLeLiMCyrI416wHm5Tkukhx" + - "QmcL2a6hNOyu0ixX/x2kSFXApEnVrJ+/IxGyfyw8kf4N2IZpW5nEP847lpfj0SZZ" + - "Fwrd1mnfnDbYohX2zRptLy2ZUn06Qo9pkG5ntvFEPo9bfZeULtjYzIl6K8gJ2uGZ" + "HQIDAQAB", true}, - {"12345", false}, - {"", false}, - {"Vml2YW11cyBmZXJtZtesting123", false}, - } - for _, test := range tests { - actual := IsBase64(test.param) - if actual != test.expected { - t.Errorf("Expected IsBase64(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsISO3166Alpha2(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"ABCD", false}, - {"A", false}, - {"AC", false}, - {"AP", false}, - {"GER", false}, - {"NU", true}, - {"DE", true}, - {"JP", true}, - {"JPN", false}, - {"ZWE", false}, - {"GER", false}, - {"DEU", false}, - } - for _, test := range tests { - actual := IsISO3166Alpha2(test.param) - if actual != test.expected { - t.Errorf("Expected IsISO3166Alpha2(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsISO3166Alpha3(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"ABCD", false}, - {"A", false}, - {"AC", false}, - {"AP", false}, - {"NU", false}, - {"DE", false}, - {"JP", false}, - {"ZWE", true}, - {"JPN", true}, - {"GER", false}, - {"DEU", true}, - } - for _, test := range tests { - actual := IsISO3166Alpha3(test.param) - if actual != test.expected { - t.Errorf("Expected IsISO3166Alpha3(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsISO693Alpha2(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"abcd", false}, - {"a", false}, - {"ac", false}, - {"ap", false}, - {"de", true}, - {"DE", false}, - {"mk", true}, - {"mac", false}, - {"sw", true}, - {"SW", false}, - {"ger", false}, - {"deu", false}, - } - for _, test := range tests { - actual := IsISO693Alpha2(test.param) - if actual != test.expected { - t.Errorf("Expected IsISO693Alpha2(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsISO693Alpha3b(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"abcd", false}, - {"a", false}, - {"ac", false}, - {"ap", false}, - {"de", false}, - {"DE", false}, - {"mkd", false}, - {"mac", true}, - {"sw", false}, - {"SW", false}, - {"ger", true}, - {"deu", false}, - } - for _, test := range tests { - actual := IsISO693Alpha3b(test.param) - if actual != test.expected { - t.Errorf("Expected IsISO693Alpha3b(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsIP(t *testing.T) { - t.Parallel() - - // Without version - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"127.0.0.1", true}, - {"0.0.0.0", true}, - {"255.255.255.255", true}, - {"1.2.3.4", true}, - {"::1", true}, - {"2001:db8:0000:1:1:1:1:1", true}, - {"300.0.0.0", false}, - } - for _, test := range tests { - actual := IsIP(test.param) - if actual != test.expected { - t.Errorf("Expected IsIP(%q) to be %v, got %v", test.param, test.expected, actual) - } - } - - // IPv4 - tests = []struct { - param string - expected bool - }{ - {"", false}, - {"127.0.0.1", true}, - {"0.0.0.0", true}, - {"255.255.255.255", true}, - {"1.2.3.4", true}, - {"::1", false}, - {"2001:db8:0000:1:1:1:1:1", false}, - {"300.0.0.0", false}, - } - for _, test := range tests { - actual := IsIPv4(test.param) - if actual != test.expected { - t.Errorf("Expected IsIPv4(%q) to be %v, got %v", test.param, test.expected, actual) - } - } - - // IPv6 - tests = []struct { - param string - expected bool - }{ - {"", false}, - {"127.0.0.1", false}, - {"0.0.0.0", false}, - {"255.255.255.255", false}, - {"1.2.3.4", false}, - {"::1", true}, - {"2001:db8:0000:1:1:1:1:1", true}, - {"300.0.0.0", false}, - } - for _, test := range tests { - actual := IsIPv6(test.param) - if actual != test.expected { - t.Errorf("Expected IsIPv6(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsPort(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"1", true}, - {"65535", true}, - {"0", false}, - {"65536", false}, - {"65538", false}, - } - - for _, test := range tests { - actual := IsPort(test.param) - if actual != test.expected { - t.Errorf("Expected IsPort(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsDNSName(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"localhost", true}, - {"a.bc", true}, - {"a.b.", true}, - {"a.b..", false}, - {"localhost.local", true}, - {"localhost.localdomain.intern", true}, - {"l.local.intern", true}, - {"ru.link.n.svpncloud.com", true}, - {"-localhost", false}, - {"localhost.-localdomain", false}, - {"localhost.localdomain.-int", false}, - {"_localhost", true}, - {"localhost._localdomain", true}, - {"localhost.localdomain._int", true}, - {"lÖcalhost", false}, - {"localhost.lÖcaldomain", false}, - {"localhost.localdomain.üntern", false}, - {"__", true}, - {"localhost/", false}, - {"127.0.0.1", false}, - {"[::1]", false}, - {"50.50.50.50", false}, - {"localhost.localdomain.intern:65535", false}, - {"漢字汉字", false}, - {"www.jubfvq1v3p38i51622y0dvmdk1mymowjyeu26gbtw9andgynj1gg8z3msb1kl5z6906k846pj3sulm4kiyk82ln5teqj9nsht59opr0cs5ssltx78lfyvml19lfq1wp4usbl0o36cmiykch1vywbttcus1p9yu0669h8fj4ll7a6bmop505908s1m83q2ec2qr9nbvql2589adma3xsq2o38os2z3dmfh2tth4is4ixyfasasasefqwe4t2ub2fz1rme.de", false}, - } - - for _, test := range tests { - actual := IsDNSName(test.param) - if actual != test.expected { - t.Errorf("Expected IsDNS(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsHost(t *testing.T) { - t.Parallel() - var tests = []struct { - param string - expected bool - }{ - {"localhost", true}, - {"localhost.localdomain", true}, - {"2001:db8:0000:1:1:1:1:1", true}, - {"::1", true}, - {"play.golang.org", true}, - {"localhost.localdomain.intern:65535", false}, - {"-[::1]", false}, - {"-localhost", false}, - {".localhost", false}, - } - for _, test := range tests { - actual := IsHost(test.param) - if actual != test.expected { - t.Errorf("Expected IsHost(%q) to be %v, got %v", test.param, test.expected, actual) - } - } - -} - -func TestIsDialString(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"localhost.local:1", true}, - {"localhost.localdomain:9090", true}, - {"localhost.localdomain.intern:65535", true}, - {"127.0.0.1:30000", true}, - {"[::1]:80", true}, - {"[1200::AB00:1234::2552:7777:1313]:22", false}, - {"-localhost:1", false}, - {"localhost.-localdomain:9090", false}, - {"localhost.localdomain.-int:65535", false}, - {"localhost.loc:100000", false}, - {"漢字汉字:2", false}, - {"www.jubfvq1v3p38i51622y0dvmdk1mymowjyeu26gbtw9andgynj1gg8z3msb1kl5z6906k846pj3sulm4kiyk82ln5teqj9nsht59opr0cs5ssltx78lfyvml19lfq1wp4usbl0o36cmiykch1vywbttcus1p9yu0669h8fj4ll7a6bmop505908s1m83q2ec2qr9nbvql2589adma3xsq2o38os2z3dmfh2tth4is4ixyfasasasefqwe4t2ub2fz1rme.de:20000", false}, - } - - for _, test := range tests { - actual := IsDialString(test.param) - if actual != test.expected { - t.Errorf("Expected IsDialString(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsMAC(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"3D:F2:C9:A6:B3:4F", true}, - {"3D-F2-C9-A6-B3:4F", false}, - {"123", false}, - {"", false}, - {"abacaba", false}, - } - for _, test := range tests { - actual := IsMAC(test.param) - if actual != test.expected { - t.Errorf("Expected IsMAC(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestFilePath(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - osType int - }{ - {"c:\\" + strings.Repeat("a", 32767), true, Win}, //See http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath - {"c:\\" + strings.Repeat("a", 32768), false, Win}, - {"c:\\path\\file (x86)\bar", true, Win}, - {"c:\\path\\file", true, Win}, - {"c:\\path\\file:exe", false, Unknown}, - {"C:\\", true, Win}, - {"c:\\path\\file\\", true, Win}, - {"c:/path/file/", false, Unknown}, - {"/path/file/", true, Unix}, - {"/path/file:SAMPLE/", true, Unix}, - {"/path/file:/.txt", true, Unix}, - {"/path", true, Unix}, - {"/path/__bc/file.txt", true, Unix}, - {"/path/a--ac/file.txt", true, Unix}, - {"/_path/file.txt", true, Unix}, - {"/path/__bc/file.txt", true, Unix}, - {"/path/a--ac/file.txt", true, Unix}, - {"/__path/--file.txt", true, Unix}, - {"/path/a bc", true, Unix}, - } - for _, test := range tests { - actual, osType := IsFilePath(test.param) - if actual != test.expected || osType != test.osType { - t.Errorf("Expected IsFilePath(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsLatitude(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"-90.000", true}, - {"+90", true}, - {"47.1231231", true}, - {"+99.9", false}, - {"108", false}, - } - for _, test := range tests { - actual := IsLatitude(test.param) - if actual != test.expected { - t.Errorf("Expected IsLatitude(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsLongitude(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"-180.000", true}, - {"180.1", false}, - {"+73.234", true}, - {"+382.3811", false}, - {"23.11111111", true}, - } - for _, test := range tests { - actual := IsLongitude(test.param) - if actual != test.expected { - t.Errorf("Expected IsLongitude(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsSSN(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"00-90-8787", false}, - {"66690-76", false}, - {"191 60 2869", true}, - {"191-60-2869", true}, - } - for _, test := range tests { - actual := IsSSN(test.param) - if actual != test.expected { - t.Errorf("Expected IsSSN(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsMongoID(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"507f1f77bcf86cd799439011", true}, - {"507f1f77bcf86cd7994390", false}, - {"507f1f77bcf86cd79943901z", false}, - {"507f1f77bcf86cd799439011 ", false}, - {"", false}, - } - for _, test := range tests { - actual := IsMongoID(test.param) - if actual != test.expected { - t.Errorf("Expected IsMongoID(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsSemver(t *testing.T) { - t.Parallel() - var tests = []struct { - param string - expected bool - }{ - {"v1.0.0", true}, - {"1.0.0", true}, - {"1.1.01", false}, - {"1.01.0", false}, - {"01.1.0", false}, - {"v1.1.01", false}, - {"v1.01.0", false}, - {"v01.1.0", false}, - {"1.0.0-alpha", true}, - {"1.0.0-alpha.1", true}, - {"1.0.0-0.3.7", true}, - {"1.0.0-0.03.7", false}, - {"1.0.0-00.3.7", false}, - {"1.0.0-x.7.z.92", true}, - {"1.0.0-alpha+001", true}, - {"1.0.0+20130313144700", true}, - {"1.0.0-beta+exp.sha.5114f85", true}, - {"1.0.0-beta+exp.sha.05114f85", true}, - {"1.0.0-+beta", false}, - {"1.0.0-b+-9+eta", false}, - {"v+1.8.0-b+-9+eta", false}, - } - for _, test := range tests { - actual := IsSemver(test.param) - if actual != test.expected { - t.Errorf("Expected IsSemver(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsTime(t *testing.T) { - t.Parallel() - var tests = []struct { - param string - format string - expected bool - }{ - {"2016-12-31 11:00", time.RFC3339, false}, - {"2016-12-31 11:00:00", time.RFC3339, false}, - {"2016-12-31T11:00", time.RFC3339, false}, - {"2016-12-31T11:00:00", time.RFC3339, false}, - {"2016-12-31T11:00:00Z", time.RFC3339, true}, - {"2016-12-31T11:00:00+01:00", time.RFC3339, true}, - {"2016-12-31T11:00:00-01:00", time.RFC3339, true}, - {"2016-12-31T11:00:00.05Z", time.RFC3339, true}, - {"2016-12-31T11:00:00.05-01:00", time.RFC3339, true}, - {"2016-12-31T11:00:00.05+01:00", time.RFC3339, true}, - {"2016-12-31T11:00:00", RF3339WithoutZone, true}, - {"2016-12-31T11:00:00Z", RF3339WithoutZone, false}, - {"2016-12-31T11:00:00+01:00", RF3339WithoutZone, false}, - {"2016-12-31T11:00:00-01:00", RF3339WithoutZone, false}, - {"2016-12-31T11:00:00.05Z", RF3339WithoutZone, false}, - {"2016-12-31T11:00:00.05-01:00", RF3339WithoutZone, false}, - {"2016-12-31T11:00:00.05+01:00", RF3339WithoutZone, false}, - } - for _, test := range tests { - actual := IsTime(test.param, test.format) - if actual != test.expected { - t.Errorf("Expected IsTime(%q, time.RFC3339) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsRFC3339(t *testing.T) { - t.Parallel() - var tests = []struct { - param string - expected bool - }{ - {"2016-12-31 11:00", false}, - {"2016-12-31 11:00:00", false}, - {"2016-12-31T11:00", false}, - {"2016-12-31T11:00:00", false}, - {"2016-12-31T11:00:00Z", true}, - {"2016-12-31T11:00:00+01:00", true}, - {"2016-12-31T11:00:00-01:00", true}, - {"2016-12-31T11:00:00.05Z", true}, - {"2016-12-31T11:00:00.05-01:00", true}, - {"2016-12-31T11:00:00.05+01:00", true}, - } - for _, test := range tests { - actual := IsRFC3339(test.param) - if actual != test.expected { - t.Errorf("Expected IsRFC3339(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestIsISO4217(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"", false}, - {"ABCD", false}, - {"A", false}, - {"ZZZ", false}, - {"usd", false}, - {"USD", true}, - } - for _, test := range tests { - actual := IsISO4217(test.param) - if actual != test.expected { - t.Errorf("Expected IsISO4217(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestByteLength(t *testing.T) { - t.Parallel() - - var tests = []struct { - value string - min string - max string - expected bool - }{ - {"123456", "0", "100", true}, - {"1239999", "0", "0", false}, - {"1239asdfasf99", "100", "200", false}, - {"1239999asdff29", "10", "30", true}, - {"你", "0", "1", false}, - } - for _, test := range tests { - actual := ByteLength(test.value, test.min, test.max) - if actual != test.expected { - t.Errorf("Expected ByteLength(%s, %s, %s) to be %v, got %v", test.value, test.min, test.max, test.expected, actual) - } - } -} - -func TestRuneLength(t *testing.T) { - t.Parallel() - - var tests = []struct { - value string - min string - max string - expected bool - }{ - {"123456", "0", "100", true}, - {"1239999", "0", "0", false}, - {"1239asdfasf99", "100", "200", false}, - {"1239999asdff29", "10", "30", true}, - {"你", "0", "1", true}, - } - for _, test := range tests { - actual := RuneLength(test.value, test.min, test.max) - if actual != test.expected { - t.Errorf("Expected RuneLength(%s, %s, %s) to be %v, got %v", test.value, test.min, test.max, test.expected, actual) - } - } -} - -func TestStringLength(t *testing.T) { - t.Parallel() - - var tests = []struct { - value string - min string - max string - expected bool - }{ - {"123456", "0", "100", true}, - {"1239999", "0", "0", false}, - {"1239asdfasf99", "100", "200", false}, - {"1239999asdff29", "10", "30", true}, - {"あいうえお", "0", "5", true}, - {"あいうえおか", "0", "5", false}, - {"あいうえお", "0", "0", false}, - {"あいうえ", "5", "10", false}, - } - for _, test := range tests { - actual := StringLength(test.value, test.min, test.max) - if actual != test.expected { - t.Errorf("Expected StringLength(%s, %s, %s) to be %v, got %v", test.value, test.min, test.max, test.expected, actual) - } - } -} - -func TestIsIn(t *testing.T) { - t.Parallel() - - var tests = []struct { - value string - params []string - expected bool - }{ - {"PRESENT", []string{"PRESENT"}, true}, - {"PRESENT", []string{"PRESENT", "PRÉSENTE", "NOTABSENT"}, true}, - {"PRÉSENTE", []string{"PRESENT", "PRÉSENTE", "NOTABSENT"}, true}, - {"PRESENT", []string{}, false}, - {"PRESENT", nil, false}, - {"ABSENT", []string{"PRESENT", "PRÉSENTE", "NOTABSENT"}, false}, - {"", []string{"PRESENT", "PRÉSENTE", "NOTABSENT"}, false}, - } - for _, test := range tests { - actual := IsIn(test.value, test.params...) - if actual != test.expected { - t.Errorf("Expected IsIn(%s, %v) to be %v, got %v", test.value, test.params, test.expected, actual) - } - } -} - -type Address struct { - Street string `valid:"-"` - Zip string `json:"zip" valid:"numeric,required"` -} - -type User struct { - Name string `valid:"required"` - Email string `valid:"required,email"` - Password string `valid:"required"` - Age int `valid:"required,numeric,@#\u0000"` - Home *Address - Work []Address -} - -type UserValid struct { - Name string `valid:"required"` - Email string `valid:"required,email"` - Password string `valid:"required"` - Age int `valid:"required"` - Home *Address - Work []Address `valid:"required"` -} - -type PrivateStruct struct { - privateField string `valid:"required,alpha,d_k"` - NonZero int - ListInt []int - ListString []string `valid:"alpha"` - Work [2]Address - Home Address - Map map[string]Address -} - -type NegationStruct struct { - NotInt string `valid:"!int"` - Int string `valid:"int"` -} - -type LengthStruct struct { - Length string `valid:"length(10|20)"` -} - -type StringLengthStruct struct { - Length string `valid:"stringlength(10|20)"` -} - -type StringMatchesStruct struct { - StringMatches string `valid:"matches(^[0-9]{3}$)"` -} - -// TODO: this testcase should be fixed -// type StringMatchesComplexStruct struct { -// StringMatches string `valid:"matches(^\\$\\([\"']\\w+[\"']\\)$)"` -// } - -type IsInStruct struct { - IsIn string `valid:"in(PRESENT|PRÉSENTE|NOTABSENT)"` -} - -type Post struct { - Title string `valid:"alpha,required"` - Message string `valid:"ascii"` - AuthorIP string `valid:"ipv4"` -} - -type MissingValidationDeclarationStruct struct { - Name string `` - Email string `valid:"required,email"` -} - -type FieldRequiredByDefault struct { - Email string `valid:"email"` -} - -type MultipleFieldsRequiredByDefault struct { - Url string `valid:"url"` - Email string `valid:"email"` -} - -type FieldsRequiredByDefaultButExemptStruct struct { - Name string `valid:"-"` - Email string `valid:"email"` -} - -type FieldsRequiredByDefaultButExemptOrOptionalStruct struct { - Name string `valid:"-"` - Email string `valid:"optional,email"` -} - -type MessageWithSeveralFieldsStruct struct { - Title string `valid:"length(1|10)"` - Body string `valid:"length(1|10)"` -} - -func TestValidateMissingValidationDeclarationStruct(t *testing.T) { - var tests = []struct { - param MissingValidationDeclarationStruct - expected bool - }{ - {MissingValidationDeclarationStruct{}, false}, - {MissingValidationDeclarationStruct{Name: "TEST", Email: "test@example.com"}, false}, - } - SetFieldsRequiredByDefault(true) - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } - SetFieldsRequiredByDefault(false) -} - -func TestFieldRequiredByDefault(t *testing.T) { - var tests = []struct { - param FieldRequiredByDefault - expected bool - }{ - {FieldRequiredByDefault{}, false}, - } - SetFieldsRequiredByDefault(true) - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } - SetFieldsRequiredByDefault(false) -} - -func TestMultipleFieldsRequiredByDefault(t *testing.T) { - var tests = []struct { - param MultipleFieldsRequiredByDefault - expected bool - }{ - {MultipleFieldsRequiredByDefault{}, false}, - } - SetFieldsRequiredByDefault(true) - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } - SetFieldsRequiredByDefault(false) -} - -func TestFieldsRequiredByDefaultButExemptStruct(t *testing.T) { - var tests = []struct { - param FieldsRequiredByDefaultButExemptStruct - expected bool - }{ - {FieldsRequiredByDefaultButExemptStruct{}, false}, - {FieldsRequiredByDefaultButExemptStruct{Name: "TEST"}, false}, - {FieldsRequiredByDefaultButExemptStruct{Email: ""}, false}, - {FieldsRequiredByDefaultButExemptStruct{Email: "test@example.com"}, true}, - } - SetFieldsRequiredByDefault(true) - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } - SetFieldsRequiredByDefault(false) -} - -func TestFieldsRequiredByDefaultButExemptOrOptionalStruct(t *testing.T) { - var tests = []struct { - param FieldsRequiredByDefaultButExemptOrOptionalStruct - expected bool - }{ - {FieldsRequiredByDefaultButExemptOrOptionalStruct{}, true}, - {FieldsRequiredByDefaultButExemptOrOptionalStruct{Name: "TEST"}, true}, - {FieldsRequiredByDefaultButExemptOrOptionalStruct{Email: ""}, true}, - {FieldsRequiredByDefaultButExemptOrOptionalStruct{Email: "test@example.com"}, true}, - {FieldsRequiredByDefaultButExemptOrOptionalStruct{Email: "test@example"}, false}, - } - SetFieldsRequiredByDefault(true) - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } - SetFieldsRequiredByDefault(false) -} - -func TestInvalidValidator(t *testing.T) { - type InvalidStruct struct { - Field int `valid:"someInvalidValidator"` - } - - invalidStruct := InvalidStruct{1} - if valid, err := ValidateStruct(&invalidStruct); valid || err == nil || - err.Error() != `Field: The following validator is invalid or can't be applied to the field: "someInvalidValidator"` { - t.Errorf("Got an unexpected result for struct with invalid validator: %t %s", valid, err) - } -} - -func TestCustomValidator(t *testing.T) { - type ValidStruct struct { - Field int `valid:"customTrueValidator"` - } - - type InvalidStruct struct { - Field int `valid:"customFalseValidator~Custom validator error"` - } - - type StructWithCustomAndBuiltinValidator struct { - Field int `valid:"customTrueValidator,required"` - } - - if valid, err := ValidateStruct(&ValidStruct{Field: 1}); !valid || err != nil { - t.Errorf("Got an unexpected result for struct with custom always true validator: %t %s", valid, err) - } - - if valid, err := ValidateStruct(&InvalidStruct{Field: 1}); valid || err == nil || err.Error() != "Custom validator error" { - t.Errorf("Got an unexpected result for struct with custom always false validator: %t %s", valid, err) - } - - mixedStruct := StructWithCustomAndBuiltinValidator{} - if valid, err := ValidateStruct(&mixedStruct); valid || err == nil || err.Error() != "Field: non zero value required" { - t.Errorf("Got an unexpected result for invalid struct with custom and built-in validators: %t %s", valid, err) - } - - mixedStruct.Field = 1 - if valid, err := ValidateStruct(&mixedStruct); !valid || err != nil { - t.Errorf("Got an unexpected result for valid struct with custom and built-in validators: %t %s", valid, err) - } -} - -type CustomByteArray [6]byte - -type StructWithCustomByteArray struct { - ID CustomByteArray `valid:"customByteArrayValidator,customMinLengthValidator"` - Email string `valid:"email"` - CustomMinLength int `valid:"-"` -} - -func TestStructWithCustomByteArray(t *testing.T) { - t.Parallel() - - // add our custom byte array validator that fails when the byte array is pristine (all zeroes) - CustomTypeTagMap.Set("customByteArrayValidator", CustomTypeValidator(func(i interface{}, o interface{}) bool { - switch v := o.(type) { - case StructWithCustomByteArray: - if len(v.Email) > 0 { - if v.Email != "test@example.com" { - t.Errorf("v.Email should have been 'test@example.com' but was '%s'", v.Email) - } - } - default: - t.Errorf("Context object passed to custom validator should have been a StructWithCustomByteArray but was %T (%+v)", o, o) - } - - switch v := i.(type) { - case CustomByteArray: - for _, e := range v { // check if v is empty, i.e. all zeroes - if e != 0 { - return true - } - } - } - return false - })) - CustomTypeTagMap.Set("customMinLengthValidator", CustomTypeValidator(func(i interface{}, o interface{}) bool { - switch v := o.(type) { - case StructWithCustomByteArray: - return len(v.ID) >= v.CustomMinLength - } - return false - })) - testCustomByteArray := CustomByteArray{'1', '2', '3', '4', '5', '6'} - var tests = []struct { - param StructWithCustomByteArray - expected bool - }{ - {StructWithCustomByteArray{}, false}, - {StructWithCustomByteArray{Email: "test@example.com"}, false}, - {StructWithCustomByteArray{ID: testCustomByteArray, Email: "test@example.com"}, true}, - {StructWithCustomByteArray{ID: testCustomByteArray, Email: "test@example.com", CustomMinLength: 7}, false}, - } - SetFieldsRequiredByDefault(true) - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } - SetFieldsRequiredByDefault(false) -} - -func TestValidateNegationStruct(t *testing.T) { - var tests = []struct { - param NegationStruct - expected bool - }{ - {NegationStruct{"a1", "11"}, true}, - {NegationStruct{"email@email.email", "11"}, true}, - {NegationStruct{"123456----", "11"}, true}, - {NegationStruct{"::1", "11"}, true}, - {NegationStruct{"123.123", "11"}, true}, - {NegationStruct{"a1", "a1"}, false}, - {NegationStruct{"11", "a1"}, false}, - {NegationStruct{"11", "11"}, false}, - } - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } -} - -func TestLengthStruct(t *testing.T) { - var tests = []struct { - param interface{} - expected bool - }{ - {LengthStruct{"11111"}, false}, - {LengthStruct{"11111111111111111110000000000000000"}, false}, - {LengthStruct{"11dfffdf0099"}, true}, - } - - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } -} - -func TestStringLengthStruct(t *testing.T) { - var tests = []struct { - param interface{} - expected bool - }{ - {StringLengthStruct{"11111"}, false}, - {StringLengthStruct{"11111111111111111110000000000000000"}, false}, - {StringLengthStruct{"11dfffdf0099"}, true}, - {StringLengthStruct{"あいうえお"}, false}, - {StringLengthStruct{"あいうえおかきくけこ"}, true}, - {StringLengthStruct{"あいうえおかきくけこさしすせそたちつてと"}, true}, - {StringLengthStruct{"あいうえおかきくけこさしすせそたちつてとな"}, false}, - } - - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } -} - -func TestStringMatchesStruct(t *testing.T) { - var tests = []struct { - param interface{} - expected bool - }{ - {StringMatchesStruct{"123"}, true}, - {StringMatchesStruct{"123456"}, false}, - {StringMatchesStruct{"123abcd"}, false}, - } - - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } -} - -func TestIsInStruct(t *testing.T) { - var tests = []struct { - param interface{} - expected bool - }{ - {IsInStruct{"PRESENT"}, true}, - {IsInStruct{""}, true}, - {IsInStruct{" "}, false}, - {IsInStruct{"ABSENT"}, false}, - } - - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } -} - -func TestRequiredIsInStruct(t *testing.T) { - type RequiredIsInStruct struct { - IsIn string `valid:"in(PRESENT|PRÉSENTE|NOTABSENT),required"` - } - - var tests = []struct { - param interface{} - expected bool - }{ - {RequiredIsInStruct{"PRESENT"}, true}, - {RequiredIsInStruct{""}, false}, - {RequiredIsInStruct{" "}, false}, - {RequiredIsInStruct{"ABSENT"}, false}, - } - - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } -} - -func TestEmptyRequiredIsInStruct(t *testing.T) { - type EmptyRequiredIsInStruct struct { - IsIn string `valid:"in(),required"` - } - - var tests = []struct { - param interface{} - expected bool - }{ - {EmptyRequiredIsInStruct{"PRESENT"}, false}, - {EmptyRequiredIsInStruct{""}, false}, - {EmptyRequiredIsInStruct{" "}, false}, - {EmptyRequiredIsInStruct{"ABSENT"}, false}, - } - - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } -} - -func TestFunkyIsInStruct(t *testing.T) { - type FunkyIsInStruct struct { - IsIn string `valid:"in(PRESENT|| |PRÉSENTE|NOTABSENT)"` - } - - var tests = []struct { - param interface{} - expected bool - }{ - {FunkyIsInStruct{"PRESENT"}, true}, - {FunkyIsInStruct{""}, true}, - {FunkyIsInStruct{" "}, true}, - {FunkyIsInStruct{"ABSENT"}, false}, - } - - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } -} - -// TODO: test case broken -// func TestStringMatchesComplexStruct(t *testing.T) { -// var tests = []struct { -// param interface{} -// expected bool -// }{ -// {StringMatchesComplexStruct{"$()"}, false}, -// {StringMatchesComplexStruct{"$('AZERTY')"}, true}, -// {StringMatchesComplexStruct{`$("AZERTY")`}, true}, -// {StringMatchesComplexStruct{`$("")`}, false}, -// {StringMatchesComplexStruct{"AZERTY"}, false}, -// {StringMatchesComplexStruct{"$AZERTY"}, false}, -// } - -// for _, test := range tests { -// actual, err := ValidateStruct(test.param) -// if actual != test.expected { -// t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) -// if err != nil { -// t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) -// } -// } -// } -// } - -func TestValidateStruct(t *testing.T) { - - var tests = []struct { - param interface{} - expected bool - }{ - {User{"John", "john@yahoo.com", "123G#678", 20, &Address{"Street", "123456"}, []Address{{"Street", "123456"}, {"Street", "123456"}}}, false}, - {User{"John", "john!yahoo.com", "12345678", 20, &Address{"Street", "ABC456D89"}, []Address{{"Street", "ABC456D89"}, {"Street", "123456"}}}, false}, - {User{"John", "", "12345", 0, &Address{"Street", "123456789"}, []Address{{"Street", "ABC456D89"}, {"Street", "123456"}}}, false}, - {UserValid{"John", "john@yahoo.com", "123G#678", 20, &Address{"Street", "123456"}, []Address{{"Street", "123456"}, {"Street", "123456"}}}, true}, - {UserValid{"John", "john!yahoo.com", "12345678", 20, &Address{"Street", "ABC456D89"}, []Address{}}, false}, - {UserValid{"John", "john@yahoo.com", "12345678", 20, &Address{"Street", "123456xxx"}, []Address{{"Street", "123456"}, {"Street", "123456"}}}, false}, - {UserValid{"John", "john!yahoo.com", "12345678", 20, &Address{"Street", "ABC456D89"}, []Address{{"Street", "ABC456D89"}, {"Street", "123456"}}}, false}, - {UserValid{"John", "", "12345", 0, &Address{"Street", "123456789"}, []Address{{"Street", "ABC456D89"}, {"Street", "123456"}}}, false}, - {nil, true}, - {User{"John", "john@yahoo.com", "123G#678", 0, &Address{"Street", "123456"}, []Address{}}, false}, - {"im not a struct", false}, - } - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } - - TagMap["d_k"] = Validator(func(str string) bool { - return str == "d_k" - }) - result, err := ValidateStruct(PrivateStruct{"d_k", 0, []int{1, 2}, []string{"hi", "super"}, [2]Address{{"Street", "123456"}, - {"Street", "123456"}}, Address{"Street", "123456"}, map[string]Address{"address": {"Street", "123456"}}}) - if result != true { - t.Log("Case ", 6, ": expected ", true, " when result is ", result) - t.Error(err) - t.FailNow() - } -} - -type testByteArray [8]byte -type testByteMap map[byte]byte -type testByteSlice []byte -type testStringStringMap map[string]string -type testStringIntMap map[string]int - -func TestRequired(t *testing.T) { - - testString := "foobar" - var tests = []struct { - param interface{} - expected bool - }{ - { - struct { - Pointer *string `valid:"required"` - }{}, - false, - }, - { - struct { - Pointer *string `valid:"required"` - }{ - Pointer: &testString, - }, - true, - }, - { - struct { - Addr Address `valid:"required"` - }{}, - false, - }, - { - struct { - Addr Address `valid:"required"` - }{ - Addr: Address{"", "123"}, - }, - true, - }, - { - struct { - Pointer *Address `valid:"required"` - }{}, - false, - }, - { - struct { - Pointer *Address `valid:"required"` - }{ - Pointer: &Address{"", "123"}, - }, - true, - }, - { - struct { - TestByteArray testByteArray `valid:"required"` - }{}, - false, - }, - { - struct { - TestByteArray testByteArray `valid:"required"` - }{ - testByteArray{}, - }, - false, - }, - { - struct { - TestByteArray testByteArray `valid:"required"` - }{ - testByteArray{'1', '2', '3', '4', '5', '6', '7', 'A'}, - }, - true, - }, - { - struct { - TestByteMap testByteMap `valid:"required"` - }{}, - false, - }, - { - struct { - TestByteSlice testByteSlice `valid:"required"` - }{}, - false, - }, - { - struct { - TestStringStringMap testStringStringMap `valid:"required"` - }{ - testStringStringMap{"test": "test"}, - }, - true, - }, - { - struct { - TestIntMap testStringIntMap `valid:"required"` - }{ - testStringIntMap{"test": 42}, - }, - true, - }, - } - for _, test := range tests { - actual, err := ValidateStruct(test.param) - if actual != test.expected { - t.Errorf("Expected ValidateStruct(%q) to be %v, got %v", test.param, test.expected, actual) - if err != nil { - t.Errorf("Got Error on ValidateStruct(%q): %s", test.param, err) - } - } - } -} - -func TestErrorByField(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected string - }{ - {"message", ""}, - {"Message", ""}, - {"title", ""}, - {"Title", "My123 does not validate as alpha"}, - {"AuthorIP", "123 does not validate as ipv4"}, - } - post := &Post{"My123", "duck13126", "123"} - _, err := ValidateStruct(post) - - for _, test := range tests { - actual := ErrorByField(err, test.param) - if actual != test.expected { - t.Errorf("Expected ErrorByField(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestErrorsByField(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected string - }{ - {"Title", "My123 does not validate as alpha"}, - {"AuthorIP", "123 does not validate as ipv4"}, - } - post := &Post{Title: "My123", Message: "duck13126", AuthorIP: "123"} - _, err := ValidateStruct(post) - errs := ErrorsByField(err) - if len(errs) != 2 { - t.Errorf("There should only be 2 errors but got %v", len(errs)) - } - - for _, test := range tests { - if actual, ok := errs[test.param]; !ok || actual != test.expected { - t.Errorf("Expected ErrorsByField(%q) to be %v, got %v", test.param, test.expected, actual) - } - } - - tests = []struct { - param string - expected string - }{ - {"Title", ";:;message;:; does not validate as length(1|10)"}, - {"Body", ";:;message;:; does not validate as length(1|10)"}, - } - - message := &MessageWithSeveralFieldsStruct{Title: ";:;message;:;", Body: ";:;message;:;"} - _, err = ValidateStruct(message) - errs = ErrorsByField(err) - if len(errs) != 2 { - t.Errorf("There should only be 2 errors but got %v", len(errs)) - } - - for _, test := range tests { - if actual, ok := errs[test.param]; !ok || actual != test.expected { - t.Errorf("Expected ErrorsByField(%q) to be %v, got %v", test.param, test.expected, actual) - } - } - - tests = []struct { - param string - expected string - }{ - {"CustomField", "An error occurred"}, - } - - err = Error{"CustomField", fmt.Errorf("An error occurred"), false, "hello"} - errs = ErrorsByField(err) - - if len(errs) != 1 { - t.Errorf("There should only be 1 errors but got %v", len(errs)) - } - - for _, test := range tests { - if actual, ok := errs[test.param]; !ok || actual != test.expected { - t.Errorf("Expected ErrorsByField(%q) to be %v, got %v", test.param, test.expected, actual) - } - } - - type StructWithCustomValidation struct { - Email string `valid:"email"` - ID string `valid:"falseValidation"` - } - - CustomTypeTagMap.Set("falseValidation", CustomTypeValidator(func(i interface{}, o interface{}) bool { - return false - })) - - tests = []struct { - param string - expected string - }{ - {"Email", "My123 does not validate as email"}, - {"ID", "duck13126 does not validate as falseValidation"}, - } - s := &StructWithCustomValidation{Email: "My123", ID: "duck13126"} - _, err = ValidateStruct(s) - errs = ErrorsByField(err) - if len(errs) != 2 { - t.Errorf("There should only be 2 errors but got %v", len(errs)) - } - - for _, test := range tests { - if actual, ok := errs[test.param]; !ok || actual != test.expected { - t.Errorf("Expected ErrorsByField(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestValidateStructPointers(t *testing.T) { - // Struct which uses pointers for values - type UserWithPointers struct { - Name *string `valid:"-"` - Email *string `valid:"email"` - FavoriteFood *string `valid:"length(0|32)"` - Nerd *bool `valid:"-"` - } - - var tests = []struct { - param string - expected string - }{ - {"Name", ""}, - {"Email", "invalid does not validate as email"}, - {"FavoriteFood", ""}, - {"Nerd", ""}, - } - - name := "Herman" - email := "invalid" - food := "Pizza" - nerd := true - user := &UserWithPointers{&name, &email, &food, &nerd} - _, err := ValidateStruct(user) - - for _, test := range tests { - actual := ErrorByField(err, test.param) - if actual != test.expected { - t.Errorf("Expected ErrorByField(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func ExampleValidateStruct() { - type Post struct { - Title string `valid:"alphanum,required"` - Message string `valid:"duck,ascii"` - AuthorIP string `valid:"ipv4"` - } - post := &Post{"My Example Post", "duck", "123.234.54.3"} - - //Add your own struct validation tags - TagMap["duck"] = Validator(func(str string) bool { - return str == "duck" - }) - - result, err := ValidateStruct(post) - if err != nil { - println("error: " + err.Error()) - } - println(result) -} - -func TestValidateStructParamValidatorInt(t *testing.T) { - type Test1 struct { - Int int `valid:"range(1|10)"` - Int8 int8 `valid:"range(1|10)"` - Int16 int16 `valid:"range(1|10)"` - Int32 int32 `valid:"range(1|10)"` - Int64 int64 `valid:"range(1|10)"` - - Uint uint `valid:"range(1|10)"` - Uint8 uint8 `valid:"range(1|10)"` - Uint16 uint16 `valid:"range(1|10)"` - Uint32 uint32 `valid:"range(1|10)"` - Uint64 uint64 `valid:"range(1|10)"` - - Float32 float32 `valid:"range(1|10)"` - Float64 float64 `valid:"range(1|10)"` - } - test1Ok := &Test1{5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5} - test1NotOk := &Test1{11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11} - - _, err := ValidateStruct(test1Ok) - if err != nil { - t.Errorf("Test failed: %s", err) - } - - _, err = ValidateStruct(test1NotOk) - if err == nil { - t.Errorf("Test failed: nil") - } - - type Test2 struct { - Int int `valid:"in(1|10)"` - Int8 int8 `valid:"in(1|10)"` - Int16 int16 `valid:"in(1|10)"` - Int32 int32 `valid:"in(1|10)"` - Int64 int64 `valid:"in(1|10)"` - - Uint uint `valid:"in(1|10)"` - Uint8 uint8 `valid:"in(1|10)"` - Uint16 uint16 `valid:"in(1|10)"` - Uint32 uint32 `valid:"in(1|10)"` - Uint64 uint64 `valid:"in(1|10)"` - - Float32 float32 `valid:"in(1|10)"` - Float64 float64 `valid:"in(1|10)"` - } - - test2Ok1 := &Test2{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} - test2Ok2 := &Test2{10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10} - test2NotOk := &Test2{2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2} - - _, err = ValidateStruct(test2Ok1) - if err != nil { - t.Errorf("Test failed: %s", err) - } - - _, err = ValidateStruct(test2Ok2) - if err != nil { - t.Errorf("Test failed: %s", err) - } - - _, err = ValidateStruct(test2NotOk) - if err == nil { - t.Errorf("Test failed: nil") - } -} - -func TestIsCIDR(t *testing.T) { - t.Parallel() - - var tests = []struct { - param string - expected bool - }{ - {"193.168.3.20/7", true}, - {"2001:db8::/32", true}, - {"2001:0db8:85a3:0000:0000:8a2e:0370:7334/64", true}, - {"193.138.3.20/60", false}, - {"500.323.2.23/43", false}, - {"", false}, - } - for _, test := range tests { - actual := IsCIDR(test.param) - if actual != test.expected { - t.Errorf("Expected IsCIDR(%q) to be %v, got %v", test.param, test.expected, actual) - } - } -} - -func TestOptionalCustomValidators(t *testing.T) { - - CustomTypeTagMap.Set("f2", CustomTypeValidator(func(i interface{}, o interface{}) bool { - return false - })) - - var val struct { - WithCustomError string `valid:"f2~boom,optional"` - WithoutCustomError string `valid:"f2,optional"` - OptionalFirst string `valid:"optional,f2"` - } - - ok, err := ValidateStruct(val) - - if err != nil { - t.Errorf("Expected nil err with optional validation, got %v", err) - } - - if !ok { - t.Error("Expected validation to return true, got false") - } -} - -func TestJSONValidator(t *testing.T) { - - var val struct { - WithJSONName string `json:"with_json_name" valid:"-,required"` - WithoutJSONName string `valid:"-,required"` - WithJSONOmit string `json:"with_other_json_name,omitempty" valid:"-,required"` - WithJSONOption string `json:",omitempty" valid:"-,required"` - WithEmptyJSONName string `json:"-" valid:"-,required"` - } - - _, err := ValidateStruct(val) - - if err == nil { - t.Error("Expected error but got no error") - } - - if Contains(err.Error(), "WithJSONName") { - t.Errorf("Expected error message to contain with_json_name but actual error is: %s", err.Error()) - } - - if Contains(err.Error(), "WithoutJSONName") == false { - t.Errorf("Expected error message to contain WithoutJSONName but actual error is: %s", err.Error()) - } - - if Contains(err.Error(), "omitempty") { - t.Errorf("Expected error message to not contain ',omitempty' but actual error is: %s", err.Error()) - } - - if !Contains(err.Error(), "WithEmptyJSONName") { - t.Errorf("Expected error message to contain WithEmptyJSONName but actual error is: %s", err.Error()) - } -} - -func TestValidatorIncludedInError(t *testing.T) { - post := Post{ - Title: "", - Message: "👍", - AuthorIP: "xyz", - } - - validatorMap := map[string]string{ - "Title": "required", - "Message": "ascii", - "AuthorIP": "ipv4", - } - - ok, errors := ValidateStruct(post) - if ok { - t.Errorf("expected validation to fail %v", ok) - } - - for _, e := range errors.(Errors) { - casted := e.(Error) - if validatorMap[casted.Name] != casted.Validator { - t.Errorf("expected validator for %s to be %s, but was %s", casted.Name, validatorMap[casted.Name], casted.Validator) - } - } - - // check to make sure that validators with arguments (like length(1|10)) don't include the arguments - // in the validator name - message := MessageWithSeveralFieldsStruct{ - Title: "", - Body: "asdfasdfasdfasdfasdf", - } - - validatorMap = map[string]string{ - "Title": "length", - "Body": "length", - } - - ok, errors = ValidateStruct(message) - if ok { - t.Errorf("expected validation to fail, %v", ok) - } - - for _, e := range errors.(Errors) { - casted := e.(Error) - if validatorMap[casted.Name] != casted.Validator { - t.Errorf("expected validator for %s to be %s, but was %s", casted.Name, validatorMap[casted.Name], casted.Validator) - } - } - - // make sure validators with custom messages don't show up in the validator string - type CustomMessage struct { - Text string `valid:"length(1|10)~Custom message"` - } - cs := CustomMessage{Text: "asdfasdfasdfasdf"} - - ok, errors = ValidateStruct(&cs) - if ok { - t.Errorf("expected validation to fail, %v", ok) - } - - validator := errors.(Errors)[0].(Error).Validator - if validator != "length" { - t.Errorf("expected validator for Text to be length, but was %s", validator) - } - -} - -func TestIsRsaPublicKey(t *testing.T) { - var tests = []struct { - rsastr string - keylen int - expected bool - }{ - {`fubar`, 2048, false}, - {`MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvncDCeibmEkabJLmFec7x9y86RP6dIvkVxxbQoOJo06E+p7tH6vCmiGHKnuu -XwKYLq0DKUE3t/HHsNdowfD9+NH8caLzmXqGBx45/Dzxnwqz0qYq7idK+Qff34qrk/YFoU7498U1Ee7PkKb7/VE9BmMEcI3uoKbeXCbJRI -HoTp8bUXOpNTSUfwUNwJzbm2nsHo2xu6virKtAZLTsJFzTUmRd11MrWCvj59lWzt1/eIMN+ekjH8aXeLOOl54CL+kWp48C+V9BchyKCShZ -B7ucimFvjHTtuxziXZQRO7HlcsBOa0WwvDJnRnskdyoD31s4F4jpKEYBJNWTo63v6lUvbQIDAQAB`, 2048, true}, - {`MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvncDCeibmEkabJLmFec7x9y86RP6dIvkVxxbQoOJo06E+p7tH6vCmiGHKnuu -XwKYLq0DKUE3t/HHsNdowfD9+NH8caLzmXqGBx45/Dzxnwqz0qYq7idK+Qff34qrk/YFoU7498U1Ee7PkKb7/VE9BmMEcI3uoKbeXCbJRI -HoTp8bUXOpNTSUfwUNwJzbm2nsHo2xu6virKtAZLTsJFzTUmRd11MrWCvj59lWzt1/eIMN+ekjH8aXeLOOl54CL+kWp48C+V9BchyKCShZ -B7ucimFvjHTtuxziXZQRO7HlcsBOa0WwvDJnRnskdyoD31s4F4jpKEYBJNWTo63v6lUvbQIDAQAB`, 1024, false}, - {`-----BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvncDCeibmEkabJLmFec7 -x9y86RP6dIvkVxxbQoOJo06E+p7tH6vCmiGHKnuuXwKYLq0DKUE3t/HHsNdowfD9 -+NH8caLzmXqGBx45/Dzxnwqz0qYq7idK+Qff34qrk/YFoU7498U1Ee7PkKb7/VE9 -BmMEcI3uoKbeXCbJRIHoTp8bUXOpNTSUfwUNwJzbm2nsHo2xu6virKtAZLTsJFzT -UmRd11MrWCvj59lWzt1/eIMN+ekjH8aXeLOOl54CL+kWp48C+V9BchyKCShZB7uc -imFvjHTtuxziXZQRO7HlcsBOa0WwvDJnRnskdyoD31s4F4jpKEYBJNWTo63v6lUv -bQIDAQAB ------END PUBLIC KEY-----`, 2048, true}, - {`-----BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvncDCeibmEkabJLmFec7 -x9y86RP6dIvkVxxbQoOJo06E+p7tH6vCmiGHKnuuXwKYLq0DKUE3t/HHsNdowfD9 -+NH8caLzmXqGBx45/Dzxnwqz0qYq7idK+Qff34qrk/YFoU7498U1Ee7PkKb7/VE9 -BmMEcI3uoKbeXCbJRIHoTp8bUXOpNTSUfwUNwJzbm2nsHo2xu6virKtAZLTsJFzT -UmRd11MrWCvj59lWzt1/eIMN+ekjH8aXeLOOl54CL+kWp48C+V9BchyKCShZB7uc -imFvjHTtuxziXZQRO7HlcsBOa0WwvDJnRnskdyoD31s4F4jpKEYBJNWTo63v6lUv -bQIDAQAB ------END PUBLIC KEY-----`, 4096, false}, - } - for i, test := range tests { - actual := IsRsaPublicKey(test.rsastr, test.keylen) - if actual != test.expected { - t.Errorf("Expected TestIsRsaPublicKey(%d, %d) to be %v, got %v", i, test.keylen, test.expected, actual) - } - } -} diff --git a/vendor/github.com/asaskevich/govalidator/wercker.yml b/vendor/github.com/asaskevich/govalidator/wercker.yml deleted file mode 100644 index cac7a5fcf..000000000 --- a/vendor/github.com/asaskevich/govalidator/wercker.yml +++ /dev/null @@ -1,15 +0,0 @@ -box: golang -build: - steps: - - setup-go-workspace - - - script: - name: go get - code: | - go version - go get -t ./... - - - script: - name: go test - code: | - go test -race ./... diff --git a/vendor/github.com/containerd/continuity/.travis.yml b/vendor/github.com/containerd/continuity/.travis.yml index 4ddbe28b0..ac6dcf7e2 100644 --- a/vendor/github.com/containerd/continuity/.travis.yml +++ b/vendor/github.com/containerd/continuity/.travis.yml @@ -4,6 +4,8 @@ sudo: required go: - 1.8.x - 1.9.x + - 1.10.x + - 1.x - tip go_import_path: github.com/containerd/continuity diff --git a/vendor/github.com/containerd/continuity/fs/du.go b/vendor/github.com/containerd/continuity/fs/du.go index 26f533315..f8fc9a994 100644 --- a/vendor/github.com/containerd/continuity/fs/du.go +++ b/vendor/github.com/containerd/continuity/fs/du.go @@ -10,8 +10,8 @@ type Usage struct { // DiskUsage counts the number of inodes and disk usage for the resources under // path. -func DiskUsage(roots ...string) (Usage, error) { - return diskUsage(roots...) +func DiskUsage(ctx context.Context, roots ...string) (Usage, error) { + return diskUsage(ctx, roots...) } // DiffUsage counts the numbers of inodes and disk usage in the diff --git a/vendor/github.com/containerd/continuity/fs/du_unix.go b/vendor/github.com/containerd/continuity/fs/du_unix.go index fe3426d27..9f6bc55fd 100644 --- a/vendor/github.com/containerd/continuity/fs/du_unix.go +++ b/vendor/github.com/containerd/continuity/fs/du_unix.go @@ -24,7 +24,7 @@ func newInode(stat *syscall.Stat_t) inode { } } -func diskUsage(roots ...string) (Usage, error) { +func diskUsage(ctx context.Context, roots ...string) (Usage, error) { var ( size int64 @@ -37,6 +37,12 @@ func diskUsage(roots ...string) (Usage, error) { return err } + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + inoKey := newInode(fi.Sys().(*syscall.Stat_t)) if _, ok := inodes[inoKey]; !ok { inodes[inoKey] = struct{}{} diff --git a/vendor/github.com/containerd/continuity/fs/du_windows.go b/vendor/github.com/containerd/continuity/fs/du_windows.go index 3f852fc15..faa443fed 100644 --- a/vendor/github.com/containerd/continuity/fs/du_windows.go +++ b/vendor/github.com/containerd/continuity/fs/du_windows.go @@ -8,7 +8,7 @@ import ( "path/filepath" ) -func diskUsage(roots ...string) (Usage, error) { +func diskUsage(ctx context.Context, roots ...string) (Usage, error) { var ( size int64 ) @@ -21,6 +21,12 @@ func diskUsage(roots ...string) (Usage, error) { return err } + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + size += fi.Size() return nil }); err != nil { diff --git a/vendor/github.com/containerd/continuity/fs/fstest/compare_unix.go b/vendor/github.com/containerd/continuity/fs/fstest/compare_unix.go new file mode 100644 index 000000000..b100a2a8c --- /dev/null +++ b/vendor/github.com/containerd/continuity/fs/fstest/compare_unix.go @@ -0,0 +1,5 @@ +// +build !windows + +package fstest + +var metadataFiles map[string]bool diff --git a/vendor/github.com/containerd/continuity/fs/fstest/compare_windows.go b/vendor/github.com/containerd/continuity/fs/fstest/compare_windows.go new file mode 100644 index 000000000..58f650a54 --- /dev/null +++ b/vendor/github.com/containerd/continuity/fs/fstest/compare_windows.go @@ -0,0 +1,7 @@ +package fstest + +// TODO: Any more metadata files generated by Windows layers? +var metadataFiles = map[string]bool{ + "\\System Volume Information": true, + "\\WcSandboxState": true, +} diff --git a/vendor/github.com/containerd/continuity/syscallx/syscall_unix.go b/vendor/github.com/containerd/continuity/syscallx/syscall_unix.go new file mode 100644 index 000000000..4205d1e82 --- /dev/null +++ b/vendor/github.com/containerd/continuity/syscallx/syscall_unix.go @@ -0,0 +1,10 @@ +// +build !windows + +package syscallx + +import "syscall" + +// Readlink returns the destination of the named symbolic link. +func Readlink(path string, buf []byte) (n int, err error) { + return syscall.Readlink(path, buf) +} diff --git a/vendor/github.com/containerd/continuity/syscallx/syscall_windows.go b/vendor/github.com/containerd/continuity/syscallx/syscall_windows.go new file mode 100644 index 000000000..9637a2875 --- /dev/null +++ b/vendor/github.com/containerd/continuity/syscallx/syscall_windows.go @@ -0,0 +1,96 @@ +package syscallx + +import ( + "syscall" + "unsafe" +) + +type reparseDataBuffer struct { + ReparseTag uint32 + ReparseDataLength uint16 + Reserved uint16 + + // GenericReparseBuffer + reparseBuffer byte +} + +type mountPointReparseBuffer struct { + SubstituteNameOffset uint16 + SubstituteNameLength uint16 + PrintNameOffset uint16 + PrintNameLength uint16 + PathBuffer [1]uint16 +} + +type symbolicLinkReparseBuffer struct { + SubstituteNameOffset uint16 + SubstituteNameLength uint16 + PrintNameOffset uint16 + PrintNameLength uint16 + Flags uint32 + PathBuffer [1]uint16 +} + +const ( + _IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003 + _SYMLINK_FLAG_RELATIVE = 1 +) + +// Readlink returns the destination of the named symbolic link. +func Readlink(path string, buf []byte) (n int, err error) { + fd, err := syscall.CreateFile(syscall.StringToUTF16Ptr(path), syscall.GENERIC_READ, 0, nil, syscall.OPEN_EXISTING, + syscall.FILE_FLAG_OPEN_REPARSE_POINT|syscall.FILE_FLAG_BACKUP_SEMANTICS, 0) + if err != nil { + return -1, err + } + defer syscall.CloseHandle(fd) + + rdbbuf := make([]byte, syscall.MAXIMUM_REPARSE_DATA_BUFFER_SIZE) + var bytesReturned uint32 + err = syscall.DeviceIoControl(fd, syscall.FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil) + if err != nil { + return -1, err + } + + rdb := (*reparseDataBuffer)(unsafe.Pointer(&rdbbuf[0])) + var s string + switch rdb.ReparseTag { + case syscall.IO_REPARSE_TAG_SYMLINK: + data := (*symbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer)) + p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0])) + s = syscall.UTF16ToString(p[data.SubstituteNameOffset/2 : (data.SubstituteNameOffset+data.SubstituteNameLength)/2]) + if data.Flags&_SYMLINK_FLAG_RELATIVE == 0 { + if len(s) >= 4 && s[:4] == `\??\` { + s = s[4:] + switch { + case len(s) >= 2 && s[1] == ':': // \??\C:\foo\bar + // do nothing + case len(s) >= 4 && s[:4] == `UNC\`: // \??\UNC\foo\bar + s = `\\` + s[4:] + default: + // unexpected; do nothing + } + } else { + // unexpected; do nothing + } + } + case _IO_REPARSE_TAG_MOUNT_POINT: + data := (*mountPointReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer)) + p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0])) + s = syscall.UTF16ToString(p[data.SubstituteNameOffset/2 : (data.SubstituteNameOffset+data.SubstituteNameLength)/2]) + if len(s) >= 4 && s[:4] == `\??\` { // \??\C:\foo\bar + if len(s) < 48 || s[:11] != `\??\Volume{` { + s = s[4:] + } + } else { + // unexpected; do nothing + } + default: + // the path is not a symlink or junction but another type of reparse + // point + return -1, syscall.ENOENT + } + n = copy(buf, []byte(s)) + + return n, nil +} diff --git a/vendor/github.com/containerd/continuity/sysx/file_posix.go b/vendor/github.com/containerd/continuity/sysx/file_posix.go new file mode 100644 index 000000000..d0784f819 --- /dev/null +++ b/vendor/github.com/containerd/continuity/sysx/file_posix.go @@ -0,0 +1,112 @@ +package sysx + +import ( + "os" + "path/filepath" + + "github.com/containerd/continuity/syscallx" +) + +// Readlink returns the destination of the named symbolic link. +// If there is an error, it will be of type *PathError. +func Readlink(name string) (string, error) { + for len := 128; ; len *= 2 { + b := make([]byte, len) + n, e := fixCount(syscallx.Readlink(fixLongPath(name), b)) + if e != nil { + return "", &os.PathError{Op: "readlink", Path: name, Err: e} + } + if n < len { + return string(b[0:n]), nil + } + } +} + +// Many functions in package syscall return a count of -1 instead of 0. +// Using fixCount(call()) instead of call() corrects the count. +func fixCount(n int, err error) (int, error) { + if n < 0 { + n = 0 + } + return n, err +} + +// fixLongPath returns the extended-length (\\?\-prefixed) form of +// path when needed, in order to avoid the default 260 character file +// path limit imposed by Windows. If path is not easily converted to +// the extended-length form (for example, if path is a relative path +// or contains .. elements), or is short enough, fixLongPath returns +// path unmodified. +// +// See https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath +func fixLongPath(path string) string { + // Do nothing (and don't allocate) if the path is "short". + // Empirically (at least on the Windows Server 2013 builder), + // the kernel is arbitrarily okay with < 248 bytes. That + // matches what the docs above say: + // "When using an API to create a directory, the specified + // path cannot be so long that you cannot append an 8.3 file + // name (that is, the directory name cannot exceed MAX_PATH + // minus 12)." Since MAX_PATH is 260, 260 - 12 = 248. + // + // The MSDN docs appear to say that a normal path that is 248 bytes long + // will work; empirically the path must be less then 248 bytes long. + if len(path) < 248 { + // Don't fix. (This is how Go 1.7 and earlier worked, + // not automatically generating the \\?\ form) + return path + } + + // The extended form begins with \\?\, as in + // \\?\c:\windows\foo.txt or \\?\UNC\server\share\foo.txt. + // The extended form disables evaluation of . and .. path + // elements and disables the interpretation of / as equivalent + // to \. The conversion here rewrites / to \ and elides + // . elements as well as trailing or duplicate separators. For + // simplicity it avoids the conversion entirely for relative + // paths or paths containing .. elements. For now, + // \\server\share paths are not converted to + // \\?\UNC\server\share paths because the rules for doing so + // are less well-specified. + if len(path) >= 2 && path[:2] == `\\` { + // Don't canonicalize UNC paths. + return path + } + if !filepath.IsAbs(path) { + // Relative path + return path + } + + const prefix = `\\?` + + pathbuf := make([]byte, len(prefix)+len(path)+len(`\`)) + copy(pathbuf, prefix) + n := len(path) + r, w := 0, len(prefix) + for r < n { + switch { + case os.IsPathSeparator(path[r]): + // empty block + r++ + case path[r] == '.' && (r+1 == n || os.IsPathSeparator(path[r+1])): + // /./ + r++ + case r+1 < n && path[r] == '.' && path[r+1] == '.' && (r+2 == n || os.IsPathSeparator(path[r+2])): + // /../ is currently unhandled + return path + default: + pathbuf[w] = '\\' + w++ + for ; r < n && !os.IsPathSeparator(path[r]); r++ { + pathbuf[w] = path[r] + w++ + } + } + } + // A drive's root directory needs a trailing \ + if w == len(`\\?\c:`) { + pathbuf[w] = '\\' + w++ + } + return string(pathbuf[:w]) +} diff --git a/vendor/github.com/docker/go-units/MAINTAINERS b/vendor/github.com/docker/go-units/MAINTAINERS index 477be8b21..9b3b6b101 100644 --- a/vendor/github.com/docker/go-units/MAINTAINERS +++ b/vendor/github.com/docker/go-units/MAINTAINERS @@ -1,6 +1,6 @@ -# go-connections maintainers file +# go-units maintainers file # -# This file describes who runs the docker/go-connections project and how. +# This file describes who runs the docker/go-units project and how. # This is a living document - if you see something out of date or missing, speak up! # # It is structured to be consumable by both humans and programs. @@ -11,7 +11,10 @@ [Org] [Org."Core maintainers"] people = [ - "calavera", + "akihirosuda", + "dnephin", + "thajeztah", + "vdemeester", ] [people] @@ -21,7 +24,23 @@ # in the people section. # ADD YOURSELF HERE IN ALPHABETICAL ORDER - [people.calavera] - Name = "David Calavera" - Email = "david.calavera@gmail.com" - GitHub = "calavera" + + [people.akihirosuda] + Name = "Akihiro Suda" + Email = "suda.akihiro@lab.ntt.co.jp" + GitHub = "AkihiroSuda" + + [people.dnephin] + Name = "Daniel Nephin" + Email = "dnephin@gmail.com" + GitHub = "dnephin" + + [people.thajeztah] + Name = "Sebastiaan van Stijn" + Email = "github@gone.nl" + GitHub = "thaJeztah" + + [people.vdemeester] + Name = "Vincent Demeester" + Email = "vincent@sbr.pm" + GitHub = "vdemeester" \ No newline at end of file diff --git a/vendor/github.com/docker/go-units/size.go b/vendor/github.com/docker/go-units/size.go index 44616c271..85f6ab071 100644 --- a/vendor/github.com/docker/go-units/size.go +++ b/vendor/github.com/docker/go-units/size.go @@ -31,7 +31,7 @@ type unitMap map[string]int64 var ( decimalMap = unitMap{"k": KB, "m": MB, "g": GB, "t": TB, "p": PB} binaryMap = unitMap{"k": KiB, "m": MiB, "g": GiB, "t": TiB, "p": PiB} - sizeRegex = regexp.MustCompile(`^(\d+(\.\d+)*) ?([kKmMgGtTpP])?[bB]?$`) + sizeRegex = regexp.MustCompile(`^(\d+(\.\d+)*) ?([kKmMgGtTpP])?[iI]?[bB]?$`) ) var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} diff --git a/vendor/github.com/docker/go-units/size_test.go b/vendor/github.com/docker/go-units/size_test.go index 8923e5076..ab389ec50 100644 --- a/vendor/github.com/docker/go-units/size_test.go +++ b/vendor/github.com/docker/go-units/size_test.go @@ -116,6 +116,8 @@ func TestRAMInBytes(t *testing.T) { assertSuccessEquals(t, 32*KiB, RAMInBytes, "32K") assertSuccessEquals(t, 32*KiB, RAMInBytes, "32kb") assertSuccessEquals(t, 32*KiB, RAMInBytes, "32Kb") + assertSuccessEquals(t, 32*KiB, RAMInBytes, "32Kib") + assertSuccessEquals(t, 32*KiB, RAMInBytes, "32KIB") assertSuccessEquals(t, 32*MiB, RAMInBytes, "32Mb") assertSuccessEquals(t, 32*GiB, RAMInBytes, "32Gb") assertSuccessEquals(t, 32*TiB, RAMInBytes, "32Tb") diff --git a/vendor/github.com/fnproject/fdk-go/README.md b/vendor/github.com/fnproject/fdk-go/README.md index 88c0c3c7c..8c9255dc0 100644 --- a/vendor/github.com/fnproject/fdk-go/README.md +++ b/vendor/github.com/fnproject/fdk-go/README.md @@ -52,7 +52,7 @@ func myHandler(ctx context.Context, in io.Reader, out io.Writer) { return } - if fnctx.Config["FN_METHOD"] != "PUT" { + if fnctx.Method != "PUT" { fdk.WriteStatus(out, 404) fdk.SetHeader(out, "Content-Type", "application/json") io.WriteString(out, `{"error":"route not found"}`) diff --git a/vendor/github.com/fnproject/fdk-go/fdk.go b/vendor/github.com/fnproject/fdk-go/fdk.go index c653b2072..42e0ed807 100644 --- a/vendor/github.com/fnproject/fdk-go/fdk.go +++ b/vendor/github.com/fnproject/fdk-go/fdk.go @@ -24,23 +24,29 @@ func (f HandlerFunc) Serve(ctx context.Context, in io.Reader, out io.Writer) { func Context(ctx context.Context) *Ctx { utilsCtx := utils.Context(ctx) return &Ctx{ - Header: utilsCtx.Header, - Config: utilsCtx.Config, + Header: utilsCtx.Header, + Config: utilsCtx.Config, + RequestURL: utilsCtx.RequestURL, + Method: utilsCtx.Method, } } func WithContext(ctx context.Context, fnctx *Ctx) context.Context { utilsCtx := &utils.Ctx{ - Header: fnctx.Header, - Config: fnctx.Config, + Header: fnctx.Header, + Config: fnctx.Config, + RequestURL: fnctx.RequestURL, + Method: fnctx.Method, } return utils.WithContext(ctx, utilsCtx) } // Ctx provides access to Config and Headers from fn. type Ctx struct { - Header http.Header - Config map[string]string + Header http.Header + Config map[string]string + RequestURL string + Method string } // AddHeader will add a header on the function response, for hot function diff --git a/vendor/github.com/fnproject/fdk-go/fdk_test.go b/vendor/github.com/fnproject/fdk-go/fdk_test.go index 115d20381..fe7e4b58f 100644 --- a/vendor/github.com/fnproject/fdk-go/fdk_test.go +++ b/vendor/github.com/fnproject/fdk-go/fdk_test.go @@ -15,6 +15,7 @@ import ( "testing" "github.com/fnproject/fdk-go/utils" + "time" ) func echoHTTPHandler(_ context.Context, in io.Reader, out io.Writer) { @@ -55,12 +56,12 @@ func JSONHandler(_ context.Context, in io.Reader, out io.Writer) { Name string `json:"name"` } json.NewDecoder(in).Decode(&person) - if person.Name == "" { person.Name = "world" } body := fmt.Sprintf("Hello %s!\n", person.Name) + SetHeader(out, "Content-Type", "application/json") err := json.NewEncoder(out).Encode(body) if err != nil { fmt.Fprintln(os.Stderr, err.Error()) @@ -80,8 +81,9 @@ func TestJSON(t *testing.T) { Deadline: "2018-01-30T16:52:39.786Z", Protocol: utils.CallRequestHTTP{ Type: "http", - RequestURL: "someURL", + RequestURL: "http://localhost:8080/r/myapp/yodawg", Headers: http.Header{}, + Method: "POST", }, } @@ -151,8 +153,9 @@ func TestJSONOverwriteStatusCodeAndHeaders(t *testing.T) { Deadline: "2018-01-30T16:52:39.786Z", Protocol: utils.CallRequestHTTP{ Type: "json", - RequestURL: "someURL", + RequestURL: "http://localhost:8080/r/myapp/yodawg", Headers: http.Header{}, + Method: "POST", }, } @@ -242,3 +245,78 @@ func HTTPreq(t *testing.T, bod string) io.Reader { } return bytes.NewReader(byts) } + +func setupTestFromRequest(t *testing.T, data interface{}, contentType, nameTest string) { + req := &utils.CloudEventIn{ + CloudEvent: utils.CloudEvent{ + EventID: "someid", + Source: "fn-api", + EventType: "test-type", + EventTypeVersion: "1.0", + EventTime: time.Now(), + ContentType: contentType, + Data: data, + }, + Extensions: utils.CloudEventInExtension{ + Deadline: "2018-01-30T16:52:39.786Z", + Protocol: utils.CallRequestHTTP{ + Type: "http", + RequestURL: "http://localhost:8080/r/myapp/yodawg", + Headers: http.Header{}, + Method: "POST", + }, + }, + } + var in bytes.Buffer + err := json.NewEncoder(&in).Encode(req) + if err != nil { + t.Fatal("Unable to marshal request") + } + t.Log(in.String()) + var out, buf bytes.Buffer + + err = utils.DoCloudEventOnce(HandlerFunc(JSONHandler), utils.BuildCtx(), + &in, &out, &buf, make(http.Header)) + if err != nil { + t.Fatal("should not return error", err) + } + + t.Log(out.String()) + ceOut := &utils.CloudEventOut{} + err = json.NewDecoder(&out).Decode(ceOut) + if err != nil { + t.Fatal(err.Error()) + } + + if ceOut.Extensions.Protocol.StatusCode != 200 { + t.Fatalf("Response code must equal to 200, but have: %v", ceOut.Extensions.Protocol.StatusCode) + } + + var respData string + json.Unmarshal([]byte(ceOut.Data.(string)), &respData) + + if respData != "Hello "+nameTest+"!\n" { + t.Fatalf("Output assertion mismatch. Expected: `Hello %v!\n`. Actual: %v", nameTest, ceOut.Data) + } +} + +func TestCloudEventWithJSONData(t *testing.T) { + data := map[string]string{ + "name": "John", + } + contentType := "application/json" + setupTestFromRequest(t, data, contentType, "John") +} + +func TestCloudEventWithStringData(t *testing.T) { + data := `{"name":"John"}` + contentType := "text/plain" + setupTestFromRequest(t, data, contentType, "John") +} + +func TestCloudEventWithPerfectlyValidJSONValue(t *testing.T) { + // https://tools.ietf.org/html/rfc7159#section-3 + data := false + contentType := "application/json" + setupTestFromRequest(t, data, contentType, "world") +} diff --git a/vendor/github.com/fnproject/fdk-go/utils/cloudevent.go b/vendor/github.com/fnproject/fdk-go/utils/cloudevent.go new file mode 100644 index 000000000..04d3de5c5 --- /dev/null +++ b/vendor/github.com/fnproject/fdk-go/utils/cloudevent.go @@ -0,0 +1,117 @@ +package utils + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "strings" + "time" +) + +type CloudEvent struct { + CloudEventsVersion string `json:"cloudEventsVersion"` + EventID string `json:"eventID"` + Source string `json:"source"` + EventType string `json:"eventType"` + EventTypeVersion string `json:"eventTypeVersion"` + EventTime time.Time `json:"eventTime"` + SchemaURL string `json:"schemaURL"` + ContentType string `json:"contentType"` + Data interface{} `json:"data"` // from docs: the payload is encoded into a media format which is specified by the contentType attribute (e.g. application/json) +} + +type CloudEventInExtension struct { + Protocol CallRequestHTTP `json:"protocol"` + Deadline string `json:"deadline"` +} + +type CloudEventOutExtension struct { + Protocol CallResponseHTTP `json:"protocol"` +} + +type CloudEventIn struct { + CloudEvent + Extensions CloudEventInExtension `json:"extensions"` +} + +type CloudEventOut struct { + CloudEvent + Extensions CloudEventOutExtension `json:"extensions"` +} + +func writeError(ceOut *CloudEventOut, err error) { + ceOut.Extensions.Protocol.StatusCode = http.StatusInternalServerError + ceOut.Data = fmt.Sprintf(`{"error": %v}`, err.Error()) + ceOut.ContentType = "application/json" + ceOut.EventTime = time.Now() +} + +func DoCloudEventOnce(handler Handler, ctx context.Context, in io.Reader, out io.Writer, buf *bytes.Buffer, hdr http.Header) error { + buf.Reset() + ResetHeaders(hdr) + resp := Response{ + Writer: buf, + Status: 200, + Header: hdr, + } + + ceOut := CloudEventOut{ + Extensions: CloudEventOutExtension{ + Protocol: CallResponseHTTP{ + StatusCode: http.StatusOK, + Headers: hdr, + }, + }, + CloudEvent: CloudEvent{ + ContentType: "text/plain", + }, + } + + var ceIn CloudEventIn + err := json.NewDecoder(in).Decode(&ceIn) + if err != nil { + if err == io.EOF { + return err + } + writeError(&ceOut, err) + } else { + SetHeaders(ctx, ceIn.Extensions.Protocol.Headers) + SetRequestURL(ctx, ceIn.Extensions.Protocol.RequestURL) + SetMethod(ctx, ceIn.Extensions.Protocol.Method) + ctx, cancel := CtxWithDeadline(ctx, ceIn.Extensions.Deadline) + defer cancel() + + if ceIn.ContentType == "application/json" { + // TODO this is lame, need to make FDK cloud event native and not io.Reader + err = json.NewEncoder(buf).Encode(ceIn.Data) + in := strings.NewReader(buf.String()) // string is immutable, we need a copy + buf.Reset() + handler.Serve(ctx, in, &resp) + } else { + handler.Serve(ctx, strings.NewReader(ceIn.Data.(string)), &resp) + } + } + + ceOut.EventID = ceIn.EventID + ceOut.EventTime = time.Now() + ceOut.ContentType = ceOut.Extensions.Protocol.Headers.Get("Content-Type") + ceOut.Data = buf.String() + return json.NewEncoder(out).Encode(ceOut) +} + +func DoCloudEvent(handler Handler, ctx context.Context, in io.Reader, out io.Writer) { + var buf bytes.Buffer + hdr := make(http.Header) + + for { + err := DoCloudEventOnce(handler, ctx, in, out, &buf, hdr) + if err != nil { + log.Println(err.Error()) + break + } + } +} diff --git a/vendor/github.com/fnproject/fdk-go/utils/http.go b/vendor/github.com/fnproject/fdk-go/utils/http.go new file mode 100644 index 000000000..e1cd3ce62 --- /dev/null +++ b/vendor/github.com/fnproject/fdk-go/utils/http.go @@ -0,0 +1,62 @@ +package utils + +import ( + "bufio" + "bytes" + "context" + "io" + "io/ioutil" + "net/http" + "strconv" +) + +func GetHTTPResp(buf *bytes.Buffer, fnResp *Response, req *http.Request) http.Response { + + fnResp.Header.Set("Content-Length", strconv.Itoa(buf.Len())) + + hResp := http.Response{ + ProtoMajor: 1, + ProtoMinor: 1, + StatusCode: fnResp.Status, + Request: req, + Body: ioutil.NopCloser(buf), + ContentLength: int64(buf.Len()), + Header: fnResp.Header, + } + + return hResp +} + +func DoHTTPOnce(handler Handler, ctx context.Context, in io.Reader, out io.Writer, buf *bytes.Buffer, hdr http.Header) error { + buf.Reset() + ResetHeaders(hdr) + resp := Response{ + Writer: buf, + Status: 200, + Header: hdr, + } + + req, err := http.ReadRequest(bufio.NewReader(in)) + if err != nil { + // stdin now closed + if err == io.EOF { + return err + } + // TODO it would be nice if we could let the user format this response to their preferred style.. + resp.Status = http.StatusInternalServerError + io.WriteString(resp, err.Error()) + } else { + fnDeadline := Context(ctx).Header.Get("FN_DEADLINE") + ctx, cancel := CtxWithDeadline(ctx, fnDeadline) + defer cancel() + + SetHeaders(ctx, req.Header) + SetRequestURL(ctx, req.URL.String()) + SetMethod(ctx, req.Method) + handler.Serve(ctx, req.Body, &resp) + } + + hResp := GetHTTPResp(buf, &resp, req) + hResp.Write(out) + return nil +} diff --git a/vendor/github.com/fnproject/fdk-go/utils/json.go b/vendor/github.com/fnproject/fdk-go/utils/json.go new file mode 100644 index 000000000..68002cc0b --- /dev/null +++ b/vendor/github.com/fnproject/fdk-go/utils/json.go @@ -0,0 +1,96 @@ +package utils + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" +) + +func DoJSON(handler Handler, ctx context.Context, in io.Reader, out io.Writer) { + var buf bytes.Buffer + hdr := make(http.Header) + + for { + err := DoJSONOnce(handler, ctx, in, out, &buf, hdr) + if err != nil { + break + } + } +} + +type CallRequestHTTP struct { + Type string `json:"type"` + RequestURL string `json:"request_url"` + Method string `json:"method"` + Headers http.Header `json:"headers"` +} + +type JsonIn struct { + CallID string `json:"call_id"` + Deadline string `json:"deadline"` + Body string `json:"body"` + ContentType string `json:"content_type"` + Protocol CallRequestHTTP `json:"protocol"` +} + +type CallResponseHTTP struct { + StatusCode int `json:"status_code,omitempty"` + Headers http.Header `json:"headers,omitempty"` +} + +type JsonOut struct { + Body string `json:"body"` + ContentType string `json:"content_type"` + Protocol CallResponseHTTP `json:"protocol,omitempty"` +} + +func GetJSONResp(buf *bytes.Buffer, fnResp *Response) *JsonOut { + + hResp := &JsonOut{ + Body: buf.String(), + ContentType: "", + Protocol: CallResponseHTTP{ + StatusCode: fnResp.Status, + Headers: fnResp.Header, + }, + } + + return hResp +} + +func DoJSONOnce(handler Handler, ctx context.Context, in io.Reader, out io.Writer, buf *bytes.Buffer, hdr http.Header) error { + buf.Reset() + ResetHeaders(hdr) + resp := Response{ + Writer: buf, + Status: 200, + Header: hdr, + } + + var jsonRequest JsonIn + err := json.NewDecoder(in).Decode(&jsonRequest) + if err != nil { + // stdin now closed + if err == io.EOF { + return err + } + resp.Status = http.StatusInternalServerError + io.WriteString(resp, fmt.Sprintf(`{"error": %v}`, err.Error())) + } else { + + SetHeaders(ctx, jsonRequest.Protocol.Headers) + SetRequestURL(ctx, jsonRequest.Protocol.RequestURL) + SetMethod(ctx, jsonRequest.Protocol.Method) + ctx, cancel := CtxWithDeadline(ctx, jsonRequest.Deadline) + defer cancel() + handler.Serve(ctx, strings.NewReader(jsonRequest.Body), &resp) + } + + jsonResponse := GetJSONResp(buf, &resp) + json.NewEncoder(out).Encode(jsonResponse) + return nil +} diff --git a/vendor/github.com/fnproject/fdk-go/utils/utils.go b/vendor/github.com/fnproject/fdk-go/utils/utils.go index 96910b87a..b73580377 100644 --- a/vendor/github.com/fnproject/fdk-go/utils/utils.go +++ b/vendor/github.com/fnproject/fdk-go/utils/utils.go @@ -1,16 +1,11 @@ package utils import ( - "bufio" "bytes" "context" - "encoding/json" - "fmt" "io" - "io/ioutil" "net/http" "os" - "strconv" "strings" "time" ) @@ -31,8 +26,10 @@ func WithContext(ctx context.Context, fnctx *Ctx) context.Context { // Ctx provides access to Config and Headers from fn. type Ctx struct { - Header http.Header - Config map[string]string + Header http.Header + Config map[string]string + RequestURL string + Method string } type key struct{} @@ -46,6 +43,8 @@ func Do(handler Handler, format string, in io.Reader, out io.Writer) { DoHTTP(handler, ctx, in, out) case "json": DoJSON(handler, ctx, in, out) + case "cloudevent": + DoCloudEvent(handler, ctx, in, out) case "default": DoDefault(handler, ctx, in, out) default: @@ -81,88 +80,6 @@ func DoHTTP(handler Handler, ctx context.Context, in io.Reader, out io.Writer) { } } -func DoJSON(handler Handler, ctx context.Context, in io.Reader, out io.Writer) { - var buf bytes.Buffer - hdr := make(http.Header) - - for { - err := DoJSONOnce(handler, ctx, in, out, &buf, hdr) - if err != nil { - break - } - } -} - -type CallRequestHTTP struct { - Type string `json:"type"` - RequestURL string `json:"request_url"` - Method string `json:"method"` - Headers http.Header `json:"headers"` -} - -type JsonIn struct { - CallID string `json:"call_id"` - Deadline string `json:"deadline"` - Body string `json:"body"` - ContentType string `json:"content_type"` - Protocol CallRequestHTTP `json:"protocol"` -} - -type CallResponseHTTP struct { - StatusCode int `json:"status_code,omitempty"` - Headers http.Header `json:"headers,omitempty"` -} - -type JsonOut struct { - Body string `json:"body"` - ContentType string `json:"content_type"` - Protocol CallResponseHTTP `json:"protocol,omitempty"` -} - -func GetJSONResp(buf *bytes.Buffer, fnResp *Response, req *JsonIn) *JsonOut { - - hResp := &JsonOut{ - Body: buf.String(), - ContentType: "", - Protocol: CallResponseHTTP{ - StatusCode: fnResp.Status, - Headers: fnResp.Header, - }, - } - - return hResp -} - -func DoJSONOnce(handler Handler, ctx context.Context, in io.Reader, out io.Writer, buf *bytes.Buffer, hdr http.Header) error { - buf.Reset() - ResetHeaders(hdr) - resp := Response{ - Writer: buf, - Status: 200, - Header: hdr, - } - - var jsonRequest JsonIn - err := json.NewDecoder(in).Decode(&jsonRequest) - if err != nil { - // stdin now closed - if err == io.EOF { - return err - } - resp.Status = http.StatusInternalServerError - io.WriteString(resp, fmt.Sprintf(`{"error": %v}`, err.Error())) - } else { - SetHeaders(ctx, jsonRequest.Protocol.Headers) - ctx, cancel := CtxWithDeadline(ctx, jsonRequest.Deadline) - defer cancel() - handler.Serve(ctx, strings.NewReader(jsonRequest.Body), &resp) - } - - jsonResponse := GetJSONResp(buf, &resp, &jsonRequest) - json.NewEncoder(out).Encode(jsonResponse) - return nil -} - func CtxWithDeadline(ctx context.Context, fnDeadline string) (context.Context, context.CancelFunc) { t, err := time.Parse(time.RFC3339, fnDeadline) if err == nil { @@ -171,54 +88,6 @@ func CtxWithDeadline(ctx context.Context, fnDeadline string) (context.Context, c return context.WithCancel(ctx) } -func GetHTTPResp(buf *bytes.Buffer, fnResp *Response, req *http.Request) http.Response { - - fnResp.Header.Set("Content-Length", strconv.Itoa(buf.Len())) - - hResp := http.Response{ - ProtoMajor: 1, - ProtoMinor: 1, - StatusCode: fnResp.Status, - Request: req, - Body: ioutil.NopCloser(buf), - ContentLength: int64(buf.Len()), - Header: fnResp.Header, - } - - return hResp -} - -func DoHTTPOnce(handler Handler, ctx context.Context, in io.Reader, out io.Writer, buf *bytes.Buffer, hdr http.Header) error { - buf.Reset() - ResetHeaders(hdr) - resp := Response{ - Writer: buf, - Status: 200, - Header: hdr, - } - - req, err := http.ReadRequest(bufio.NewReader(in)) - if err != nil { - // stdin now closed - if err == io.EOF { - return err - } - // TODO it would be nice if we could let the user format this response to their preferred style.. - resp.Status = http.StatusInternalServerError - io.WriteString(resp, err.Error()) - } else { - fnDeadline := Context(ctx).Header.Get("FN_DEADLINE") - ctx, cancel := CtxWithDeadline(ctx, fnDeadline) - defer cancel() - SetHeaders(ctx, req.Header) - handler.Serve(ctx, req.Body, &resp) - } - - hResp := GetHTTPResp(buf, &resp, req) - hResp.Write(out) - return nil -} - func ResetHeaders(m http.Header) { for k := range m { // compiler optimizes this to 1 instruction now delete(m, k) @@ -258,6 +127,16 @@ func SetHeaders(ctx context.Context, hdr http.Header) { fctx.Header = hdr } +func SetRequestURL(ctx context.Context, requestURL string) { + fctx := ctx.Value(ctxKey).(*Ctx) + fctx.RequestURL = requestURL +} + +func SetMethod(ctx context.Context, method string) { + fctx := ctx.Value(ctxKey).(*Ctx) + fctx.Method = method +} + func BuildCtx() context.Context { ctx := &Ctx{ Config: BuildConfig(), diff --git a/vendor/github.com/fnproject/fn_go/.gitignore b/vendor/github.com/fnproject/fn_go/.gitignore deleted file mode 100644 index a1338d685..000000000 --- a/vendor/github.com/fnproject/fn_go/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.dll -*.so -*.dylib - -# Test binary, build with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 -.glide/ diff --git a/vendor/github.com/fnproject/fn_go/LICENSE b/vendor/github.com/fnproject/fn_go/LICENSE deleted file mode 100644 index 8dada3eda..000000000 --- a/vendor/github.com/fnproject/fn_go/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. diff --git a/vendor/github.com/fnproject/fn_go/VERSION b/vendor/github.com/fnproject/fn_go/VERSION deleted file mode 100644 index 53a75d673..000000000 --- a/vendor/github.com/fnproject/fn_go/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.2.6 diff --git a/vendor/github.com/fnproject/fn_go/client/apps/apps_client.go b/vendor/github.com/fnproject/fn_go/client/apps/apps_client.go deleted file mode 100644 index af2395ba2..000000000 --- a/vendor/github.com/fnproject/fn_go/client/apps/apps_client.go +++ /dev/null @@ -1,180 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package apps - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" -) - -// New creates a new apps API client. -func New(transport runtime.ClientTransport, formats strfmt.Registry) *Client { - return &Client{transport: transport, formats: formats} -} - -/* -Client for apps API -*/ -type Client struct { - transport runtime.ClientTransport - formats strfmt.Registry -} - -/* -DeleteAppsApp deletes an app - -Delete an app. -*/ -func (a *Client) DeleteAppsApp(params *DeleteAppsAppParams) (*DeleteAppsAppOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewDeleteAppsAppParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "DeleteAppsApp", - Method: "DELETE", - PathPattern: "/apps/{app}", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &DeleteAppsAppReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*DeleteAppsAppOK), nil - -} - -/* -GetApps gets all app names - -Get a list of all the apps in the system, returned in alphabetical order. -*/ -func (a *Client) GetApps(params *GetAppsParams) (*GetAppsOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetAppsParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "GetApps", - Method: "GET", - PathPattern: "/apps", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &GetAppsReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*GetAppsOK), nil - -} - -/* -GetAppsApp gets information for a app - -This gives more details about a app, such as statistics. -*/ -func (a *Client) GetAppsApp(params *GetAppsAppParams) (*GetAppsAppOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetAppsAppParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "GetAppsApp", - Method: "GET", - PathPattern: "/apps/{app}", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &GetAppsAppReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*GetAppsAppOK), nil - -} - -/* -PatchAppsApp updates an app - -You can set app level settings here. -*/ -func (a *Client) PatchAppsApp(params *PatchAppsAppParams) (*PatchAppsAppOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewPatchAppsAppParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "PatchAppsApp", - Method: "PATCH", - PathPattern: "/apps/{app}", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &PatchAppsAppReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*PatchAppsAppOK), nil - -} - -/* -PostApps posts new app - -Insert a new app -*/ -func (a *Client) PostApps(params *PostAppsParams) (*PostAppsOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewPostAppsParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "PostApps", - Method: "POST", - PathPattern: "/apps", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &PostAppsReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*PostAppsOK), nil - -} - -// SetTransport changes the transport on the client -func (a *Client) SetTransport(transport runtime.ClientTransport) { - a.transport = transport -} diff --git a/vendor/github.com/fnproject/fn_go/client/apps/delete_apps_app_parameters.go b/vendor/github.com/fnproject/fn_go/client/apps/delete_apps_app_parameters.go deleted file mode 100644 index 27e8ac7b9..000000000 --- a/vendor/github.com/fnproject/fn_go/client/apps/delete_apps_app_parameters.go +++ /dev/null @@ -1,137 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package apps - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - - strfmt "github.com/go-openapi/strfmt" -) - -// NewDeleteAppsAppParams creates a new DeleteAppsAppParams object -// with the default values initialized. -func NewDeleteAppsAppParams() *DeleteAppsAppParams { - var () - return &DeleteAppsAppParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewDeleteAppsAppParamsWithTimeout creates a new DeleteAppsAppParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewDeleteAppsAppParamsWithTimeout(timeout time.Duration) *DeleteAppsAppParams { - var () - return &DeleteAppsAppParams{ - - timeout: timeout, - } -} - -// NewDeleteAppsAppParamsWithContext creates a new DeleteAppsAppParams object -// with the default values initialized, and the ability to set a context for a request -func NewDeleteAppsAppParamsWithContext(ctx context.Context) *DeleteAppsAppParams { - var () - return &DeleteAppsAppParams{ - - Context: ctx, - } -} - -// NewDeleteAppsAppParamsWithHTTPClient creates a new DeleteAppsAppParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewDeleteAppsAppParamsWithHTTPClient(client *http.Client) *DeleteAppsAppParams { - var () - return &DeleteAppsAppParams{ - HTTPClient: client, - } -} - -/*DeleteAppsAppParams contains all the parameters to send to the API endpoint -for the delete apps app operation typically these are written to a http.Request -*/ -type DeleteAppsAppParams struct { - - /*App - Name of the app. - - */ - App string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the delete apps app params -func (o *DeleteAppsAppParams) WithTimeout(timeout time.Duration) *DeleteAppsAppParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the delete apps app params -func (o *DeleteAppsAppParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the delete apps app params -func (o *DeleteAppsAppParams) WithContext(ctx context.Context) *DeleteAppsAppParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the delete apps app params -func (o *DeleteAppsAppParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the delete apps app params -func (o *DeleteAppsAppParams) WithHTTPClient(client *http.Client) *DeleteAppsAppParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the delete apps app params -func (o *DeleteAppsAppParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithApp adds the app to the delete apps app params -func (o *DeleteAppsAppParams) WithApp(app string) *DeleteAppsAppParams { - o.SetApp(app) - return o -} - -// SetApp adds the app to the delete apps app params -func (o *DeleteAppsAppParams) SetApp(app string) { - o.App = app -} - -// WriteToRequest writes these params to a swagger request -func (o *DeleteAppsAppParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param app - if err := r.SetPathParam("app", o.App); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/apps/delete_apps_app_responses.go b/vendor/github.com/fnproject/fn_go/client/apps/delete_apps_app_responses.go deleted file mode 100644 index ee7aa24f7..000000000 --- a/vendor/github.com/fnproject/fn_go/client/apps/delete_apps_app_responses.go +++ /dev/null @@ -1,140 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package apps - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// DeleteAppsAppReader is a Reader for the DeleteAppsApp structure. -type DeleteAppsAppReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *DeleteAppsAppReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewDeleteAppsAppOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - case 404: - result := NewDeleteAppsAppNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - default: - result := NewDeleteAppsAppDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewDeleteAppsAppOK creates a DeleteAppsAppOK with default headers values -func NewDeleteAppsAppOK() *DeleteAppsAppOK { - return &DeleteAppsAppOK{} -} - -/*DeleteAppsAppOK handles this case with default header values. - -Apps successfully deleted. -*/ -type DeleteAppsAppOK struct { -} - -func (o *DeleteAppsAppOK) Error() string { - return fmt.Sprintf("[DELETE /apps/{app}][%d] deleteAppsAppOK ", 200) -} - -func (o *DeleteAppsAppOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} - -// NewDeleteAppsAppNotFound creates a DeleteAppsAppNotFound with default headers values -func NewDeleteAppsAppNotFound() *DeleteAppsAppNotFound { - return &DeleteAppsAppNotFound{} -} - -/*DeleteAppsAppNotFound handles this case with default header values. - -App does not exist. -*/ -type DeleteAppsAppNotFound struct { - Payload *models.Error -} - -func (o *DeleteAppsAppNotFound) Error() string { - return fmt.Sprintf("[DELETE /apps/{app}][%d] deleteAppsAppNotFound %+v", 404, o.Payload) -} - -func (o *DeleteAppsAppNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewDeleteAppsAppDefault creates a DeleteAppsAppDefault with default headers values -func NewDeleteAppsAppDefault(code int) *DeleteAppsAppDefault { - return &DeleteAppsAppDefault{ - _statusCode: code, - } -} - -/*DeleteAppsAppDefault handles this case with default header values. - -Unexpected error -*/ -type DeleteAppsAppDefault struct { - _statusCode int - - Payload *models.Error -} - -// Code gets the status code for the delete apps app default response -func (o *DeleteAppsAppDefault) Code() int { - return o._statusCode -} - -func (o *DeleteAppsAppDefault) Error() string { - return fmt.Sprintf("[DELETE /apps/{app}][%d] DeleteAppsApp default %+v", o._statusCode, o.Payload) -} - -func (o *DeleteAppsAppDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/apps/get_apps_app_parameters.go b/vendor/github.com/fnproject/fn_go/client/apps/get_apps_app_parameters.go deleted file mode 100644 index 3e3ff3ae8..000000000 --- a/vendor/github.com/fnproject/fn_go/client/apps/get_apps_app_parameters.go +++ /dev/null @@ -1,137 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package apps - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - - strfmt "github.com/go-openapi/strfmt" -) - -// NewGetAppsAppParams creates a new GetAppsAppParams object -// with the default values initialized. -func NewGetAppsAppParams() *GetAppsAppParams { - var () - return &GetAppsAppParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewGetAppsAppParamsWithTimeout creates a new GetAppsAppParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewGetAppsAppParamsWithTimeout(timeout time.Duration) *GetAppsAppParams { - var () - return &GetAppsAppParams{ - - timeout: timeout, - } -} - -// NewGetAppsAppParamsWithContext creates a new GetAppsAppParams object -// with the default values initialized, and the ability to set a context for a request -func NewGetAppsAppParamsWithContext(ctx context.Context) *GetAppsAppParams { - var () - return &GetAppsAppParams{ - - Context: ctx, - } -} - -// NewGetAppsAppParamsWithHTTPClient creates a new GetAppsAppParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewGetAppsAppParamsWithHTTPClient(client *http.Client) *GetAppsAppParams { - var () - return &GetAppsAppParams{ - HTTPClient: client, - } -} - -/*GetAppsAppParams contains all the parameters to send to the API endpoint -for the get apps app operation typically these are written to a http.Request -*/ -type GetAppsAppParams struct { - - /*App - name of the app. - - */ - App string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the get apps app params -func (o *GetAppsAppParams) WithTimeout(timeout time.Duration) *GetAppsAppParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get apps app params -func (o *GetAppsAppParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get apps app params -func (o *GetAppsAppParams) WithContext(ctx context.Context) *GetAppsAppParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get apps app params -func (o *GetAppsAppParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get apps app params -func (o *GetAppsAppParams) WithHTTPClient(client *http.Client) *GetAppsAppParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get apps app params -func (o *GetAppsAppParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithApp adds the app to the get apps app params -func (o *GetAppsAppParams) WithApp(app string) *GetAppsAppParams { - o.SetApp(app) - return o -} - -// SetApp adds the app to the get apps app params -func (o *GetAppsAppParams) SetApp(app string) { - o.App = app -} - -// WriteToRequest writes these params to a swagger request -func (o *GetAppsAppParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param app - if err := r.SetPathParam("app", o.App); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/apps/get_apps_app_responses.go b/vendor/github.com/fnproject/fn_go/client/apps/get_apps_app_responses.go deleted file mode 100644 index 9c50d6bd5..000000000 --- a/vendor/github.com/fnproject/fn_go/client/apps/get_apps_app_responses.go +++ /dev/null @@ -1,148 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package apps - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// GetAppsAppReader is a Reader for the GetAppsApp structure. -type GetAppsAppReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetAppsAppReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewGetAppsAppOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - case 404: - result := NewGetAppsAppNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - default: - result := NewGetAppsAppDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewGetAppsAppOK creates a GetAppsAppOK with default headers values -func NewGetAppsAppOK() *GetAppsAppOK { - return &GetAppsAppOK{} -} - -/*GetAppsAppOK handles this case with default header values. - -App details and stats. -*/ -type GetAppsAppOK struct { - Payload *models.AppWrapper -} - -func (o *GetAppsAppOK) Error() string { - return fmt.Sprintf("[GET /apps/{app}][%d] getAppsAppOK %+v", 200, o.Payload) -} - -func (o *GetAppsAppOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.AppWrapper) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetAppsAppNotFound creates a GetAppsAppNotFound with default headers values -func NewGetAppsAppNotFound() *GetAppsAppNotFound { - return &GetAppsAppNotFound{} -} - -/*GetAppsAppNotFound handles this case with default header values. - -App does not exist. -*/ -type GetAppsAppNotFound struct { - Payload *models.Error -} - -func (o *GetAppsAppNotFound) Error() string { - return fmt.Sprintf("[GET /apps/{app}][%d] getAppsAppNotFound %+v", 404, o.Payload) -} - -func (o *GetAppsAppNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetAppsAppDefault creates a GetAppsAppDefault with default headers values -func NewGetAppsAppDefault(code int) *GetAppsAppDefault { - return &GetAppsAppDefault{ - _statusCode: code, - } -} - -/*GetAppsAppDefault handles this case with default header values. - -Unexpected error -*/ -type GetAppsAppDefault struct { - _statusCode int - - Payload *models.Error -} - -// Code gets the status code for the get apps app default response -func (o *GetAppsAppDefault) Code() int { - return o._statusCode -} - -func (o *GetAppsAppDefault) Error() string { - return fmt.Sprintf("[GET /apps/{app}][%d] GetAppsApp default %+v", o._statusCode, o.Payload) -} - -func (o *GetAppsAppDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/apps/get_apps_parameters.go b/vendor/github.com/fnproject/fn_go/client/apps/get_apps_parameters.go deleted file mode 100644 index 8ed16bac5..000000000 --- a/vendor/github.com/fnproject/fn_go/client/apps/get_apps_parameters.go +++ /dev/null @@ -1,181 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package apps - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/swag" - - strfmt "github.com/go-openapi/strfmt" -) - -// NewGetAppsParams creates a new GetAppsParams object -// with the default values initialized. -func NewGetAppsParams() *GetAppsParams { - var () - return &GetAppsParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewGetAppsParamsWithTimeout creates a new GetAppsParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewGetAppsParamsWithTimeout(timeout time.Duration) *GetAppsParams { - var () - return &GetAppsParams{ - - timeout: timeout, - } -} - -// NewGetAppsParamsWithContext creates a new GetAppsParams object -// with the default values initialized, and the ability to set a context for a request -func NewGetAppsParamsWithContext(ctx context.Context) *GetAppsParams { - var () - return &GetAppsParams{ - - Context: ctx, - } -} - -// NewGetAppsParamsWithHTTPClient creates a new GetAppsParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewGetAppsParamsWithHTTPClient(client *http.Client) *GetAppsParams { - var () - return &GetAppsParams{ - HTTPClient: client, - } -} - -/*GetAppsParams contains all the parameters to send to the API endpoint -for the get apps operation typically these are written to a http.Request -*/ -type GetAppsParams struct { - - /*Cursor - Cursor from previous response.next_cursor to begin results after, if any. - - */ - Cursor *string - /*PerPage - Number of results to return, defaults to 30. Max of 100. - - */ - PerPage *int64 - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the get apps params -func (o *GetAppsParams) WithTimeout(timeout time.Duration) *GetAppsParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get apps params -func (o *GetAppsParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get apps params -func (o *GetAppsParams) WithContext(ctx context.Context) *GetAppsParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get apps params -func (o *GetAppsParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get apps params -func (o *GetAppsParams) WithHTTPClient(client *http.Client) *GetAppsParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get apps params -func (o *GetAppsParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithCursor adds the cursor to the get apps params -func (o *GetAppsParams) WithCursor(cursor *string) *GetAppsParams { - o.SetCursor(cursor) - return o -} - -// SetCursor adds the cursor to the get apps params -func (o *GetAppsParams) SetCursor(cursor *string) { - o.Cursor = cursor -} - -// WithPerPage adds the perPage to the get apps params -func (o *GetAppsParams) WithPerPage(perPage *int64) *GetAppsParams { - o.SetPerPage(perPage) - return o -} - -// SetPerPage adds the perPage to the get apps params -func (o *GetAppsParams) SetPerPage(perPage *int64) { - o.PerPage = perPage -} - -// WriteToRequest writes these params to a swagger request -func (o *GetAppsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - if o.Cursor != nil { - - // query param cursor - var qrCursor string - if o.Cursor != nil { - qrCursor = *o.Cursor - } - qCursor := qrCursor - if qCursor != "" { - if err := r.SetQueryParam("cursor", qCursor); err != nil { - return err - } - } - - } - - if o.PerPage != nil { - - // query param per_page - var qrPerPage int64 - if o.PerPage != nil { - qrPerPage = *o.PerPage - } - qPerPage := swag.FormatInt64(qrPerPage) - if qPerPage != "" { - if err := r.SetQueryParam("per_page", qPerPage); err != nil { - return err - } - } - - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/apps/get_apps_responses.go b/vendor/github.com/fnproject/fn_go/client/apps/get_apps_responses.go deleted file mode 100644 index ab2a07248..000000000 --- a/vendor/github.com/fnproject/fn_go/client/apps/get_apps_responses.go +++ /dev/null @@ -1,112 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package apps - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// GetAppsReader is a Reader for the GetApps structure. -type GetAppsReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetAppsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewGetAppsOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - default: - result := NewGetAppsDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewGetAppsOK creates a GetAppsOK with default headers values -func NewGetAppsOK() *GetAppsOK { - return &GetAppsOK{} -} - -/*GetAppsOK handles this case with default header values. - -List of apps. -*/ -type GetAppsOK struct { - Payload *models.AppsWrapper -} - -func (o *GetAppsOK) Error() string { - return fmt.Sprintf("[GET /apps][%d] getAppsOK %+v", 200, o.Payload) -} - -func (o *GetAppsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.AppsWrapper) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetAppsDefault creates a GetAppsDefault with default headers values -func NewGetAppsDefault(code int) *GetAppsDefault { - return &GetAppsDefault{ - _statusCode: code, - } -} - -/*GetAppsDefault handles this case with default header values. - -Unexpected error -*/ -type GetAppsDefault struct { - _statusCode int - - Payload *models.Error -} - -// Code gets the status code for the get apps default response -func (o *GetAppsDefault) Code() int { - return o._statusCode -} - -func (o *GetAppsDefault) Error() string { - return fmt.Sprintf("[GET /apps][%d] GetApps default %+v", o._statusCode, o.Payload) -} - -func (o *GetAppsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/apps/patch_apps_app_parameters.go b/vendor/github.com/fnproject/fn_go/client/apps/patch_apps_app_parameters.go deleted file mode 100644 index 391f5155f..000000000 --- a/vendor/github.com/fnproject/fn_go/client/apps/patch_apps_app_parameters.go +++ /dev/null @@ -1,161 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package apps - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// NewPatchAppsAppParams creates a new PatchAppsAppParams object -// with the default values initialized. -func NewPatchAppsAppParams() *PatchAppsAppParams { - var () - return &PatchAppsAppParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewPatchAppsAppParamsWithTimeout creates a new PatchAppsAppParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewPatchAppsAppParamsWithTimeout(timeout time.Duration) *PatchAppsAppParams { - var () - return &PatchAppsAppParams{ - - timeout: timeout, - } -} - -// NewPatchAppsAppParamsWithContext creates a new PatchAppsAppParams object -// with the default values initialized, and the ability to set a context for a request -func NewPatchAppsAppParamsWithContext(ctx context.Context) *PatchAppsAppParams { - var () - return &PatchAppsAppParams{ - - Context: ctx, - } -} - -// NewPatchAppsAppParamsWithHTTPClient creates a new PatchAppsAppParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewPatchAppsAppParamsWithHTTPClient(client *http.Client) *PatchAppsAppParams { - var () - return &PatchAppsAppParams{ - HTTPClient: client, - } -} - -/*PatchAppsAppParams contains all the parameters to send to the API endpoint -for the patch apps app operation typically these are written to a http.Request -*/ -type PatchAppsAppParams struct { - - /*App - name of the app. - - */ - App string - /*Body - App to post. - - */ - Body *models.AppWrapper - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the patch apps app params -func (o *PatchAppsAppParams) WithTimeout(timeout time.Duration) *PatchAppsAppParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the patch apps app params -func (o *PatchAppsAppParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the patch apps app params -func (o *PatchAppsAppParams) WithContext(ctx context.Context) *PatchAppsAppParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the patch apps app params -func (o *PatchAppsAppParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the patch apps app params -func (o *PatchAppsAppParams) WithHTTPClient(client *http.Client) *PatchAppsAppParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the patch apps app params -func (o *PatchAppsAppParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithApp adds the app to the patch apps app params -func (o *PatchAppsAppParams) WithApp(app string) *PatchAppsAppParams { - o.SetApp(app) - return o -} - -// SetApp adds the app to the patch apps app params -func (o *PatchAppsAppParams) SetApp(app string) { - o.App = app -} - -// WithBody adds the body to the patch apps app params -func (o *PatchAppsAppParams) WithBody(body *models.AppWrapper) *PatchAppsAppParams { - o.SetBody(body) - return o -} - -// SetBody adds the body to the patch apps app params -func (o *PatchAppsAppParams) SetBody(body *models.AppWrapper) { - o.Body = body -} - -// WriteToRequest writes these params to a swagger request -func (o *PatchAppsAppParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param app - if err := r.SetPathParam("app", o.App); err != nil { - return err - } - - if o.Body != nil { - if err := r.SetBodyParam(o.Body); err != nil { - return err - } - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/apps/patch_apps_app_responses.go b/vendor/github.com/fnproject/fn_go/client/apps/patch_apps_app_responses.go deleted file mode 100644 index a8684863f..000000000 --- a/vendor/github.com/fnproject/fn_go/client/apps/patch_apps_app_responses.go +++ /dev/null @@ -1,184 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package apps - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// PatchAppsAppReader is a Reader for the PatchAppsApp structure. -type PatchAppsAppReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *PatchAppsAppReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewPatchAppsAppOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - case 400: - result := NewPatchAppsAppBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - case 404: - result := NewPatchAppsAppNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - default: - result := NewPatchAppsAppDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewPatchAppsAppOK creates a PatchAppsAppOK with default headers values -func NewPatchAppsAppOK() *PatchAppsAppOK { - return &PatchAppsAppOK{} -} - -/*PatchAppsAppOK handles this case with default header values. - -App details and stats. -*/ -type PatchAppsAppOK struct { - Payload *models.AppWrapper -} - -func (o *PatchAppsAppOK) Error() string { - return fmt.Sprintf("[PATCH /apps/{app}][%d] patchAppsAppOK %+v", 200, o.Payload) -} - -func (o *PatchAppsAppOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.AppWrapper) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPatchAppsAppBadRequest creates a PatchAppsAppBadRequest with default headers values -func NewPatchAppsAppBadRequest() *PatchAppsAppBadRequest { - return &PatchAppsAppBadRequest{} -} - -/*PatchAppsAppBadRequest handles this case with default header values. - -Parameters are missing or invalid. -*/ -type PatchAppsAppBadRequest struct { - Payload *models.Error -} - -func (o *PatchAppsAppBadRequest) Error() string { - return fmt.Sprintf("[PATCH /apps/{app}][%d] patchAppsAppBadRequest %+v", 400, o.Payload) -} - -func (o *PatchAppsAppBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPatchAppsAppNotFound creates a PatchAppsAppNotFound with default headers values -func NewPatchAppsAppNotFound() *PatchAppsAppNotFound { - return &PatchAppsAppNotFound{} -} - -/*PatchAppsAppNotFound handles this case with default header values. - -App does not exist. -*/ -type PatchAppsAppNotFound struct { - Payload *models.Error -} - -func (o *PatchAppsAppNotFound) Error() string { - return fmt.Sprintf("[PATCH /apps/{app}][%d] patchAppsAppNotFound %+v", 404, o.Payload) -} - -func (o *PatchAppsAppNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPatchAppsAppDefault creates a PatchAppsAppDefault with default headers values -func NewPatchAppsAppDefault(code int) *PatchAppsAppDefault { - return &PatchAppsAppDefault{ - _statusCode: code, - } -} - -/*PatchAppsAppDefault handles this case with default header values. - -Unexpected error -*/ -type PatchAppsAppDefault struct { - _statusCode int - - Payload *models.Error -} - -// Code gets the status code for the patch apps app default response -func (o *PatchAppsAppDefault) Code() int { - return o._statusCode -} - -func (o *PatchAppsAppDefault) Error() string { - return fmt.Sprintf("[PATCH /apps/{app}][%d] PatchAppsApp default %+v", o._statusCode, o.Payload) -} - -func (o *PatchAppsAppDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/apps/post_apps_parameters.go b/vendor/github.com/fnproject/fn_go/client/apps/post_apps_parameters.go deleted file mode 100644 index c5e37d51e..000000000 --- a/vendor/github.com/fnproject/fn_go/client/apps/post_apps_parameters.go +++ /dev/null @@ -1,140 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package apps - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// NewPostAppsParams creates a new PostAppsParams object -// with the default values initialized. -func NewPostAppsParams() *PostAppsParams { - var () - return &PostAppsParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewPostAppsParamsWithTimeout creates a new PostAppsParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewPostAppsParamsWithTimeout(timeout time.Duration) *PostAppsParams { - var () - return &PostAppsParams{ - - timeout: timeout, - } -} - -// NewPostAppsParamsWithContext creates a new PostAppsParams object -// with the default values initialized, and the ability to set a context for a request -func NewPostAppsParamsWithContext(ctx context.Context) *PostAppsParams { - var () - return &PostAppsParams{ - - Context: ctx, - } -} - -// NewPostAppsParamsWithHTTPClient creates a new PostAppsParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewPostAppsParamsWithHTTPClient(client *http.Client) *PostAppsParams { - var () - return &PostAppsParams{ - HTTPClient: client, - } -} - -/*PostAppsParams contains all the parameters to send to the API endpoint -for the post apps operation typically these are written to a http.Request -*/ -type PostAppsParams struct { - - /*Body - App to post. - - */ - Body *models.AppWrapper - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the post apps params -func (o *PostAppsParams) WithTimeout(timeout time.Duration) *PostAppsParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the post apps params -func (o *PostAppsParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the post apps params -func (o *PostAppsParams) WithContext(ctx context.Context) *PostAppsParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the post apps params -func (o *PostAppsParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the post apps params -func (o *PostAppsParams) WithHTTPClient(client *http.Client) *PostAppsParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the post apps params -func (o *PostAppsParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithBody adds the body to the post apps params -func (o *PostAppsParams) WithBody(body *models.AppWrapper) *PostAppsParams { - o.SetBody(body) - return o -} - -// SetBody adds the body to the post apps params -func (o *PostAppsParams) SetBody(body *models.AppWrapper) { - o.Body = body -} - -// WriteToRequest writes these params to a swagger request -func (o *PostAppsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - if o.Body != nil { - if err := r.SetBodyParam(o.Body); err != nil { - return err - } - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/apps/post_apps_responses.go b/vendor/github.com/fnproject/fn_go/client/apps/post_apps_responses.go deleted file mode 100644 index c05d49086..000000000 --- a/vendor/github.com/fnproject/fn_go/client/apps/post_apps_responses.go +++ /dev/null @@ -1,184 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package apps - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// PostAppsReader is a Reader for the PostApps structure. -type PostAppsReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *PostAppsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewPostAppsOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - case 400: - result := NewPostAppsBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - case 409: - result := NewPostAppsConflict() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - default: - result := NewPostAppsDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewPostAppsOK creates a PostAppsOK with default headers values -func NewPostAppsOK() *PostAppsOK { - return &PostAppsOK{} -} - -/*PostAppsOK handles this case with default header values. - -App details and stats. -*/ -type PostAppsOK struct { - Payload *models.AppWrapper -} - -func (o *PostAppsOK) Error() string { - return fmt.Sprintf("[POST /apps][%d] postAppsOK %+v", 200, o.Payload) -} - -func (o *PostAppsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.AppWrapper) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPostAppsBadRequest creates a PostAppsBadRequest with default headers values -func NewPostAppsBadRequest() *PostAppsBadRequest { - return &PostAppsBadRequest{} -} - -/*PostAppsBadRequest handles this case with default header values. - -Parameters are missing or invalid. -*/ -type PostAppsBadRequest struct { - Payload *models.Error -} - -func (o *PostAppsBadRequest) Error() string { - return fmt.Sprintf("[POST /apps][%d] postAppsBadRequest %+v", 400, o.Payload) -} - -func (o *PostAppsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPostAppsConflict creates a PostAppsConflict with default headers values -func NewPostAppsConflict() *PostAppsConflict { - return &PostAppsConflict{} -} - -/*PostAppsConflict handles this case with default header values. - -App already exists. -*/ -type PostAppsConflict struct { - Payload *models.Error -} - -func (o *PostAppsConflict) Error() string { - return fmt.Sprintf("[POST /apps][%d] postAppsConflict %+v", 409, o.Payload) -} - -func (o *PostAppsConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPostAppsDefault creates a PostAppsDefault with default headers values -func NewPostAppsDefault(code int) *PostAppsDefault { - return &PostAppsDefault{ - _statusCode: code, - } -} - -/*PostAppsDefault handles this case with default header values. - -Unexpected error -*/ -type PostAppsDefault struct { - _statusCode int - - Payload *models.Error -} - -// Code gets the status code for the post apps default response -func (o *PostAppsDefault) Code() int { - return o._statusCode -} - -func (o *PostAppsDefault) Error() string { - return fmt.Sprintf("[POST /apps][%d] PostApps default %+v", o._statusCode, o.Payload) -} - -func (o *PostAppsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/call/call_client.go b/vendor/github.com/fnproject/fn_go/client/call/call_client.go deleted file mode 100644 index 613fc161a..000000000 --- a/vendor/github.com/fnproject/fn_go/client/call/call_client.go +++ /dev/null @@ -1,90 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package call - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" -) - -// New creates a new call API client. -func New(transport runtime.ClientTransport, formats strfmt.Registry) *Client { - return &Client{transport: transport, formats: formats} -} - -/* -Client for call API -*/ -type Client struct { - transport runtime.ClientTransport - formats strfmt.Registry -} - -/* -GetAppsAppCalls gets app bound calls - -Get app-bound calls can filter to route-bound calls, results returned in created_at, descending order (newest first). -*/ -func (a *Client) GetAppsAppCalls(params *GetAppsAppCallsParams) (*GetAppsAppCallsOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetAppsAppCallsParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "GetAppsAppCalls", - Method: "GET", - PathPattern: "/apps/{app}/calls", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &GetAppsAppCallsReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*GetAppsAppCallsOK), nil - -} - -/* -GetAppsAppCallsCall gets call information - -Get call information -*/ -func (a *Client) GetAppsAppCallsCall(params *GetAppsAppCallsCallParams) (*GetAppsAppCallsCallOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetAppsAppCallsCallParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "GetAppsAppCallsCall", - Method: "GET", - PathPattern: "/apps/{app}/calls/{call}", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &GetAppsAppCallsCallReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*GetAppsAppCallsCallOK), nil - -} - -// SetTransport changes the transport on the client -func (a *Client) SetTransport(transport runtime.ClientTransport) { - a.transport = transport -} diff --git a/vendor/github.com/fnproject/fn_go/client/call/get_apps_app_calls_call_parameters.go b/vendor/github.com/fnproject/fn_go/client/call/get_apps_app_calls_call_parameters.go deleted file mode 100644 index f5e6c84c8..000000000 --- a/vendor/github.com/fnproject/fn_go/client/call/get_apps_app_calls_call_parameters.go +++ /dev/null @@ -1,158 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package call - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - - strfmt "github.com/go-openapi/strfmt" -) - -// NewGetAppsAppCallsCallParams creates a new GetAppsAppCallsCallParams object -// with the default values initialized. -func NewGetAppsAppCallsCallParams() *GetAppsAppCallsCallParams { - var () - return &GetAppsAppCallsCallParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewGetAppsAppCallsCallParamsWithTimeout creates a new GetAppsAppCallsCallParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewGetAppsAppCallsCallParamsWithTimeout(timeout time.Duration) *GetAppsAppCallsCallParams { - var () - return &GetAppsAppCallsCallParams{ - - timeout: timeout, - } -} - -// NewGetAppsAppCallsCallParamsWithContext creates a new GetAppsAppCallsCallParams object -// with the default values initialized, and the ability to set a context for a request -func NewGetAppsAppCallsCallParamsWithContext(ctx context.Context) *GetAppsAppCallsCallParams { - var () - return &GetAppsAppCallsCallParams{ - - Context: ctx, - } -} - -// NewGetAppsAppCallsCallParamsWithHTTPClient creates a new GetAppsAppCallsCallParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewGetAppsAppCallsCallParamsWithHTTPClient(client *http.Client) *GetAppsAppCallsCallParams { - var () - return &GetAppsAppCallsCallParams{ - HTTPClient: client, - } -} - -/*GetAppsAppCallsCallParams contains all the parameters to send to the API endpoint -for the get apps app calls call operation typically these are written to a http.Request -*/ -type GetAppsAppCallsCallParams struct { - - /*App - app name - - */ - App string - /*Call - Call ID. - - */ - Call string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the get apps app calls call params -func (o *GetAppsAppCallsCallParams) WithTimeout(timeout time.Duration) *GetAppsAppCallsCallParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get apps app calls call params -func (o *GetAppsAppCallsCallParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get apps app calls call params -func (o *GetAppsAppCallsCallParams) WithContext(ctx context.Context) *GetAppsAppCallsCallParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get apps app calls call params -func (o *GetAppsAppCallsCallParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get apps app calls call params -func (o *GetAppsAppCallsCallParams) WithHTTPClient(client *http.Client) *GetAppsAppCallsCallParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get apps app calls call params -func (o *GetAppsAppCallsCallParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithApp adds the app to the get apps app calls call params -func (o *GetAppsAppCallsCallParams) WithApp(app string) *GetAppsAppCallsCallParams { - o.SetApp(app) - return o -} - -// SetApp adds the app to the get apps app calls call params -func (o *GetAppsAppCallsCallParams) SetApp(app string) { - o.App = app -} - -// WithCall adds the call to the get apps app calls call params -func (o *GetAppsAppCallsCallParams) WithCall(call string) *GetAppsAppCallsCallParams { - o.SetCall(call) - return o -} - -// SetCall adds the call to the get apps app calls call params -func (o *GetAppsAppCallsCallParams) SetCall(call string) { - o.Call = call -} - -// WriteToRequest writes these params to a swagger request -func (o *GetAppsAppCallsCallParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param app - if err := r.SetPathParam("app", o.App); err != nil { - return err - } - - // path param call - if err := r.SetPathParam("call", o.Call); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/call/get_apps_app_calls_call_responses.go b/vendor/github.com/fnproject/fn_go/client/call/get_apps_app_calls_call_responses.go deleted file mode 100644 index 01d4e302d..000000000 --- a/vendor/github.com/fnproject/fn_go/client/call/get_apps_app_calls_call_responses.go +++ /dev/null @@ -1,103 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package call - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// GetAppsAppCallsCallReader is a Reader for the GetAppsAppCallsCall structure. -type GetAppsAppCallsCallReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetAppsAppCallsCallReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewGetAppsAppCallsCallOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - case 404: - result := NewGetAppsAppCallsCallNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - default: - return nil, runtime.NewAPIError("unknown error", response, response.Code()) - } -} - -// NewGetAppsAppCallsCallOK creates a GetAppsAppCallsCallOK with default headers values -func NewGetAppsAppCallsCallOK() *GetAppsAppCallsCallOK { - return &GetAppsAppCallsCallOK{} -} - -/*GetAppsAppCallsCallOK handles this case with default header values. - -Call found -*/ -type GetAppsAppCallsCallOK struct { - Payload *models.CallWrapper -} - -func (o *GetAppsAppCallsCallOK) Error() string { - return fmt.Sprintf("[GET /apps/{app}/calls/{call}][%d] getAppsAppCallsCallOK %+v", 200, o.Payload) -} - -func (o *GetAppsAppCallsCallOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.CallWrapper) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetAppsAppCallsCallNotFound creates a GetAppsAppCallsCallNotFound with default headers values -func NewGetAppsAppCallsCallNotFound() *GetAppsAppCallsCallNotFound { - return &GetAppsAppCallsCallNotFound{} -} - -/*GetAppsAppCallsCallNotFound handles this case with default header values. - -Call not found. -*/ -type GetAppsAppCallsCallNotFound struct { - Payload *models.Error -} - -func (o *GetAppsAppCallsCallNotFound) Error() string { - return fmt.Sprintf("[GET /apps/{app}/calls/{call}][%d] getAppsAppCallsCallNotFound %+v", 404, o.Payload) -} - -func (o *GetAppsAppCallsCallNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/call/get_apps_app_calls_parameters.go b/vendor/github.com/fnproject/fn_go/client/call/get_apps_app_calls_parameters.go deleted file mode 100644 index 0ce363a10..000000000 --- a/vendor/github.com/fnproject/fn_go/client/call/get_apps_app_calls_parameters.go +++ /dev/null @@ -1,298 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package call - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/swag" - - strfmt "github.com/go-openapi/strfmt" -) - -// NewGetAppsAppCallsParams creates a new GetAppsAppCallsParams object -// with the default values initialized. -func NewGetAppsAppCallsParams() *GetAppsAppCallsParams { - var () - return &GetAppsAppCallsParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewGetAppsAppCallsParamsWithTimeout creates a new GetAppsAppCallsParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewGetAppsAppCallsParamsWithTimeout(timeout time.Duration) *GetAppsAppCallsParams { - var () - return &GetAppsAppCallsParams{ - - timeout: timeout, - } -} - -// NewGetAppsAppCallsParamsWithContext creates a new GetAppsAppCallsParams object -// with the default values initialized, and the ability to set a context for a request -func NewGetAppsAppCallsParamsWithContext(ctx context.Context) *GetAppsAppCallsParams { - var () - return &GetAppsAppCallsParams{ - - Context: ctx, - } -} - -// NewGetAppsAppCallsParamsWithHTTPClient creates a new GetAppsAppCallsParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewGetAppsAppCallsParamsWithHTTPClient(client *http.Client) *GetAppsAppCallsParams { - var () - return &GetAppsAppCallsParams{ - HTTPClient: client, - } -} - -/*GetAppsAppCallsParams contains all the parameters to send to the API endpoint -for the get apps app calls operation typically these are written to a http.Request -*/ -type GetAppsAppCallsParams struct { - - /*App - App name. - - */ - App string - /*Cursor - Cursor from previous response.next_cursor to begin results after, if any. - - */ - Cursor *string - /*FromTime - Unix timestamp in seconds, of call.created_at to begin the results at, default 0. - - */ - FromTime *int64 - /*Path - Route path to match, exact. - - */ - Path *string - /*PerPage - Number of results to return, defaults to 30. Max of 100. - - */ - PerPage *int64 - /*ToTime - Unix timestamp in seconds, of call.created_at to end the results at, defaults to latest. - - */ - ToTime *int64 - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the get apps app calls params -func (o *GetAppsAppCallsParams) WithTimeout(timeout time.Duration) *GetAppsAppCallsParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get apps app calls params -func (o *GetAppsAppCallsParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get apps app calls params -func (o *GetAppsAppCallsParams) WithContext(ctx context.Context) *GetAppsAppCallsParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get apps app calls params -func (o *GetAppsAppCallsParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get apps app calls params -func (o *GetAppsAppCallsParams) WithHTTPClient(client *http.Client) *GetAppsAppCallsParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get apps app calls params -func (o *GetAppsAppCallsParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithApp adds the app to the get apps app calls params -func (o *GetAppsAppCallsParams) WithApp(app string) *GetAppsAppCallsParams { - o.SetApp(app) - return o -} - -// SetApp adds the app to the get apps app calls params -func (o *GetAppsAppCallsParams) SetApp(app string) { - o.App = app -} - -// WithCursor adds the cursor to the get apps app calls params -func (o *GetAppsAppCallsParams) WithCursor(cursor *string) *GetAppsAppCallsParams { - o.SetCursor(cursor) - return o -} - -// SetCursor adds the cursor to the get apps app calls params -func (o *GetAppsAppCallsParams) SetCursor(cursor *string) { - o.Cursor = cursor -} - -// WithFromTime adds the fromTime to the get apps app calls params -func (o *GetAppsAppCallsParams) WithFromTime(fromTime *int64) *GetAppsAppCallsParams { - o.SetFromTime(fromTime) - return o -} - -// SetFromTime adds the fromTime to the get apps app calls params -func (o *GetAppsAppCallsParams) SetFromTime(fromTime *int64) { - o.FromTime = fromTime -} - -// WithPath adds the path to the get apps app calls params -func (o *GetAppsAppCallsParams) WithPath(path *string) *GetAppsAppCallsParams { - o.SetPath(path) - return o -} - -// SetPath adds the path to the get apps app calls params -func (o *GetAppsAppCallsParams) SetPath(path *string) { - o.Path = path -} - -// WithPerPage adds the perPage to the get apps app calls params -func (o *GetAppsAppCallsParams) WithPerPage(perPage *int64) *GetAppsAppCallsParams { - o.SetPerPage(perPage) - return o -} - -// SetPerPage adds the perPage to the get apps app calls params -func (o *GetAppsAppCallsParams) SetPerPage(perPage *int64) { - o.PerPage = perPage -} - -// WithToTime adds the toTime to the get apps app calls params -func (o *GetAppsAppCallsParams) WithToTime(toTime *int64) *GetAppsAppCallsParams { - o.SetToTime(toTime) - return o -} - -// SetToTime adds the toTime to the get apps app calls params -func (o *GetAppsAppCallsParams) SetToTime(toTime *int64) { - o.ToTime = toTime -} - -// WriteToRequest writes these params to a swagger request -func (o *GetAppsAppCallsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param app - if err := r.SetPathParam("app", o.App); err != nil { - return err - } - - if o.Cursor != nil { - - // query param cursor - var qrCursor string - if o.Cursor != nil { - qrCursor = *o.Cursor - } - qCursor := qrCursor - if qCursor != "" { - if err := r.SetQueryParam("cursor", qCursor); err != nil { - return err - } - } - - } - - if o.FromTime != nil { - - // query param from_time - var qrFromTime int64 - if o.FromTime != nil { - qrFromTime = *o.FromTime - } - qFromTime := swag.FormatInt64(qrFromTime) - if qFromTime != "" { - if err := r.SetQueryParam("from_time", qFromTime); err != nil { - return err - } - } - - } - - if o.Path != nil { - - // query param path - var qrPath string - if o.Path != nil { - qrPath = *o.Path - } - qPath := qrPath - if qPath != "" { - if err := r.SetQueryParam("path", qPath); err != nil { - return err - } - } - - } - - if o.PerPage != nil { - - // query param per_page - var qrPerPage int64 - if o.PerPage != nil { - qrPerPage = *o.PerPage - } - qPerPage := swag.FormatInt64(qrPerPage) - if qPerPage != "" { - if err := r.SetQueryParam("per_page", qPerPage); err != nil { - return err - } - } - - } - - if o.ToTime != nil { - - // query param to_time - var qrToTime int64 - if o.ToTime != nil { - qrToTime = *o.ToTime - } - qToTime := swag.FormatInt64(qrToTime) - if qToTime != "" { - if err := r.SetQueryParam("to_time", qToTime); err != nil { - return err - } - } - - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/call/get_apps_app_calls_responses.go b/vendor/github.com/fnproject/fn_go/client/call/get_apps_app_calls_responses.go deleted file mode 100644 index c8153b1ac..000000000 --- a/vendor/github.com/fnproject/fn_go/client/call/get_apps_app_calls_responses.go +++ /dev/null @@ -1,103 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package call - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// GetAppsAppCallsReader is a Reader for the GetAppsAppCalls structure. -type GetAppsAppCallsReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetAppsAppCallsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewGetAppsAppCallsOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - case 404: - result := NewGetAppsAppCallsNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - default: - return nil, runtime.NewAPIError("unknown error", response, response.Code()) - } -} - -// NewGetAppsAppCallsOK creates a GetAppsAppCallsOK with default headers values -func NewGetAppsAppCallsOK() *GetAppsAppCallsOK { - return &GetAppsAppCallsOK{} -} - -/*GetAppsAppCallsOK handles this case with default header values. - -Calls found -*/ -type GetAppsAppCallsOK struct { - Payload *models.CallsWrapper -} - -func (o *GetAppsAppCallsOK) Error() string { - return fmt.Sprintf("[GET /apps/{app}/calls][%d] getAppsAppCallsOK %+v", 200, o.Payload) -} - -func (o *GetAppsAppCallsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.CallsWrapper) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetAppsAppCallsNotFound creates a GetAppsAppCallsNotFound with default headers values -func NewGetAppsAppCallsNotFound() *GetAppsAppCallsNotFound { - return &GetAppsAppCallsNotFound{} -} - -/*GetAppsAppCallsNotFound handles this case with default header values. - -Calls not found. -*/ -type GetAppsAppCallsNotFound struct { - Payload *models.Error -} - -func (o *GetAppsAppCallsNotFound) Error() string { - return fmt.Sprintf("[GET /apps/{app}/calls][%d] getAppsAppCallsNotFound %+v", 404, o.Payload) -} - -func (o *GetAppsAppCallsNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/fn_client.go b/vendor/github.com/fnproject/fn_go/client/fn_client.go deleted file mode 100644 index f643d9da7..000000000 --- a/vendor/github.com/fnproject/fn_go/client/fn_client.go +++ /dev/null @@ -1,138 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package client - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "github.com/go-openapi/runtime" - httptransport "github.com/go-openapi/runtime/client" - - strfmt "github.com/go-openapi/strfmt" - - "github.com/fnproject/fn_go/client/apps" - "github.com/fnproject/fn_go/client/call" - "github.com/fnproject/fn_go/client/operations" - "github.com/fnproject/fn_go/client/routes" -) - -// Default fn HTTP client. -var Default = NewHTTPClient(nil) - -const ( - // DefaultHost is the default Host - // found in Meta (info) section of spec file - DefaultHost string = "127.0.0.1:8080" - // DefaultBasePath is the default BasePath - // found in Meta (info) section of spec file - DefaultBasePath string = "/v1" -) - -// DefaultSchemes are the default schemes found in Meta (info) section of spec file -var DefaultSchemes = []string{"http", "https"} - -// NewHTTPClient creates a new fn HTTP client. -func NewHTTPClient(formats strfmt.Registry) *Fn { - return NewHTTPClientWithConfig(formats, nil) -} - -// NewHTTPClientWithConfig creates a new fn HTTP client, -// using a customizable transport config. -func NewHTTPClientWithConfig(formats strfmt.Registry, cfg *TransportConfig) *Fn { - // ensure nullable parameters have default - if cfg == nil { - cfg = DefaultTransportConfig() - } - - // create transport and client - transport := httptransport.New(cfg.Host, cfg.BasePath, cfg.Schemes) - return New(transport, formats) -} - -// New creates a new fn client -func New(transport runtime.ClientTransport, formats strfmt.Registry) *Fn { - // ensure nullable parameters have default - if formats == nil { - formats = strfmt.Default - } - - cli := new(Fn) - cli.Transport = transport - - cli.Apps = apps.New(transport, formats) - - cli.Call = call.New(transport, formats) - - cli.Operations = operations.New(transport, formats) - - cli.Routes = routes.New(transport, formats) - - return cli -} - -// DefaultTransportConfig creates a TransportConfig with the -// default settings taken from the meta section of the spec file. -func DefaultTransportConfig() *TransportConfig { - return &TransportConfig{ - Host: DefaultHost, - BasePath: DefaultBasePath, - Schemes: DefaultSchemes, - } -} - -// TransportConfig contains the transport related info, -// found in the meta section of the spec file. -type TransportConfig struct { - Host string - BasePath string - Schemes []string -} - -// WithHost overrides the default host, -// provided by the meta section of the spec file. -func (cfg *TransportConfig) WithHost(host string) *TransportConfig { - cfg.Host = host - return cfg -} - -// WithBasePath overrides the default basePath, -// provided by the meta section of the spec file. -func (cfg *TransportConfig) WithBasePath(basePath string) *TransportConfig { - cfg.BasePath = basePath - return cfg -} - -// WithSchemes overrides the default schemes, -// provided by the meta section of the spec file. -func (cfg *TransportConfig) WithSchemes(schemes []string) *TransportConfig { - cfg.Schemes = schemes - return cfg -} - -// Fn is a client for fn -type Fn struct { - Apps *apps.Client - - Call *call.Client - - Operations *operations.Client - - Routes *routes.Client - - Transport runtime.ClientTransport -} - -// SetTransport changes the transport on the client and all its subresources -func (c *Fn) SetTransport(transport runtime.ClientTransport) { - c.Transport = transport - - c.Apps.SetTransport(transport) - - c.Call.SetTransport(transport) - - c.Operations.SetTransport(transport) - - c.Routes.SetTransport(transport) - -} diff --git a/vendor/github.com/fnproject/fn_go/client/operations/delete_apps_app_calls_call_log_parameters.go b/vendor/github.com/fnproject/fn_go/client/operations/delete_apps_app_calls_call_log_parameters.go deleted file mode 100644 index 83b929965..000000000 --- a/vendor/github.com/fnproject/fn_go/client/operations/delete_apps_app_calls_call_log_parameters.go +++ /dev/null @@ -1,158 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package operations - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - - strfmt "github.com/go-openapi/strfmt" -) - -// NewDeleteAppsAppCallsCallLogParams creates a new DeleteAppsAppCallsCallLogParams object -// with the default values initialized. -func NewDeleteAppsAppCallsCallLogParams() *DeleteAppsAppCallsCallLogParams { - var () - return &DeleteAppsAppCallsCallLogParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewDeleteAppsAppCallsCallLogParamsWithTimeout creates a new DeleteAppsAppCallsCallLogParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewDeleteAppsAppCallsCallLogParamsWithTimeout(timeout time.Duration) *DeleteAppsAppCallsCallLogParams { - var () - return &DeleteAppsAppCallsCallLogParams{ - - timeout: timeout, - } -} - -// NewDeleteAppsAppCallsCallLogParamsWithContext creates a new DeleteAppsAppCallsCallLogParams object -// with the default values initialized, and the ability to set a context for a request -func NewDeleteAppsAppCallsCallLogParamsWithContext(ctx context.Context) *DeleteAppsAppCallsCallLogParams { - var () - return &DeleteAppsAppCallsCallLogParams{ - - Context: ctx, - } -} - -// NewDeleteAppsAppCallsCallLogParamsWithHTTPClient creates a new DeleteAppsAppCallsCallLogParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewDeleteAppsAppCallsCallLogParamsWithHTTPClient(client *http.Client) *DeleteAppsAppCallsCallLogParams { - var () - return &DeleteAppsAppCallsCallLogParams{ - HTTPClient: client, - } -} - -/*DeleteAppsAppCallsCallLogParams contains all the parameters to send to the API endpoint -for the delete apps app calls call log operation typically these are written to a http.Request -*/ -type DeleteAppsAppCallsCallLogParams struct { - - /*App - App name. - - */ - App string - /*Call - Call ID. - - */ - Call string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the delete apps app calls call log params -func (o *DeleteAppsAppCallsCallLogParams) WithTimeout(timeout time.Duration) *DeleteAppsAppCallsCallLogParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the delete apps app calls call log params -func (o *DeleteAppsAppCallsCallLogParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the delete apps app calls call log params -func (o *DeleteAppsAppCallsCallLogParams) WithContext(ctx context.Context) *DeleteAppsAppCallsCallLogParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the delete apps app calls call log params -func (o *DeleteAppsAppCallsCallLogParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the delete apps app calls call log params -func (o *DeleteAppsAppCallsCallLogParams) WithHTTPClient(client *http.Client) *DeleteAppsAppCallsCallLogParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the delete apps app calls call log params -func (o *DeleteAppsAppCallsCallLogParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithApp adds the app to the delete apps app calls call log params -func (o *DeleteAppsAppCallsCallLogParams) WithApp(app string) *DeleteAppsAppCallsCallLogParams { - o.SetApp(app) - return o -} - -// SetApp adds the app to the delete apps app calls call log params -func (o *DeleteAppsAppCallsCallLogParams) SetApp(app string) { - o.App = app -} - -// WithCall adds the call to the delete apps app calls call log params -func (o *DeleteAppsAppCallsCallLogParams) WithCall(call string) *DeleteAppsAppCallsCallLogParams { - o.SetCall(call) - return o -} - -// SetCall adds the call to the delete apps app calls call log params -func (o *DeleteAppsAppCallsCallLogParams) SetCall(call string) { - o.Call = call -} - -// WriteToRequest writes these params to a swagger request -func (o *DeleteAppsAppCallsCallLogParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param app - if err := r.SetPathParam("app", o.App); err != nil { - return err - } - - // path param call - if err := r.SetPathParam("call", o.Call); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/operations/delete_apps_app_calls_call_log_responses.go b/vendor/github.com/fnproject/fn_go/client/operations/delete_apps_app_calls_call_log_responses.go deleted file mode 100644 index aa234a4fb..000000000 --- a/vendor/github.com/fnproject/fn_go/client/operations/delete_apps_app_calls_call_log_responses.go +++ /dev/null @@ -1,140 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package operations - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - "github.com/fnproject/fn_go/models" -) - -// DeleteAppsAppCallsCallLogReader is a Reader for the DeleteAppsAppCallsCallLog structure. -type DeleteAppsAppCallsCallLogReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *DeleteAppsAppCallsCallLogReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 202: - result := NewDeleteAppsAppCallsCallLogAccepted() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - case 404: - result := NewDeleteAppsAppCallsCallLogNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - default: - result := NewDeleteAppsAppCallsCallLogDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewDeleteAppsAppCallsCallLogAccepted creates a DeleteAppsAppCallsCallLogAccepted with default headers values -func NewDeleteAppsAppCallsCallLogAccepted() *DeleteAppsAppCallsCallLogAccepted { - return &DeleteAppsAppCallsCallLogAccepted{} -} - -/*DeleteAppsAppCallsCallLogAccepted handles this case with default header values. - -Log delete request accepted -*/ -type DeleteAppsAppCallsCallLogAccepted struct { -} - -func (o *DeleteAppsAppCallsCallLogAccepted) Error() string { - return fmt.Sprintf("[DELETE /apps/{app}/calls/{call}/log][%d] deleteAppsAppCallsCallLogAccepted ", 202) -} - -func (o *DeleteAppsAppCallsCallLogAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} - -// NewDeleteAppsAppCallsCallLogNotFound creates a DeleteAppsAppCallsCallLogNotFound with default headers values -func NewDeleteAppsAppCallsCallLogNotFound() *DeleteAppsAppCallsCallLogNotFound { - return &DeleteAppsAppCallsCallLogNotFound{} -} - -/*DeleteAppsAppCallsCallLogNotFound handles this case with default header values. - -Does not exist. -*/ -type DeleteAppsAppCallsCallLogNotFound struct { - Payload *models.Error -} - -func (o *DeleteAppsAppCallsCallLogNotFound) Error() string { - return fmt.Sprintf("[DELETE /apps/{app}/calls/{call}/log][%d] deleteAppsAppCallsCallLogNotFound %+v", 404, o.Payload) -} - -func (o *DeleteAppsAppCallsCallLogNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewDeleteAppsAppCallsCallLogDefault creates a DeleteAppsAppCallsCallLogDefault with default headers values -func NewDeleteAppsAppCallsCallLogDefault(code int) *DeleteAppsAppCallsCallLogDefault { - return &DeleteAppsAppCallsCallLogDefault{ - _statusCode: code, - } -} - -/*DeleteAppsAppCallsCallLogDefault handles this case with default header values. - -Unexpected error -*/ -type DeleteAppsAppCallsCallLogDefault struct { - _statusCode int - - Payload *models.Error -} - -// Code gets the status code for the delete apps app calls call log default response -func (o *DeleteAppsAppCallsCallLogDefault) Code() int { - return o._statusCode -} - -func (o *DeleteAppsAppCallsCallLogDefault) Error() string { - return fmt.Sprintf("[DELETE /apps/{app}/calls/{call}/log][%d] DeleteAppsAppCallsCallLog default %+v", o._statusCode, o.Payload) -} - -func (o *DeleteAppsAppCallsCallLogDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/operations/get_apps_app_calls_call_log_parameters.go b/vendor/github.com/fnproject/fn_go/client/operations/get_apps_app_calls_call_log_parameters.go deleted file mode 100644 index a5cbff4cb..000000000 --- a/vendor/github.com/fnproject/fn_go/client/operations/get_apps_app_calls_call_log_parameters.go +++ /dev/null @@ -1,158 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package operations - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - - strfmt "github.com/go-openapi/strfmt" -) - -// NewGetAppsAppCallsCallLogParams creates a new GetAppsAppCallsCallLogParams object -// with the default values initialized. -func NewGetAppsAppCallsCallLogParams() *GetAppsAppCallsCallLogParams { - var () - return &GetAppsAppCallsCallLogParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewGetAppsAppCallsCallLogParamsWithTimeout creates a new GetAppsAppCallsCallLogParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewGetAppsAppCallsCallLogParamsWithTimeout(timeout time.Duration) *GetAppsAppCallsCallLogParams { - var () - return &GetAppsAppCallsCallLogParams{ - - timeout: timeout, - } -} - -// NewGetAppsAppCallsCallLogParamsWithContext creates a new GetAppsAppCallsCallLogParams object -// with the default values initialized, and the ability to set a context for a request -func NewGetAppsAppCallsCallLogParamsWithContext(ctx context.Context) *GetAppsAppCallsCallLogParams { - var () - return &GetAppsAppCallsCallLogParams{ - - Context: ctx, - } -} - -// NewGetAppsAppCallsCallLogParamsWithHTTPClient creates a new GetAppsAppCallsCallLogParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewGetAppsAppCallsCallLogParamsWithHTTPClient(client *http.Client) *GetAppsAppCallsCallLogParams { - var () - return &GetAppsAppCallsCallLogParams{ - HTTPClient: client, - } -} - -/*GetAppsAppCallsCallLogParams contains all the parameters to send to the API endpoint -for the get apps app calls call log operation typically these are written to a http.Request -*/ -type GetAppsAppCallsCallLogParams struct { - - /*App - App Name - - */ - App string - /*Call - Call ID. - - */ - Call string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the get apps app calls call log params -func (o *GetAppsAppCallsCallLogParams) WithTimeout(timeout time.Duration) *GetAppsAppCallsCallLogParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get apps app calls call log params -func (o *GetAppsAppCallsCallLogParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get apps app calls call log params -func (o *GetAppsAppCallsCallLogParams) WithContext(ctx context.Context) *GetAppsAppCallsCallLogParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get apps app calls call log params -func (o *GetAppsAppCallsCallLogParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get apps app calls call log params -func (o *GetAppsAppCallsCallLogParams) WithHTTPClient(client *http.Client) *GetAppsAppCallsCallLogParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get apps app calls call log params -func (o *GetAppsAppCallsCallLogParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithApp adds the app to the get apps app calls call log params -func (o *GetAppsAppCallsCallLogParams) WithApp(app string) *GetAppsAppCallsCallLogParams { - o.SetApp(app) - return o -} - -// SetApp adds the app to the get apps app calls call log params -func (o *GetAppsAppCallsCallLogParams) SetApp(app string) { - o.App = app -} - -// WithCall adds the call to the get apps app calls call log params -func (o *GetAppsAppCallsCallLogParams) WithCall(call string) *GetAppsAppCallsCallLogParams { - o.SetCall(call) - return o -} - -// SetCall adds the call to the get apps app calls call log params -func (o *GetAppsAppCallsCallLogParams) SetCall(call string) { - o.Call = call -} - -// WriteToRequest writes these params to a swagger request -func (o *GetAppsAppCallsCallLogParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param app - if err := r.SetPathParam("app", o.App); err != nil { - return err - } - - // path param call - if err := r.SetPathParam("call", o.Call); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/operations/get_apps_app_calls_call_log_responses.go b/vendor/github.com/fnproject/fn_go/client/operations/get_apps_app_calls_call_log_responses.go deleted file mode 100644 index f1c96f9ad..000000000 --- a/vendor/github.com/fnproject/fn_go/client/operations/get_apps_app_calls_call_log_responses.go +++ /dev/null @@ -1,103 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package operations - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// GetAppsAppCallsCallLogReader is a Reader for the GetAppsAppCallsCallLog structure. -type GetAppsAppCallsCallLogReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetAppsAppCallsCallLogReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewGetAppsAppCallsCallLogOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - case 404: - result := NewGetAppsAppCallsCallLogNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - default: - return nil, runtime.NewAPIError("unknown error", response, response.Code()) - } -} - -// NewGetAppsAppCallsCallLogOK creates a GetAppsAppCallsCallLogOK with default headers values -func NewGetAppsAppCallsCallLogOK() *GetAppsAppCallsCallLogOK { - return &GetAppsAppCallsCallLogOK{} -} - -/*GetAppsAppCallsCallLogOK handles this case with default header values. - -Log found -*/ -type GetAppsAppCallsCallLogOK struct { - Payload *models.LogWrapper -} - -func (o *GetAppsAppCallsCallLogOK) Error() string { - return fmt.Sprintf("[GET /apps/{app}/calls/{call}/log][%d] getAppsAppCallsCallLogOK %+v", 200, o.Payload) -} - -func (o *GetAppsAppCallsCallLogOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.LogWrapper) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetAppsAppCallsCallLogNotFound creates a GetAppsAppCallsCallLogNotFound with default headers values -func NewGetAppsAppCallsCallLogNotFound() *GetAppsAppCallsCallLogNotFound { - return &GetAppsAppCallsCallLogNotFound{} -} - -/*GetAppsAppCallsCallLogNotFound handles this case with default header values. - -Log not found. -*/ -type GetAppsAppCallsCallLogNotFound struct { - Payload *models.Error -} - -func (o *GetAppsAppCallsCallLogNotFound) Error() string { - return fmt.Sprintf("[GET /apps/{app}/calls/{call}/log][%d] getAppsAppCallsCallLogNotFound %+v", 404, o.Payload) -} - -func (o *GetAppsAppCallsCallLogNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/operations/operations_client.go b/vendor/github.com/fnproject/fn_go/client/operations/operations_client.go deleted file mode 100644 index 56923b5ab..000000000 --- a/vendor/github.com/fnproject/fn_go/client/operations/operations_client.go +++ /dev/null @@ -1,60 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package operations - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" -) - -// New creates a new operations API client. -func New(transport runtime.ClientTransport, formats strfmt.Registry) *Client { - return &Client{transport: transport, formats: formats} -} - -/* -Client for operations API -*/ -type Client struct { - transport runtime.ClientTransport - formats strfmt.Registry -} - -/* -GetAppsAppCallsCallLog gets call logs - -Get call logs -*/ -func (a *Client) GetAppsAppCallsCallLog(params *GetAppsAppCallsCallLogParams) (*GetAppsAppCallsCallLogOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetAppsAppCallsCallLogParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "GetAppsAppCallsCallLog", - Method: "GET", - PathPattern: "/apps/{app}/calls/{call}/log", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &GetAppsAppCallsCallLogReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*GetAppsAppCallsCallLogOK), nil - -} - -// SetTransport changes the transport on the client -func (a *Client) SetTransport(transport runtime.ClientTransport) { - a.transport = transport -} diff --git a/vendor/github.com/fnproject/fn_go/client/routes/delete_apps_app_routes_route_parameters.go b/vendor/github.com/fnproject/fn_go/client/routes/delete_apps_app_routes_route_parameters.go deleted file mode 100644 index 824aa05e1..000000000 --- a/vendor/github.com/fnproject/fn_go/client/routes/delete_apps_app_routes_route_parameters.go +++ /dev/null @@ -1,158 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package routes - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - - strfmt "github.com/go-openapi/strfmt" -) - -// NewDeleteAppsAppRoutesRouteParams creates a new DeleteAppsAppRoutesRouteParams object -// with the default values initialized. -func NewDeleteAppsAppRoutesRouteParams() *DeleteAppsAppRoutesRouteParams { - var () - return &DeleteAppsAppRoutesRouteParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewDeleteAppsAppRoutesRouteParamsWithTimeout creates a new DeleteAppsAppRoutesRouteParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewDeleteAppsAppRoutesRouteParamsWithTimeout(timeout time.Duration) *DeleteAppsAppRoutesRouteParams { - var () - return &DeleteAppsAppRoutesRouteParams{ - - timeout: timeout, - } -} - -// NewDeleteAppsAppRoutesRouteParamsWithContext creates a new DeleteAppsAppRoutesRouteParams object -// with the default values initialized, and the ability to set a context for a request -func NewDeleteAppsAppRoutesRouteParamsWithContext(ctx context.Context) *DeleteAppsAppRoutesRouteParams { - var () - return &DeleteAppsAppRoutesRouteParams{ - - Context: ctx, - } -} - -// NewDeleteAppsAppRoutesRouteParamsWithHTTPClient creates a new DeleteAppsAppRoutesRouteParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewDeleteAppsAppRoutesRouteParamsWithHTTPClient(client *http.Client) *DeleteAppsAppRoutesRouteParams { - var () - return &DeleteAppsAppRoutesRouteParams{ - HTTPClient: client, - } -} - -/*DeleteAppsAppRoutesRouteParams contains all the parameters to send to the API endpoint -for the delete apps app routes route operation typically these are written to a http.Request -*/ -type DeleteAppsAppRoutesRouteParams struct { - - /*App - Name of app for this set of routes. - - */ - App string - /*Route - Route name - - */ - Route string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the delete apps app routes route params -func (o *DeleteAppsAppRoutesRouteParams) WithTimeout(timeout time.Duration) *DeleteAppsAppRoutesRouteParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the delete apps app routes route params -func (o *DeleteAppsAppRoutesRouteParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the delete apps app routes route params -func (o *DeleteAppsAppRoutesRouteParams) WithContext(ctx context.Context) *DeleteAppsAppRoutesRouteParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the delete apps app routes route params -func (o *DeleteAppsAppRoutesRouteParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the delete apps app routes route params -func (o *DeleteAppsAppRoutesRouteParams) WithHTTPClient(client *http.Client) *DeleteAppsAppRoutesRouteParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the delete apps app routes route params -func (o *DeleteAppsAppRoutesRouteParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithApp adds the app to the delete apps app routes route params -func (o *DeleteAppsAppRoutesRouteParams) WithApp(app string) *DeleteAppsAppRoutesRouteParams { - o.SetApp(app) - return o -} - -// SetApp adds the app to the delete apps app routes route params -func (o *DeleteAppsAppRoutesRouteParams) SetApp(app string) { - o.App = app -} - -// WithRoute adds the route to the delete apps app routes route params -func (o *DeleteAppsAppRoutesRouteParams) WithRoute(route string) *DeleteAppsAppRoutesRouteParams { - o.SetRoute(route) - return o -} - -// SetRoute adds the route to the delete apps app routes route params -func (o *DeleteAppsAppRoutesRouteParams) SetRoute(route string) { - o.Route = route -} - -// WriteToRequest writes these params to a swagger request -func (o *DeleteAppsAppRoutesRouteParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param app - if err := r.SetPathParam("app", o.App); err != nil { - return err - } - - // path param route - if err := r.SetPathParam("route", o.Route); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/routes/delete_apps_app_routes_route_responses.go b/vendor/github.com/fnproject/fn_go/client/routes/delete_apps_app_routes_route_responses.go deleted file mode 100644 index 4b09aab90..000000000 --- a/vendor/github.com/fnproject/fn_go/client/routes/delete_apps_app_routes_route_responses.go +++ /dev/null @@ -1,140 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package routes - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// DeleteAppsAppRoutesRouteReader is a Reader for the DeleteAppsAppRoutesRoute structure. -type DeleteAppsAppRoutesRouteReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *DeleteAppsAppRoutesRouteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewDeleteAppsAppRoutesRouteOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - case 404: - result := NewDeleteAppsAppRoutesRouteNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - default: - result := NewDeleteAppsAppRoutesRouteDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewDeleteAppsAppRoutesRouteOK creates a DeleteAppsAppRoutesRouteOK with default headers values -func NewDeleteAppsAppRoutesRouteOK() *DeleteAppsAppRoutesRouteOK { - return &DeleteAppsAppRoutesRouteOK{} -} - -/*DeleteAppsAppRoutesRouteOK handles this case with default header values. - -Route successfully deleted. -*/ -type DeleteAppsAppRoutesRouteOK struct { -} - -func (o *DeleteAppsAppRoutesRouteOK) Error() string { - return fmt.Sprintf("[DELETE /apps/{app}/routes/{route}][%d] deleteAppsAppRoutesRouteOK ", 200) -} - -func (o *DeleteAppsAppRoutesRouteOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} - -// NewDeleteAppsAppRoutesRouteNotFound creates a DeleteAppsAppRoutesRouteNotFound with default headers values -func NewDeleteAppsAppRoutesRouteNotFound() *DeleteAppsAppRoutesRouteNotFound { - return &DeleteAppsAppRoutesRouteNotFound{} -} - -/*DeleteAppsAppRoutesRouteNotFound handles this case with default header values. - -Route does not exist. -*/ -type DeleteAppsAppRoutesRouteNotFound struct { - Payload *models.Error -} - -func (o *DeleteAppsAppRoutesRouteNotFound) Error() string { - return fmt.Sprintf("[DELETE /apps/{app}/routes/{route}][%d] deleteAppsAppRoutesRouteNotFound %+v", 404, o.Payload) -} - -func (o *DeleteAppsAppRoutesRouteNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewDeleteAppsAppRoutesRouteDefault creates a DeleteAppsAppRoutesRouteDefault with default headers values -func NewDeleteAppsAppRoutesRouteDefault(code int) *DeleteAppsAppRoutesRouteDefault { - return &DeleteAppsAppRoutesRouteDefault{ - _statusCode: code, - } -} - -/*DeleteAppsAppRoutesRouteDefault handles this case with default header values. - -Unexpected error -*/ -type DeleteAppsAppRoutesRouteDefault struct { - _statusCode int - - Payload *models.Error -} - -// Code gets the status code for the delete apps app routes route default response -func (o *DeleteAppsAppRoutesRouteDefault) Code() int { - return o._statusCode -} - -func (o *DeleteAppsAppRoutesRouteDefault) Error() string { - return fmt.Sprintf("[DELETE /apps/{app}/routes/{route}][%d] DeleteAppsAppRoutesRoute default %+v", o._statusCode, o.Payload) -} - -func (o *DeleteAppsAppRoutesRouteDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/routes/get_apps_app_routes_parameters.go b/vendor/github.com/fnproject/fn_go/client/routes/get_apps_app_routes_parameters.go deleted file mode 100644 index 2a1c6221a..000000000 --- a/vendor/github.com/fnproject/fn_go/client/routes/get_apps_app_routes_parameters.go +++ /dev/null @@ -1,234 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package routes - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/swag" - - strfmt "github.com/go-openapi/strfmt" -) - -// NewGetAppsAppRoutesParams creates a new GetAppsAppRoutesParams object -// with the default values initialized. -func NewGetAppsAppRoutesParams() *GetAppsAppRoutesParams { - var () - return &GetAppsAppRoutesParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewGetAppsAppRoutesParamsWithTimeout creates a new GetAppsAppRoutesParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewGetAppsAppRoutesParamsWithTimeout(timeout time.Duration) *GetAppsAppRoutesParams { - var () - return &GetAppsAppRoutesParams{ - - timeout: timeout, - } -} - -// NewGetAppsAppRoutesParamsWithContext creates a new GetAppsAppRoutesParams object -// with the default values initialized, and the ability to set a context for a request -func NewGetAppsAppRoutesParamsWithContext(ctx context.Context) *GetAppsAppRoutesParams { - var () - return &GetAppsAppRoutesParams{ - - Context: ctx, - } -} - -// NewGetAppsAppRoutesParamsWithHTTPClient creates a new GetAppsAppRoutesParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewGetAppsAppRoutesParamsWithHTTPClient(client *http.Client) *GetAppsAppRoutesParams { - var () - return &GetAppsAppRoutesParams{ - HTTPClient: client, - } -} - -/*GetAppsAppRoutesParams contains all the parameters to send to the API endpoint -for the get apps app routes operation typically these are written to a http.Request -*/ -type GetAppsAppRoutesParams struct { - - /*App - Name of app for this set of routes. - - */ - App string - /*Cursor - Cursor from previous response.next_cursor to begin results after, if any. - - */ - Cursor *string - /*Image - Route image to match, exact. - - */ - Image *string - /*PerPage - Number of results to return, defaults to 30. Max of 100. - - */ - PerPage *int64 - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the get apps app routes params -func (o *GetAppsAppRoutesParams) WithTimeout(timeout time.Duration) *GetAppsAppRoutesParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get apps app routes params -func (o *GetAppsAppRoutesParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get apps app routes params -func (o *GetAppsAppRoutesParams) WithContext(ctx context.Context) *GetAppsAppRoutesParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get apps app routes params -func (o *GetAppsAppRoutesParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get apps app routes params -func (o *GetAppsAppRoutesParams) WithHTTPClient(client *http.Client) *GetAppsAppRoutesParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get apps app routes params -func (o *GetAppsAppRoutesParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithApp adds the app to the get apps app routes params -func (o *GetAppsAppRoutesParams) WithApp(app string) *GetAppsAppRoutesParams { - o.SetApp(app) - return o -} - -// SetApp adds the app to the get apps app routes params -func (o *GetAppsAppRoutesParams) SetApp(app string) { - o.App = app -} - -// WithCursor adds the cursor to the get apps app routes params -func (o *GetAppsAppRoutesParams) WithCursor(cursor *string) *GetAppsAppRoutesParams { - o.SetCursor(cursor) - return o -} - -// SetCursor adds the cursor to the get apps app routes params -func (o *GetAppsAppRoutesParams) SetCursor(cursor *string) { - o.Cursor = cursor -} - -// WithImage adds the image to the get apps app routes params -func (o *GetAppsAppRoutesParams) WithImage(image *string) *GetAppsAppRoutesParams { - o.SetImage(image) - return o -} - -// SetImage adds the image to the get apps app routes params -func (o *GetAppsAppRoutesParams) SetImage(image *string) { - o.Image = image -} - -// WithPerPage adds the perPage to the get apps app routes params -func (o *GetAppsAppRoutesParams) WithPerPage(perPage *int64) *GetAppsAppRoutesParams { - o.SetPerPage(perPage) - return o -} - -// SetPerPage adds the perPage to the get apps app routes params -func (o *GetAppsAppRoutesParams) SetPerPage(perPage *int64) { - o.PerPage = perPage -} - -// WriteToRequest writes these params to a swagger request -func (o *GetAppsAppRoutesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param app - if err := r.SetPathParam("app", o.App); err != nil { - return err - } - - if o.Cursor != nil { - - // query param cursor - var qrCursor string - if o.Cursor != nil { - qrCursor = *o.Cursor - } - qCursor := qrCursor - if qCursor != "" { - if err := r.SetQueryParam("cursor", qCursor); err != nil { - return err - } - } - - } - - if o.Image != nil { - - // query param image - var qrImage string - if o.Image != nil { - qrImage = *o.Image - } - qImage := qrImage - if qImage != "" { - if err := r.SetQueryParam("image", qImage); err != nil { - return err - } - } - - } - - if o.PerPage != nil { - - // query param per_page - var qrPerPage int64 - if o.PerPage != nil { - qrPerPage = *o.PerPage - } - qPerPage := swag.FormatInt64(qrPerPage) - if qPerPage != "" { - if err := r.SetQueryParam("per_page", qPerPage); err != nil { - return err - } - } - - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/routes/get_apps_app_routes_responses.go b/vendor/github.com/fnproject/fn_go/client/routes/get_apps_app_routes_responses.go deleted file mode 100644 index 44bb0564a..000000000 --- a/vendor/github.com/fnproject/fn_go/client/routes/get_apps_app_routes_responses.go +++ /dev/null @@ -1,148 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package routes - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// GetAppsAppRoutesReader is a Reader for the GetAppsAppRoutes structure. -type GetAppsAppRoutesReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetAppsAppRoutesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewGetAppsAppRoutesOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - case 404: - result := NewGetAppsAppRoutesNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - default: - result := NewGetAppsAppRoutesDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewGetAppsAppRoutesOK creates a GetAppsAppRoutesOK with default headers values -func NewGetAppsAppRoutesOK() *GetAppsAppRoutesOK { - return &GetAppsAppRoutesOK{} -} - -/*GetAppsAppRoutesOK handles this case with default header values. - -Route information -*/ -type GetAppsAppRoutesOK struct { - Payload *models.RoutesWrapper -} - -func (o *GetAppsAppRoutesOK) Error() string { - return fmt.Sprintf("[GET /apps/{app}/routes][%d] getAppsAppRoutesOK %+v", 200, o.Payload) -} - -func (o *GetAppsAppRoutesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.RoutesWrapper) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetAppsAppRoutesNotFound creates a GetAppsAppRoutesNotFound with default headers values -func NewGetAppsAppRoutesNotFound() *GetAppsAppRoutesNotFound { - return &GetAppsAppRoutesNotFound{} -} - -/*GetAppsAppRoutesNotFound handles this case with default header values. - -App does not exist. -*/ -type GetAppsAppRoutesNotFound struct { - Payload *models.Error -} - -func (o *GetAppsAppRoutesNotFound) Error() string { - return fmt.Sprintf("[GET /apps/{app}/routes][%d] getAppsAppRoutesNotFound %+v", 404, o.Payload) -} - -func (o *GetAppsAppRoutesNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetAppsAppRoutesDefault creates a GetAppsAppRoutesDefault with default headers values -func NewGetAppsAppRoutesDefault(code int) *GetAppsAppRoutesDefault { - return &GetAppsAppRoutesDefault{ - _statusCode: code, - } -} - -/*GetAppsAppRoutesDefault handles this case with default header values. - -Unexpected error -*/ -type GetAppsAppRoutesDefault struct { - _statusCode int - - Payload *models.Error -} - -// Code gets the status code for the get apps app routes default response -func (o *GetAppsAppRoutesDefault) Code() int { - return o._statusCode -} - -func (o *GetAppsAppRoutesDefault) Error() string { - return fmt.Sprintf("[GET /apps/{app}/routes][%d] GetAppsAppRoutes default %+v", o._statusCode, o.Payload) -} - -func (o *GetAppsAppRoutesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/routes/get_apps_app_routes_route_parameters.go b/vendor/github.com/fnproject/fn_go/client/routes/get_apps_app_routes_route_parameters.go deleted file mode 100644 index aa42dc628..000000000 --- a/vendor/github.com/fnproject/fn_go/client/routes/get_apps_app_routes_route_parameters.go +++ /dev/null @@ -1,158 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package routes - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - - strfmt "github.com/go-openapi/strfmt" -) - -// NewGetAppsAppRoutesRouteParams creates a new GetAppsAppRoutesRouteParams object -// with the default values initialized. -func NewGetAppsAppRoutesRouteParams() *GetAppsAppRoutesRouteParams { - var () - return &GetAppsAppRoutesRouteParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewGetAppsAppRoutesRouteParamsWithTimeout creates a new GetAppsAppRoutesRouteParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewGetAppsAppRoutesRouteParamsWithTimeout(timeout time.Duration) *GetAppsAppRoutesRouteParams { - var () - return &GetAppsAppRoutesRouteParams{ - - timeout: timeout, - } -} - -// NewGetAppsAppRoutesRouteParamsWithContext creates a new GetAppsAppRoutesRouteParams object -// with the default values initialized, and the ability to set a context for a request -func NewGetAppsAppRoutesRouteParamsWithContext(ctx context.Context) *GetAppsAppRoutesRouteParams { - var () - return &GetAppsAppRoutesRouteParams{ - - Context: ctx, - } -} - -// NewGetAppsAppRoutesRouteParamsWithHTTPClient creates a new GetAppsAppRoutesRouteParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewGetAppsAppRoutesRouteParamsWithHTTPClient(client *http.Client) *GetAppsAppRoutesRouteParams { - var () - return &GetAppsAppRoutesRouteParams{ - HTTPClient: client, - } -} - -/*GetAppsAppRoutesRouteParams contains all the parameters to send to the API endpoint -for the get apps app routes route operation typically these are written to a http.Request -*/ -type GetAppsAppRoutesRouteParams struct { - - /*App - Name of app for this set of routes. - - */ - App string - /*Route - Route name - - */ - Route string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the get apps app routes route params -func (o *GetAppsAppRoutesRouteParams) WithTimeout(timeout time.Duration) *GetAppsAppRoutesRouteParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get apps app routes route params -func (o *GetAppsAppRoutesRouteParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get apps app routes route params -func (o *GetAppsAppRoutesRouteParams) WithContext(ctx context.Context) *GetAppsAppRoutesRouteParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get apps app routes route params -func (o *GetAppsAppRoutesRouteParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get apps app routes route params -func (o *GetAppsAppRoutesRouteParams) WithHTTPClient(client *http.Client) *GetAppsAppRoutesRouteParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get apps app routes route params -func (o *GetAppsAppRoutesRouteParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithApp adds the app to the get apps app routes route params -func (o *GetAppsAppRoutesRouteParams) WithApp(app string) *GetAppsAppRoutesRouteParams { - o.SetApp(app) - return o -} - -// SetApp adds the app to the get apps app routes route params -func (o *GetAppsAppRoutesRouteParams) SetApp(app string) { - o.App = app -} - -// WithRoute adds the route to the get apps app routes route params -func (o *GetAppsAppRoutesRouteParams) WithRoute(route string) *GetAppsAppRoutesRouteParams { - o.SetRoute(route) - return o -} - -// SetRoute adds the route to the get apps app routes route params -func (o *GetAppsAppRoutesRouteParams) SetRoute(route string) { - o.Route = route -} - -// WriteToRequest writes these params to a swagger request -func (o *GetAppsAppRoutesRouteParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param app - if err := r.SetPathParam("app", o.App); err != nil { - return err - } - - // path param route - if err := r.SetPathParam("route", o.Route); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/routes/get_apps_app_routes_route_responses.go b/vendor/github.com/fnproject/fn_go/client/routes/get_apps_app_routes_route_responses.go deleted file mode 100644 index 689719f17..000000000 --- a/vendor/github.com/fnproject/fn_go/client/routes/get_apps_app_routes_route_responses.go +++ /dev/null @@ -1,148 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package routes - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// GetAppsAppRoutesRouteReader is a Reader for the GetAppsAppRoutesRoute structure. -type GetAppsAppRoutesRouteReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetAppsAppRoutesRouteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewGetAppsAppRoutesRouteOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - case 404: - result := NewGetAppsAppRoutesRouteNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - default: - result := NewGetAppsAppRoutesRouteDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewGetAppsAppRoutesRouteOK creates a GetAppsAppRoutesRouteOK with default headers values -func NewGetAppsAppRoutesRouteOK() *GetAppsAppRoutesRouteOK { - return &GetAppsAppRoutesRouteOK{} -} - -/*GetAppsAppRoutesRouteOK handles this case with default header values. - -Route information -*/ -type GetAppsAppRoutesRouteOK struct { - Payload *models.RouteWrapper -} - -func (o *GetAppsAppRoutesRouteOK) Error() string { - return fmt.Sprintf("[GET /apps/{app}/routes/{route}][%d] getAppsAppRoutesRouteOK %+v", 200, o.Payload) -} - -func (o *GetAppsAppRoutesRouteOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.RouteWrapper) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetAppsAppRoutesRouteNotFound creates a GetAppsAppRoutesRouteNotFound with default headers values -func NewGetAppsAppRoutesRouteNotFound() *GetAppsAppRoutesRouteNotFound { - return &GetAppsAppRoutesRouteNotFound{} -} - -/*GetAppsAppRoutesRouteNotFound handles this case with default header values. - -Route does not exist. -*/ -type GetAppsAppRoutesRouteNotFound struct { - Payload *models.Error -} - -func (o *GetAppsAppRoutesRouteNotFound) Error() string { - return fmt.Sprintf("[GET /apps/{app}/routes/{route}][%d] getAppsAppRoutesRouteNotFound %+v", 404, o.Payload) -} - -func (o *GetAppsAppRoutesRouteNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetAppsAppRoutesRouteDefault creates a GetAppsAppRoutesRouteDefault with default headers values -func NewGetAppsAppRoutesRouteDefault(code int) *GetAppsAppRoutesRouteDefault { - return &GetAppsAppRoutesRouteDefault{ - _statusCode: code, - } -} - -/*GetAppsAppRoutesRouteDefault handles this case with default header values. - -Unexpected error -*/ -type GetAppsAppRoutesRouteDefault struct { - _statusCode int - - Payload *models.Error -} - -// Code gets the status code for the get apps app routes route default response -func (o *GetAppsAppRoutesRouteDefault) Code() int { - return o._statusCode -} - -func (o *GetAppsAppRoutesRouteDefault) Error() string { - return fmt.Sprintf("[GET /apps/{app}/routes/{route}][%d] GetAppsAppRoutesRoute default %+v", o._statusCode, o.Payload) -} - -func (o *GetAppsAppRoutesRouteDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/routes/patch_apps_app_routes_route_parameters.go b/vendor/github.com/fnproject/fn_go/client/routes/patch_apps_app_routes_route_parameters.go deleted file mode 100644 index 5a9343343..000000000 --- a/vendor/github.com/fnproject/fn_go/client/routes/patch_apps_app_routes_route_parameters.go +++ /dev/null @@ -1,182 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package routes - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// NewPatchAppsAppRoutesRouteParams creates a new PatchAppsAppRoutesRouteParams object -// with the default values initialized. -func NewPatchAppsAppRoutesRouteParams() *PatchAppsAppRoutesRouteParams { - var () - return &PatchAppsAppRoutesRouteParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewPatchAppsAppRoutesRouteParamsWithTimeout creates a new PatchAppsAppRoutesRouteParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewPatchAppsAppRoutesRouteParamsWithTimeout(timeout time.Duration) *PatchAppsAppRoutesRouteParams { - var () - return &PatchAppsAppRoutesRouteParams{ - - timeout: timeout, - } -} - -// NewPatchAppsAppRoutesRouteParamsWithContext creates a new PatchAppsAppRoutesRouteParams object -// with the default values initialized, and the ability to set a context for a request -func NewPatchAppsAppRoutesRouteParamsWithContext(ctx context.Context) *PatchAppsAppRoutesRouteParams { - var () - return &PatchAppsAppRoutesRouteParams{ - - Context: ctx, - } -} - -// NewPatchAppsAppRoutesRouteParamsWithHTTPClient creates a new PatchAppsAppRoutesRouteParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewPatchAppsAppRoutesRouteParamsWithHTTPClient(client *http.Client) *PatchAppsAppRoutesRouteParams { - var () - return &PatchAppsAppRoutesRouteParams{ - HTTPClient: client, - } -} - -/*PatchAppsAppRoutesRouteParams contains all the parameters to send to the API endpoint -for the patch apps app routes route operation typically these are written to a http.Request -*/ -type PatchAppsAppRoutesRouteParams struct { - - /*App - name of the app. - - */ - App string - /*Body - One route to post. - - */ - Body *models.RouteWrapper - /*Route - route path. - - */ - Route string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the patch apps app routes route params -func (o *PatchAppsAppRoutesRouteParams) WithTimeout(timeout time.Duration) *PatchAppsAppRoutesRouteParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the patch apps app routes route params -func (o *PatchAppsAppRoutesRouteParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the patch apps app routes route params -func (o *PatchAppsAppRoutesRouteParams) WithContext(ctx context.Context) *PatchAppsAppRoutesRouteParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the patch apps app routes route params -func (o *PatchAppsAppRoutesRouteParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the patch apps app routes route params -func (o *PatchAppsAppRoutesRouteParams) WithHTTPClient(client *http.Client) *PatchAppsAppRoutesRouteParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the patch apps app routes route params -func (o *PatchAppsAppRoutesRouteParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithApp adds the app to the patch apps app routes route params -func (o *PatchAppsAppRoutesRouteParams) WithApp(app string) *PatchAppsAppRoutesRouteParams { - o.SetApp(app) - return o -} - -// SetApp adds the app to the patch apps app routes route params -func (o *PatchAppsAppRoutesRouteParams) SetApp(app string) { - o.App = app -} - -// WithBody adds the body to the patch apps app routes route params -func (o *PatchAppsAppRoutesRouteParams) WithBody(body *models.RouteWrapper) *PatchAppsAppRoutesRouteParams { - o.SetBody(body) - return o -} - -// SetBody adds the body to the patch apps app routes route params -func (o *PatchAppsAppRoutesRouteParams) SetBody(body *models.RouteWrapper) { - o.Body = body -} - -// WithRoute adds the route to the patch apps app routes route params -func (o *PatchAppsAppRoutesRouteParams) WithRoute(route string) *PatchAppsAppRoutesRouteParams { - o.SetRoute(route) - return o -} - -// SetRoute adds the route to the patch apps app routes route params -func (o *PatchAppsAppRoutesRouteParams) SetRoute(route string) { - o.Route = route -} - -// WriteToRequest writes these params to a swagger request -func (o *PatchAppsAppRoutesRouteParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param app - if err := r.SetPathParam("app", o.App); err != nil { - return err - } - - if o.Body != nil { - if err := r.SetBodyParam(o.Body); err != nil { - return err - } - } - - // path param route - if err := r.SetPathParam("route", o.Route); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/routes/patch_apps_app_routes_route_responses.go b/vendor/github.com/fnproject/fn_go/client/routes/patch_apps_app_routes_route_responses.go deleted file mode 100644 index 99b582f86..000000000 --- a/vendor/github.com/fnproject/fn_go/client/routes/patch_apps_app_routes_route_responses.go +++ /dev/null @@ -1,184 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package routes - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// PatchAppsAppRoutesRouteReader is a Reader for the PatchAppsAppRoutesRoute structure. -type PatchAppsAppRoutesRouteReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *PatchAppsAppRoutesRouteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewPatchAppsAppRoutesRouteOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - case 400: - result := NewPatchAppsAppRoutesRouteBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - case 404: - result := NewPatchAppsAppRoutesRouteNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - default: - result := NewPatchAppsAppRoutesRouteDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewPatchAppsAppRoutesRouteOK creates a PatchAppsAppRoutesRouteOK with default headers values -func NewPatchAppsAppRoutesRouteOK() *PatchAppsAppRoutesRouteOK { - return &PatchAppsAppRoutesRouteOK{} -} - -/*PatchAppsAppRoutesRouteOK handles this case with default header values. - -Route updated -*/ -type PatchAppsAppRoutesRouteOK struct { - Payload *models.RouteWrapper -} - -func (o *PatchAppsAppRoutesRouteOK) Error() string { - return fmt.Sprintf("[PATCH /apps/{app}/routes/{route}][%d] patchAppsAppRoutesRouteOK %+v", 200, o.Payload) -} - -func (o *PatchAppsAppRoutesRouteOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.RouteWrapper) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPatchAppsAppRoutesRouteBadRequest creates a PatchAppsAppRoutesRouteBadRequest with default headers values -func NewPatchAppsAppRoutesRouteBadRequest() *PatchAppsAppRoutesRouteBadRequest { - return &PatchAppsAppRoutesRouteBadRequest{} -} - -/*PatchAppsAppRoutesRouteBadRequest handles this case with default header values. - -Invalid route due to parameters being missing or invalid. -*/ -type PatchAppsAppRoutesRouteBadRequest struct { - Payload *models.Error -} - -func (o *PatchAppsAppRoutesRouteBadRequest) Error() string { - return fmt.Sprintf("[PATCH /apps/{app}/routes/{route}][%d] patchAppsAppRoutesRouteBadRequest %+v", 400, o.Payload) -} - -func (o *PatchAppsAppRoutesRouteBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPatchAppsAppRoutesRouteNotFound creates a PatchAppsAppRoutesRouteNotFound with default headers values -func NewPatchAppsAppRoutesRouteNotFound() *PatchAppsAppRoutesRouteNotFound { - return &PatchAppsAppRoutesRouteNotFound{} -} - -/*PatchAppsAppRoutesRouteNotFound handles this case with default header values. - -App / Route does not exist. -*/ -type PatchAppsAppRoutesRouteNotFound struct { - Payload *models.Error -} - -func (o *PatchAppsAppRoutesRouteNotFound) Error() string { - return fmt.Sprintf("[PATCH /apps/{app}/routes/{route}][%d] patchAppsAppRoutesRouteNotFound %+v", 404, o.Payload) -} - -func (o *PatchAppsAppRoutesRouteNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPatchAppsAppRoutesRouteDefault creates a PatchAppsAppRoutesRouteDefault with default headers values -func NewPatchAppsAppRoutesRouteDefault(code int) *PatchAppsAppRoutesRouteDefault { - return &PatchAppsAppRoutesRouteDefault{ - _statusCode: code, - } -} - -/*PatchAppsAppRoutesRouteDefault handles this case with default header values. - -Unexpected error -*/ -type PatchAppsAppRoutesRouteDefault struct { - _statusCode int - - Payload *models.Error -} - -// Code gets the status code for the patch apps app routes route default response -func (o *PatchAppsAppRoutesRouteDefault) Code() int { - return o._statusCode -} - -func (o *PatchAppsAppRoutesRouteDefault) Error() string { - return fmt.Sprintf("[PATCH /apps/{app}/routes/{route}][%d] PatchAppsAppRoutesRoute default %+v", o._statusCode, o.Payload) -} - -func (o *PatchAppsAppRoutesRouteDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/routes/post_apps_app_routes_parameters.go b/vendor/github.com/fnproject/fn_go/client/routes/post_apps_app_routes_parameters.go deleted file mode 100644 index 61faa4a30..000000000 --- a/vendor/github.com/fnproject/fn_go/client/routes/post_apps_app_routes_parameters.go +++ /dev/null @@ -1,161 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package routes - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// NewPostAppsAppRoutesParams creates a new PostAppsAppRoutesParams object -// with the default values initialized. -func NewPostAppsAppRoutesParams() *PostAppsAppRoutesParams { - var () - return &PostAppsAppRoutesParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewPostAppsAppRoutesParamsWithTimeout creates a new PostAppsAppRoutesParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewPostAppsAppRoutesParamsWithTimeout(timeout time.Duration) *PostAppsAppRoutesParams { - var () - return &PostAppsAppRoutesParams{ - - timeout: timeout, - } -} - -// NewPostAppsAppRoutesParamsWithContext creates a new PostAppsAppRoutesParams object -// with the default values initialized, and the ability to set a context for a request -func NewPostAppsAppRoutesParamsWithContext(ctx context.Context) *PostAppsAppRoutesParams { - var () - return &PostAppsAppRoutesParams{ - - Context: ctx, - } -} - -// NewPostAppsAppRoutesParamsWithHTTPClient creates a new PostAppsAppRoutesParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewPostAppsAppRoutesParamsWithHTTPClient(client *http.Client) *PostAppsAppRoutesParams { - var () - return &PostAppsAppRoutesParams{ - HTTPClient: client, - } -} - -/*PostAppsAppRoutesParams contains all the parameters to send to the API endpoint -for the post apps app routes operation typically these are written to a http.Request -*/ -type PostAppsAppRoutesParams struct { - - /*App - name of the app. - - */ - App string - /*Body - One route to post. - - */ - Body *models.RouteWrapper - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the post apps app routes params -func (o *PostAppsAppRoutesParams) WithTimeout(timeout time.Duration) *PostAppsAppRoutesParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the post apps app routes params -func (o *PostAppsAppRoutesParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the post apps app routes params -func (o *PostAppsAppRoutesParams) WithContext(ctx context.Context) *PostAppsAppRoutesParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the post apps app routes params -func (o *PostAppsAppRoutesParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the post apps app routes params -func (o *PostAppsAppRoutesParams) WithHTTPClient(client *http.Client) *PostAppsAppRoutesParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the post apps app routes params -func (o *PostAppsAppRoutesParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithApp adds the app to the post apps app routes params -func (o *PostAppsAppRoutesParams) WithApp(app string) *PostAppsAppRoutesParams { - o.SetApp(app) - return o -} - -// SetApp adds the app to the post apps app routes params -func (o *PostAppsAppRoutesParams) SetApp(app string) { - o.App = app -} - -// WithBody adds the body to the post apps app routes params -func (o *PostAppsAppRoutesParams) WithBody(body *models.RouteWrapper) *PostAppsAppRoutesParams { - o.SetBody(body) - return o -} - -// SetBody adds the body to the post apps app routes params -func (o *PostAppsAppRoutesParams) SetBody(body *models.RouteWrapper) { - o.Body = body -} - -// WriteToRequest writes these params to a swagger request -func (o *PostAppsAppRoutesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param app - if err := r.SetPathParam("app", o.App); err != nil { - return err - } - - if o.Body != nil { - if err := r.SetBodyParam(o.Body); err != nil { - return err - } - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/routes/post_apps_app_routes_responses.go b/vendor/github.com/fnproject/fn_go/client/routes/post_apps_app_routes_responses.go deleted file mode 100644 index 67fa20699..000000000 --- a/vendor/github.com/fnproject/fn_go/client/routes/post_apps_app_routes_responses.go +++ /dev/null @@ -1,184 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package routes - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// PostAppsAppRoutesReader is a Reader for the PostAppsAppRoutes structure. -type PostAppsAppRoutesReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *PostAppsAppRoutesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewPostAppsAppRoutesOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - case 400: - result := NewPostAppsAppRoutesBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - case 409: - result := NewPostAppsAppRoutesConflict() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - default: - result := NewPostAppsAppRoutesDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewPostAppsAppRoutesOK creates a PostAppsAppRoutesOK with default headers values -func NewPostAppsAppRoutesOK() *PostAppsAppRoutesOK { - return &PostAppsAppRoutesOK{} -} - -/*PostAppsAppRoutesOK handles this case with default header values. - -Route created -*/ -type PostAppsAppRoutesOK struct { - Payload *models.RouteWrapper -} - -func (o *PostAppsAppRoutesOK) Error() string { - return fmt.Sprintf("[POST /apps/{app}/routes][%d] postAppsAppRoutesOK %+v", 200, o.Payload) -} - -func (o *PostAppsAppRoutesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.RouteWrapper) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPostAppsAppRoutesBadRequest creates a PostAppsAppRoutesBadRequest with default headers values -func NewPostAppsAppRoutesBadRequest() *PostAppsAppRoutesBadRequest { - return &PostAppsAppRoutesBadRequest{} -} - -/*PostAppsAppRoutesBadRequest handles this case with default header values. - -Invalid route due to parameters being missing or invalid. -*/ -type PostAppsAppRoutesBadRequest struct { - Payload *models.Error -} - -func (o *PostAppsAppRoutesBadRequest) Error() string { - return fmt.Sprintf("[POST /apps/{app}/routes][%d] postAppsAppRoutesBadRequest %+v", 400, o.Payload) -} - -func (o *PostAppsAppRoutesBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPostAppsAppRoutesConflict creates a PostAppsAppRoutesConflict with default headers values -func NewPostAppsAppRoutesConflict() *PostAppsAppRoutesConflict { - return &PostAppsAppRoutesConflict{} -} - -/*PostAppsAppRoutesConflict handles this case with default header values. - -Route already exists. -*/ -type PostAppsAppRoutesConflict struct { - Payload *models.Error -} - -func (o *PostAppsAppRoutesConflict) Error() string { - return fmt.Sprintf("[POST /apps/{app}/routes][%d] postAppsAppRoutesConflict %+v", 409, o.Payload) -} - -func (o *PostAppsAppRoutesConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPostAppsAppRoutesDefault creates a PostAppsAppRoutesDefault with default headers values -func NewPostAppsAppRoutesDefault(code int) *PostAppsAppRoutesDefault { - return &PostAppsAppRoutesDefault{ - _statusCode: code, - } -} - -/*PostAppsAppRoutesDefault handles this case with default header values. - -Unexpected error -*/ -type PostAppsAppRoutesDefault struct { - _statusCode int - - Payload *models.Error -} - -// Code gets the status code for the post apps app routes default response -func (o *PostAppsAppRoutesDefault) Code() int { - return o._statusCode -} - -func (o *PostAppsAppRoutesDefault) Error() string { - return fmt.Sprintf("[POST /apps/{app}/routes][%d] PostAppsAppRoutes default %+v", o._statusCode, o.Payload) -} - -func (o *PostAppsAppRoutesDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/routes/put_apps_app_routes_route_parameters.go b/vendor/github.com/fnproject/fn_go/client/routes/put_apps_app_routes_route_parameters.go deleted file mode 100644 index 6299fc7a9..000000000 --- a/vendor/github.com/fnproject/fn_go/client/routes/put_apps_app_routes_route_parameters.go +++ /dev/null @@ -1,182 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package routes - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// NewPutAppsAppRoutesRouteParams creates a new PutAppsAppRoutesRouteParams object -// with the default values initialized. -func NewPutAppsAppRoutesRouteParams() *PutAppsAppRoutesRouteParams { - var () - return &PutAppsAppRoutesRouteParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewPutAppsAppRoutesRouteParamsWithTimeout creates a new PutAppsAppRoutesRouteParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewPutAppsAppRoutesRouteParamsWithTimeout(timeout time.Duration) *PutAppsAppRoutesRouteParams { - var () - return &PutAppsAppRoutesRouteParams{ - - timeout: timeout, - } -} - -// NewPutAppsAppRoutesRouteParamsWithContext creates a new PutAppsAppRoutesRouteParams object -// with the default values initialized, and the ability to set a context for a request -func NewPutAppsAppRoutesRouteParamsWithContext(ctx context.Context) *PutAppsAppRoutesRouteParams { - var () - return &PutAppsAppRoutesRouteParams{ - - Context: ctx, - } -} - -// NewPutAppsAppRoutesRouteParamsWithHTTPClient creates a new PutAppsAppRoutesRouteParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewPutAppsAppRoutesRouteParamsWithHTTPClient(client *http.Client) *PutAppsAppRoutesRouteParams { - var () - return &PutAppsAppRoutesRouteParams{ - HTTPClient: client, - } -} - -/*PutAppsAppRoutesRouteParams contains all the parameters to send to the API endpoint -for the put apps app routes route operation typically these are written to a http.Request -*/ -type PutAppsAppRoutesRouteParams struct { - - /*App - name of the app. - - */ - App string - /*Body - One route to post. - - */ - Body *models.RouteWrapper - /*Route - route path. - - */ - Route string - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the put apps app routes route params -func (o *PutAppsAppRoutesRouteParams) WithTimeout(timeout time.Duration) *PutAppsAppRoutesRouteParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the put apps app routes route params -func (o *PutAppsAppRoutesRouteParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the put apps app routes route params -func (o *PutAppsAppRoutesRouteParams) WithContext(ctx context.Context) *PutAppsAppRoutesRouteParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the put apps app routes route params -func (o *PutAppsAppRoutesRouteParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the put apps app routes route params -func (o *PutAppsAppRoutesRouteParams) WithHTTPClient(client *http.Client) *PutAppsAppRoutesRouteParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the put apps app routes route params -func (o *PutAppsAppRoutesRouteParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithApp adds the app to the put apps app routes route params -func (o *PutAppsAppRoutesRouteParams) WithApp(app string) *PutAppsAppRoutesRouteParams { - o.SetApp(app) - return o -} - -// SetApp adds the app to the put apps app routes route params -func (o *PutAppsAppRoutesRouteParams) SetApp(app string) { - o.App = app -} - -// WithBody adds the body to the put apps app routes route params -func (o *PutAppsAppRoutesRouteParams) WithBody(body *models.RouteWrapper) *PutAppsAppRoutesRouteParams { - o.SetBody(body) - return o -} - -// SetBody adds the body to the put apps app routes route params -func (o *PutAppsAppRoutesRouteParams) SetBody(body *models.RouteWrapper) { - o.Body = body -} - -// WithRoute adds the route to the put apps app routes route params -func (o *PutAppsAppRoutesRouteParams) WithRoute(route string) *PutAppsAppRoutesRouteParams { - o.SetRoute(route) - return o -} - -// SetRoute adds the route to the put apps app routes route params -func (o *PutAppsAppRoutesRouteParams) SetRoute(route string) { - o.Route = route -} - -// WriteToRequest writes these params to a swagger request -func (o *PutAppsAppRoutesRouteParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - // path param app - if err := r.SetPathParam("app", o.App); err != nil { - return err - } - - if o.Body != nil { - if err := r.SetBodyParam(o.Body); err != nil { - return err - } - } - - // path param route - if err := r.SetPathParam("route", o.Route); err != nil { - return err - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/routes/put_apps_app_routes_route_responses.go b/vendor/github.com/fnproject/fn_go/client/routes/put_apps_app_routes_route_responses.go deleted file mode 100644 index 16c151ff2..000000000 --- a/vendor/github.com/fnproject/fn_go/client/routes/put_apps_app_routes_route_responses.go +++ /dev/null @@ -1,148 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package routes - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - models "github.com/fnproject/fn_go/models" -) - -// PutAppsAppRoutesRouteReader is a Reader for the PutAppsAppRoutesRoute structure. -type PutAppsAppRoutesRouteReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *PutAppsAppRoutesRouteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewPutAppsAppRoutesRouteOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - case 400: - result := NewPutAppsAppRoutesRouteBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - - default: - result := NewPutAppsAppRoutesRouteDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewPutAppsAppRoutesRouteOK creates a PutAppsAppRoutesRouteOK with default headers values -func NewPutAppsAppRoutesRouteOK() *PutAppsAppRoutesRouteOK { - return &PutAppsAppRoutesRouteOK{} -} - -/*PutAppsAppRoutesRouteOK handles this case with default header values. - -Route created or updated -*/ -type PutAppsAppRoutesRouteOK struct { - Payload *models.RouteWrapper -} - -func (o *PutAppsAppRoutesRouteOK) Error() string { - return fmt.Sprintf("[PUT /apps/{app}/routes/{route}][%d] putAppsAppRoutesRouteOK %+v", 200, o.Payload) -} - -func (o *PutAppsAppRoutesRouteOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.RouteWrapper) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPutAppsAppRoutesRouteBadRequest creates a PutAppsAppRoutesRouteBadRequest with default headers values -func NewPutAppsAppRoutesRouteBadRequest() *PutAppsAppRoutesRouteBadRequest { - return &PutAppsAppRoutesRouteBadRequest{} -} - -/*PutAppsAppRoutesRouteBadRequest handles this case with default header values. - -Invalid route due to parameters being missing or invalid. -*/ -type PutAppsAppRoutesRouteBadRequest struct { - Payload *models.Error -} - -func (o *PutAppsAppRoutesRouteBadRequest) Error() string { - return fmt.Sprintf("[PUT /apps/{app}/routes/{route}][%d] putAppsAppRoutesRouteBadRequest %+v", 400, o.Payload) -} - -func (o *PutAppsAppRoutesRouteBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewPutAppsAppRoutesRouteDefault creates a PutAppsAppRoutesRouteDefault with default headers values -func NewPutAppsAppRoutesRouteDefault(code int) *PutAppsAppRoutesRouteDefault { - return &PutAppsAppRoutesRouteDefault{ - _statusCode: code, - } -} - -/*PutAppsAppRoutesRouteDefault handles this case with default header values. - -Unexpected error -*/ -type PutAppsAppRoutesRouteDefault struct { - _statusCode int - - Payload *models.Error -} - -// Code gets the status code for the put apps app routes route default response -func (o *PutAppsAppRoutesRouteDefault) Code() int { - return o._statusCode -} - -func (o *PutAppsAppRoutesRouteDefault) Error() string { - return fmt.Sprintf("[PUT /apps/{app}/routes/{route}][%d] PutAppsAppRoutesRoute default %+v", o._statusCode, o.Payload) -} - -func (o *PutAppsAppRoutesRouteDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/routes/routes_client.go b/vendor/github.com/fnproject/fn_go/client/routes/routes_client.go deleted file mode 100644 index d00faa6a9..000000000 --- a/vendor/github.com/fnproject/fn_go/client/routes/routes_client.go +++ /dev/null @@ -1,210 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package routes - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" -) - -// New creates a new routes API client. -func New(transport runtime.ClientTransport, formats strfmt.Registry) *Client { - return &Client{transport: transport, formats: formats} -} - -/* -Client for routes API -*/ -type Client struct { - transport runtime.ClientTransport - formats strfmt.Registry -} - -/* -DeleteAppsAppRoutesRoute deletes the route - -Deletes the route. -*/ -func (a *Client) DeleteAppsAppRoutesRoute(params *DeleteAppsAppRoutesRouteParams) (*DeleteAppsAppRoutesRouteOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewDeleteAppsAppRoutesRouteParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "DeleteAppsAppRoutesRoute", - Method: "DELETE", - PathPattern: "/apps/{app}/routes/{route}", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &DeleteAppsAppRoutesRouteReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*DeleteAppsAppRoutesRouteOK), nil - -} - -/* -GetAppsAppRoutes gets route list by app name - -This will list routes for a particular app, returned in alphabetical order. -*/ -func (a *Client) GetAppsAppRoutes(params *GetAppsAppRoutesParams) (*GetAppsAppRoutesOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetAppsAppRoutesParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "GetAppsAppRoutes", - Method: "GET", - PathPattern: "/apps/{app}/routes", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &GetAppsAppRoutesReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*GetAppsAppRoutesOK), nil - -} - -/* -GetAppsAppRoutesRoute gets route by name - -Gets a route by name. -*/ -func (a *Client) GetAppsAppRoutesRoute(params *GetAppsAppRoutesRouteParams) (*GetAppsAppRoutesRouteOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetAppsAppRoutesRouteParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "GetAppsAppRoutesRoute", - Method: "GET", - PathPattern: "/apps/{app}/routes/{route}", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &GetAppsAppRoutesRouteReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*GetAppsAppRoutesRouteOK), nil - -} - -/* -PatchAppsAppRoutesRoute updates a route fails if the route or app does not exist accepts partial updates skips validation of zero values - -Update a route -*/ -func (a *Client) PatchAppsAppRoutesRoute(params *PatchAppsAppRoutesRouteParams) (*PatchAppsAppRoutesRouteOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewPatchAppsAppRoutesRouteParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "PatchAppsAppRoutesRoute", - Method: "PATCH", - PathPattern: "/apps/{app}/routes/{route}", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &PatchAppsAppRoutesRouteReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*PatchAppsAppRoutesRouteOK), nil - -} - -/* -PostAppsAppRoutes creates new route - -Create a new route in an app, if app doesn't exists, it creates the app. Post does not skip validation of zero values. -*/ -func (a *Client) PostAppsAppRoutes(params *PostAppsAppRoutesParams) (*PostAppsAppRoutesOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewPostAppsAppRoutesParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "PostAppsAppRoutes", - Method: "POST", - PathPattern: "/apps/{app}/routes", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &PostAppsAppRoutesReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*PostAppsAppRoutesOK), nil - -} - -/* -PutAppsAppRoutesRoute creates a route if it does not exist update if it does will also create app if it does not exist put does not skip validation of zero values - -Update or Create a route -*/ -func (a *Client) PutAppsAppRoutesRoute(params *PutAppsAppRoutesRouteParams) (*PutAppsAppRoutesRouteOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewPutAppsAppRoutesRouteParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "PutAppsAppRoutesRoute", - Method: "PUT", - PathPattern: "/apps/{app}/routes/{route}", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &PutAppsAppRoutesRouteReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*PutAppsAppRoutesRouteOK), nil - -} - -// SetTransport changes the transport on the client -func (a *Client) SetTransport(transport runtime.ClientTransport) { - a.transport = transport -} diff --git a/vendor/github.com/fnproject/fn_go/client/tasks/get_tasks_parameters.go b/vendor/github.com/fnproject/fn_go/client/tasks/get_tasks_parameters.go deleted file mode 100644 index 5398ab931..000000000 --- a/vendor/github.com/fnproject/fn_go/client/tasks/get_tasks_parameters.go +++ /dev/null @@ -1,114 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package tasks - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - - strfmt "github.com/go-openapi/strfmt" -) - -// NewGetTasksParams creates a new GetTasksParams object -// with the default values initialized. -func NewGetTasksParams() *GetTasksParams { - - return &GetTasksParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewGetTasksParamsWithTimeout creates a new GetTasksParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewGetTasksParamsWithTimeout(timeout time.Duration) *GetTasksParams { - - return &GetTasksParams{ - - timeout: timeout, - } -} - -// NewGetTasksParamsWithContext creates a new GetTasksParams object -// with the default values initialized, and the ability to set a context for a request -func NewGetTasksParamsWithContext(ctx context.Context) *GetTasksParams { - - return &GetTasksParams{ - - Context: ctx, - } -} - -// NewGetTasksParamsWithHTTPClient creates a new GetTasksParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewGetTasksParamsWithHTTPClient(client *http.Client) *GetTasksParams { - - return &GetTasksParams{ - HTTPClient: client, - } -} - -/*GetTasksParams contains all the parameters to send to the API endpoint -for the get tasks operation typically these are written to a http.Request -*/ -type GetTasksParams struct { - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the get tasks params -func (o *GetTasksParams) WithTimeout(timeout time.Duration) *GetTasksParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get tasks params -func (o *GetTasksParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get tasks params -func (o *GetTasksParams) WithContext(ctx context.Context) *GetTasksParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get tasks params -func (o *GetTasksParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get tasks params -func (o *GetTasksParams) WithHTTPClient(client *http.Client) *GetTasksParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get tasks params -func (o *GetTasksParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WriteToRequest writes these params to a swagger request -func (o *GetTasksParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/tasks/get_tasks_responses.go b/vendor/github.com/fnproject/fn_go/client/tasks/get_tasks_responses.go deleted file mode 100644 index bef2b8932..000000000 --- a/vendor/github.com/fnproject/fn_go/client/tasks/get_tasks_responses.go +++ /dev/null @@ -1,112 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package tasks - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - "github.com/fnproject/fn_go/models" -) - -// GetTasksReader is a Reader for the GetTasks structure. -type GetTasksReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetTasksReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewGetTasksOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - default: - result := NewGetTasksDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewGetTasksOK creates a GetTasksOK with default headers values -func NewGetTasksOK() *GetTasksOK { - return &GetTasksOK{} -} - -/*GetTasksOK handles this case with default header values. - -Task information -*/ -type GetTasksOK struct { - Payload *models.TaskWrapper -} - -func (o *GetTasksOK) Error() string { - return fmt.Sprintf("[GET /tasks][%d] getTasksOK %+v", 200, o.Payload) -} - -func (o *GetTasksOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.TaskWrapper) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetTasksDefault creates a GetTasksDefault with default headers values -func NewGetTasksDefault(code int) *GetTasksDefault { - return &GetTasksDefault{ - _statusCode: code, - } -} - -/*GetTasksDefault handles this case with default header values. - -Unexpected error -*/ -type GetTasksDefault struct { - _statusCode int - - Payload *models.Error -} - -// Code gets the status code for the get tasks default response -func (o *GetTasksDefault) Code() int { - return o._statusCode -} - -func (o *GetTasksDefault) Error() string { - return fmt.Sprintf("[GET /tasks][%d] GetTasks default %+v", o._statusCode, o.Payload) -} - -func (o *GetTasksDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/tasks/tasks_client.go b/vendor/github.com/fnproject/fn_go/client/tasks/tasks_client.go deleted file mode 100644 index fdd690d61..000000000 --- a/vendor/github.com/fnproject/fn_go/client/tasks/tasks_client.go +++ /dev/null @@ -1,60 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package tasks - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" -) - -// New creates a new tasks API client. -func New(transport runtime.ClientTransport, formats strfmt.Registry) *Client { - return &Client{transport: transport, formats: formats} -} - -/* -Client for tasks API -*/ -type Client struct { - transport runtime.ClientTransport - formats strfmt.Registry -} - -/* -GetTasks gets next task - -Gets the next task in the queue, ready for processing. Consumers should start processing tasks in order. No other consumer can retrieve this task. -*/ -func (a *Client) GetTasks(params *GetTasksParams) (*GetTasksOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetTasksParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "GetTasks", - Method: "GET", - PathPattern: "/tasks", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &GetTasksReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*GetTasksOK), nil - -} - -// SetTransport changes the transport on the client -func (a *Client) SetTransport(transport runtime.ClientTransport) { - a.transport = transport -} diff --git a/vendor/github.com/fnproject/fn_go/client/version/get_version_parameters.go b/vendor/github.com/fnproject/fn_go/client/version/get_version_parameters.go deleted file mode 100644 index 062b0a2f8..000000000 --- a/vendor/github.com/fnproject/fn_go/client/version/get_version_parameters.go +++ /dev/null @@ -1,114 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package version - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - "time" - - "golang.org/x/net/context" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - - strfmt "github.com/go-openapi/strfmt" -) - -// NewGetVersionParams creates a new GetVersionParams object -// with the default values initialized. -func NewGetVersionParams() *GetVersionParams { - - return &GetVersionParams{ - - timeout: cr.DefaultTimeout, - } -} - -// NewGetVersionParamsWithTimeout creates a new GetVersionParams object -// with the default values initialized, and the ability to set a timeout on a request -func NewGetVersionParamsWithTimeout(timeout time.Duration) *GetVersionParams { - - return &GetVersionParams{ - - timeout: timeout, - } -} - -// NewGetVersionParamsWithContext creates a new GetVersionParams object -// with the default values initialized, and the ability to set a context for a request -func NewGetVersionParamsWithContext(ctx context.Context) *GetVersionParams { - - return &GetVersionParams{ - - Context: ctx, - } -} - -// NewGetVersionParamsWithHTTPClient creates a new GetVersionParams object -// with the default values initialized, and the ability to set a custom HTTPClient for a request -func NewGetVersionParamsWithHTTPClient(client *http.Client) *GetVersionParams { - - return &GetVersionParams{ - HTTPClient: client, - } -} - -/*GetVersionParams contains all the parameters to send to the API endpoint -for the get version operation typically these are written to a http.Request -*/ -type GetVersionParams struct { - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithTimeout adds the timeout to the get version params -func (o *GetVersionParams) WithTimeout(timeout time.Duration) *GetVersionParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get version params -func (o *GetVersionParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get version params -func (o *GetVersionParams) WithContext(ctx context.Context) *GetVersionParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get version params -func (o *GetVersionParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get version params -func (o *GetVersionParams) WithHTTPClient(client *http.Client) *GetVersionParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get version params -func (o *GetVersionParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WriteToRequest writes these params to a swagger request -func (o *GetVersionParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/version/get_version_responses.go b/vendor/github.com/fnproject/fn_go/client/version/get_version_responses.go deleted file mode 100644 index d09dade59..000000000 --- a/vendor/github.com/fnproject/fn_go/client/version/get_version_responses.go +++ /dev/null @@ -1,67 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package version - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" - - "github.com/fnproject/fn_go/models" -) - -// GetVersionReader is a Reader for the GetVersion structure. -type GetVersionReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetVersionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - - case 200: - result := NewGetVersionOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - - default: - return nil, runtime.NewAPIError("unknown error", response, response.Code()) - } -} - -// NewGetVersionOK creates a GetVersionOK with default headers values -func NewGetVersionOK() *GetVersionOK { - return &GetVersionOK{} -} - -/*GetVersionOK handles this case with default header values. - -Daemon version. -*/ -type GetVersionOK struct { - Payload *models.Version -} - -func (o *GetVersionOK) Error() string { - return fmt.Sprintf("[GET /version][%d] getVersionOK %+v", 200, o.Payload) -} - -func (o *GetVersionOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Version) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/client/version/version_client.go b/vendor/github.com/fnproject/fn_go/client/version/version_client.go deleted file mode 100644 index 0624a0e2c..000000000 --- a/vendor/github.com/fnproject/fn_go/client/version/version_client.go +++ /dev/null @@ -1,58 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package version - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "github.com/go-openapi/runtime" - - strfmt "github.com/go-openapi/strfmt" -) - -// New creates a new version API client. -func New(transport runtime.ClientTransport, formats strfmt.Registry) *Client { - return &Client{transport: transport, formats: formats} -} - -/* -Client for version API -*/ -type Client struct { - transport runtime.ClientTransport - formats strfmt.Registry -} - -/* -GetVersion gets daemon version -*/ -func (a *Client) GetVersion(params *GetVersionParams) (*GetVersionOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetVersionParams() - } - - result, err := a.transport.Submit(&runtime.ClientOperation{ - ID: "GetVersion", - Method: "GET", - PathPattern: "/version", - ProducesMediaTypes: []string{"application/json"}, - ConsumesMediaTypes: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Params: params, - Reader: &GetVersionReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - }) - if err != nil { - return nil, err - } - return result.(*GetVersionOK), nil - -} - -// SetTransport changes the transport on the client -func (a *Client) SetTransport(transport runtime.ClientTransport) { - a.transport = transport -} diff --git a/vendor/github.com/fnproject/fn_go/models/app.go b/vendor/github.com/fnproject/fn_go/models/app.go deleted file mode 100644 index 265178eb6..000000000 --- a/vendor/github.com/fnproject/fn_go/models/app.go +++ /dev/null @@ -1,101 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// App app -// swagger:model App -type App struct { - - // Application annotations - this is a map of annotations attached to this app, keys must not exceed 128 bytes and must consist of non-whitespace printable ascii characters, and the seralized representation of individual values must not exeed 512 bytes - Annotations map[string]interface{} `json:"annotations,omitempty"` - - // Application function configuration, applied to all routes. - Config map[string]string `json:"config,omitempty"` - - // Time when app was created. Always in UTC. - // Read Only: true - CreatedAt strfmt.DateTime `json:"created_at,omitempty"` - - // Name of this app. Must be different than the image name. Can ony contain alphanumeric, -, and _. - // Read Only: true - Name string `json:"name,omitempty"` - - // Most recent time that app was updated. Always in UTC. - // Read Only: true - UpdatedAt strfmt.DateTime `json:"updated_at,omitempty"` -} - -// Validate validates this app -func (m *App) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCreatedAt(formats); err != nil { - // prop - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - // prop - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *App) validateCreatedAt(formats strfmt.Registry) error { - - if swag.IsZero(m.CreatedAt) { // not required - return nil - } - - if err := validate.FormatOf("created_at", "body", "date-time", m.CreatedAt.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *App) validateUpdatedAt(formats strfmt.Registry) error { - - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.FormatOf("updated_at", "body", "date-time", m.UpdatedAt.String(), formats); err != nil { - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *App) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *App) UnmarshalBinary(b []byte) error { - var res App - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/app_wrapper.go b/vendor/github.com/fnproject/fn_go/models/app_wrapper.go deleted file mode 100644 index b28e785d2..000000000 --- a/vendor/github.com/fnproject/fn_go/models/app_wrapper.go +++ /dev/null @@ -1,104 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// AppWrapper app wrapper -// swagger:model AppWrapper -type AppWrapper struct { - - // app - // Required: true - App *App `json:"app"` - - // error - Error *ErrorBody `json:"error,omitempty"` -} - -// Validate validates this app wrapper -func (m *AppWrapper) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateApp(formats); err != nil { - // prop - res = append(res, err) - } - - if err := m.validateError(formats); err != nil { - // prop - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AppWrapper) validateApp(formats strfmt.Registry) error { - - if err := validate.Required("app", "body", m.App); err != nil { - return err - } - - if m.App != nil { - - if err := m.App.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("app") - } - return err - } - - } - - return nil -} - -func (m *AppWrapper) validateError(formats strfmt.Registry) error { - - if swag.IsZero(m.Error) { // not required - return nil - } - - if m.Error != nil { - - if err := m.Error.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("error") - } - return err - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *AppWrapper) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AppWrapper) UnmarshalBinary(b []byte) error { - var res AppWrapper - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/apps_wrapper.go b/vendor/github.com/fnproject/fn_go/models/apps_wrapper.go deleted file mode 100644 index 5d03c4e03..000000000 --- a/vendor/github.com/fnproject/fn_go/models/apps_wrapper.go +++ /dev/null @@ -1,118 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "strconv" - - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// AppsWrapper apps wrapper -// swagger:model AppsWrapper -type AppsWrapper struct { - - // apps - // Required: true - Apps []*App `json:"apps"` - - // error - Error *ErrorBody `json:"error,omitempty"` - - // cursor to send with subsequent request to receive the next page, if non-empty - // Read Only: true - NextCursor string `json:"next_cursor,omitempty"` -} - -// Validate validates this apps wrapper -func (m *AppsWrapper) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateApps(formats); err != nil { - // prop - res = append(res, err) - } - - if err := m.validateError(formats); err != nil { - // prop - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *AppsWrapper) validateApps(formats strfmt.Registry) error { - - if err := validate.Required("apps", "body", m.Apps); err != nil { - return err - } - - for i := 0; i < len(m.Apps); i++ { - - if swag.IsZero(m.Apps[i]) { // not required - continue - } - - if m.Apps[i] != nil { - - if err := m.Apps[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("apps" + "." + strconv.Itoa(i)) - } - return err - } - - } - - } - - return nil -} - -func (m *AppsWrapper) validateError(formats strfmt.Registry) error { - - if swag.IsZero(m.Error) { // not required - return nil - } - - if m.Error != nil { - - if err := m.Error.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("error") - } - return err - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *AppsWrapper) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *AppsWrapper) UnmarshalBinary(b []byte) error { - var res AppsWrapper - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/apps_wrapper_apps.go b/vendor/github.com/fnproject/fn_go/models/apps_wrapper_apps.go deleted file mode 100644 index 5453def9f..000000000 --- a/vendor/github.com/fnproject/fn_go/models/apps_wrapper_apps.go +++ /dev/null @@ -1,47 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "strconv" - - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" -) - -// AppsWrapperApps apps wrapper apps -// swagger:model appsWrapperApps -type AppsWrapperApps []*App - -// Validate validates this apps wrapper apps -func (m AppsWrapperApps) Validate(formats strfmt.Registry) error { - var res []error - - for i := 0; i < len(m); i++ { - - if swag.IsZero(m[i]) { // not required - continue - } - - if m[i] != nil { - - if err := m[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName(strconv.Itoa(i)) - } - return err - } - } - - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/call.go b/vendor/github.com/fnproject/fn_go/models/call.go deleted file mode 100644 index cfe439a9c..000000000 --- a/vendor/github.com/fnproject/fn_go/models/call.go +++ /dev/null @@ -1,172 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "strconv" - - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Call call -// swagger:model Call -type Call struct { - - // App name that is assigned to a route that is being executed. - // Read Only: true - AppName string `json:"app_name,omitempty"` - - // Time when call completed, whether it was successul or failed. Always in UTC. - // Read Only: true - CompletedAt strfmt.DateTime `json:"completed_at,omitempty"` - - // Time when call was submitted. Always in UTC. - // Read Only: true - CreatedAt strfmt.DateTime `json:"created_at,omitempty"` - - // Call execution error, if status is 'error'. - // Read Only: true - Error string `json:"error,omitempty"` - - // Call UUID ID. - // Read Only: true - ID string `json:"id,omitempty"` - - // App route that is being executed. - // Read Only: true - Path string `json:"path,omitempty"` - - // Time when call started execution. Always in UTC. - // Read Only: true - StartedAt strfmt.DateTime `json:"started_at,omitempty"` - - // A histogram of stats for a call, each is a snapshot of a calls state at the timestamp. - // Read Only: true - Stats []*Stat `json:"stats"` - - // Call execution status. - // Read Only: true - Status string `json:"status,omitempty"` -} - -// Validate validates this call -func (m *Call) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCompletedAt(formats); err != nil { - // prop - res = append(res, err) - } - - if err := m.validateCreatedAt(formats); err != nil { - // prop - res = append(res, err) - } - - if err := m.validateStartedAt(formats); err != nil { - // prop - res = append(res, err) - } - - if err := m.validateStats(formats); err != nil { - // prop - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Call) validateCompletedAt(formats strfmt.Registry) error { - - if swag.IsZero(m.CompletedAt) { // not required - return nil - } - - if err := validate.FormatOf("completed_at", "body", "date-time", m.CompletedAt.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *Call) validateCreatedAt(formats strfmt.Registry) error { - - if swag.IsZero(m.CreatedAt) { // not required - return nil - } - - if err := validate.FormatOf("created_at", "body", "date-time", m.CreatedAt.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *Call) validateStartedAt(formats strfmt.Registry) error { - - if swag.IsZero(m.StartedAt) { // not required - return nil - } - - if err := validate.FormatOf("started_at", "body", "date-time", m.StartedAt.String(), formats); err != nil { - return err - } - - return nil -} - -func (m *Call) validateStats(formats strfmt.Registry) error { - - if swag.IsZero(m.Stats) { // not required - return nil - } - - for i := 0; i < len(m.Stats); i++ { - - if swag.IsZero(m.Stats[i]) { // not required - continue - } - - if m.Stats[i] != nil { - - if err := m.Stats[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("stats" + "." + strconv.Itoa(i)) - } - return err - } - - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Call) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Call) UnmarshalBinary(b []byte) error { - var res Call - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/call_stats.go b/vendor/github.com/fnproject/fn_go/models/call_stats.go deleted file mode 100644 index 8a41262cb..000000000 --- a/vendor/github.com/fnproject/fn_go/models/call_stats.go +++ /dev/null @@ -1,47 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "strconv" - - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" -) - -// CallStats A histogram of stats for a call, each is a snapshot of a calls state at the timestamp. -// swagger:model callStats -type CallStats []*Stat - -// Validate validates this call stats -func (m CallStats) Validate(formats strfmt.Registry) error { - var res []error - - for i := 0; i < len(m); i++ { - - if swag.IsZero(m[i]) { // not required - continue - } - - if m[i] != nil { - - if err := m[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName(strconv.Itoa(i)) - } - return err - } - } - - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/call_wrapper.go b/vendor/github.com/fnproject/fn_go/models/call_wrapper.go deleted file mode 100644 index f3d420d40..000000000 --- a/vendor/github.com/fnproject/fn_go/models/call_wrapper.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CallWrapper call wrapper -// swagger:model CallWrapper -type CallWrapper struct { - - // Call object. - // Required: true - Call *Call `json:"call"` -} - -// Validate validates this call wrapper -func (m *CallWrapper) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCall(formats); err != nil { - // prop - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CallWrapper) validateCall(formats strfmt.Registry) error { - - if err := validate.Required("call", "body", m.Call); err != nil { - return err - } - - if m.Call != nil { - - if err := m.Call.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("call") - } - return err - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CallWrapper) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CallWrapper) UnmarshalBinary(b []byte) error { - var res CallWrapper - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/calls_wrapper.go b/vendor/github.com/fnproject/fn_go/models/calls_wrapper.go deleted file mode 100644 index 3f21011f1..000000000 --- a/vendor/github.com/fnproject/fn_go/models/calls_wrapper.go +++ /dev/null @@ -1,118 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "strconv" - - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// CallsWrapper calls wrapper -// swagger:model CallsWrapper -type CallsWrapper struct { - - // calls - // Required: true - Calls []*Call `json:"calls"` - - // error - Error *ErrorBody `json:"error,omitempty"` - - // cursor to send with subsequent request to receive the next page, if non-empty - // Read Only: true - NextCursor string `json:"next_cursor,omitempty"` -} - -// Validate validates this calls wrapper -func (m *CallsWrapper) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCalls(formats); err != nil { - // prop - res = append(res, err) - } - - if err := m.validateError(formats); err != nil { - // prop - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *CallsWrapper) validateCalls(formats strfmt.Registry) error { - - if err := validate.Required("calls", "body", m.Calls); err != nil { - return err - } - - for i := 0; i < len(m.Calls); i++ { - - if swag.IsZero(m.Calls[i]) { // not required - continue - } - - if m.Calls[i] != nil { - - if err := m.Calls[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("calls" + "." + strconv.Itoa(i)) - } - return err - } - - } - - } - - return nil -} - -func (m *CallsWrapper) validateError(formats strfmt.Registry) error { - - if swag.IsZero(m.Error) { // not required - return nil - } - - if m.Error != nil { - - if err := m.Error.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("error") - } - return err - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *CallsWrapper) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *CallsWrapper) UnmarshalBinary(b []byte) error { - var res CallsWrapper - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/calls_wrapper_calls.go b/vendor/github.com/fnproject/fn_go/models/calls_wrapper_calls.go deleted file mode 100644 index 4b00fdca9..000000000 --- a/vendor/github.com/fnproject/fn_go/models/calls_wrapper_calls.go +++ /dev/null @@ -1,47 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "strconv" - - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" -) - -// CallsWrapperCalls calls wrapper calls -// swagger:model callsWrapperCalls -type CallsWrapperCalls []*Call - -// Validate validates this calls wrapper calls -func (m CallsWrapperCalls) Validate(formats strfmt.Registry) error { - var res []error - - for i := 0; i < len(m); i++ { - - if swag.IsZero(m[i]) { // not required - continue - } - - if m[i] != nil { - - if err := m[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName(strconv.Itoa(i)) - } - return err - } - } - - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/error.go b/vendor/github.com/fnproject/fn_go/models/error.go deleted file mode 100644 index 7959433fb..000000000 --- a/vendor/github.com/fnproject/fn_go/models/error.go +++ /dev/null @@ -1,74 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" -) - -// Error error -// swagger:model Error -type Error struct { - - // error - Error *ErrorBody `json:"error,omitempty"` -} - -// Validate validates this error -func (m *Error) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateError(formats); err != nil { - // prop - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Error) validateError(formats strfmt.Registry) error { - - if swag.IsZero(m.Error) { // not required - return nil - } - - if m.Error != nil { - - if err := m.Error.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("error") - } - return err - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Error) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Error) UnmarshalBinary(b []byte) error { - var res Error - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/error_body.go b/vendor/github.com/fnproject/fn_go/models/error_body.go deleted file mode 100644 index 2df71285c..000000000 --- a/vendor/github.com/fnproject/fn_go/models/error_body.go +++ /dev/null @@ -1,54 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" -) - -// ErrorBody error body -// swagger:model ErrorBody -type ErrorBody struct { - - // fields - // Read Only: true - Fields string `json:"fields,omitempty"` - - // message - // Read Only: true - Message string `json:"message,omitempty"` -} - -// Validate validates this error body -func (m *ErrorBody) Validate(formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *ErrorBody) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *ErrorBody) UnmarshalBinary(b []byte) error { - var res ErrorBody - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/log.go b/vendor/github.com/fnproject/fn_go/models/log.go deleted file mode 100644 index 429a6c74a..000000000 --- a/vendor/github.com/fnproject/fn_go/models/log.go +++ /dev/null @@ -1,52 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" -) - -// Log log -// swagger:model Log -type Log struct { - - // Call UUID ID - CallID string `json:"call_id,omitempty"` - - // log - Log string `json:"log,omitempty"` -} - -// Validate validates this log -func (m *Log) Validate(formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *Log) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Log) UnmarshalBinary(b []byte) error { - var res Log - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/log_wrapper.go b/vendor/github.com/fnproject/fn_go/models/log_wrapper.go deleted file mode 100644 index b0143fdc3..000000000 --- a/vendor/github.com/fnproject/fn_go/models/log_wrapper.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// LogWrapper log wrapper -// swagger:model LogWrapper -type LogWrapper struct { - - // Call log entry. - // Required: true - Log *Log `json:"log"` -} - -// Validate validates this log wrapper -func (m *LogWrapper) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateLog(formats); err != nil { - // prop - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *LogWrapper) validateLog(formats strfmt.Registry) error { - - if err := validate.Required("log", "body", m.Log); err != nil { - return err - } - - if m.Log != nil { - - if err := m.Log.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("log") - } - return err - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *LogWrapper) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *LogWrapper) UnmarshalBinary(b []byte) error { - var res LogWrapper - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/new_task.go b/vendor/github.com/fnproject/fn_go/models/new_task.go deleted file mode 100644 index e6ff866e7..000000000 --- a/vendor/github.com/fnproject/fn_go/models/new_task.go +++ /dev/null @@ -1,73 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// NewTask new task -// swagger:model NewTask - -type NewTask struct { - - // Name of Docker image to use. This is optional and can be used to override the image defined at the group level. - // Required: true - Image *string `json:"image"` - - // Payload for the task. This is what you pass into each task to make it do something. - Payload string `json:"payload,omitempty"` -} - -/* polymorph NewTask image false */ - -/* polymorph NewTask payload false */ - -// Validate validates this new task -func (m *NewTask) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateImage(formats); err != nil { - // prop - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *NewTask) validateImage(formats strfmt.Registry) error { - - if err := validate.Required("image", "body", m.Image); err != nil { - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *NewTask) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *NewTask) UnmarshalBinary(b []byte) error { - var res NewTask - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/route.go b/vendor/github.com/fnproject/fn_go/models/route.go deleted file mode 100644 index 4f1a25883..000000000 --- a/vendor/github.com/fnproject/fn_go/models/route.go +++ /dev/null @@ -1,240 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Route route -// swagger:model Route -type Route struct { - - // Route annotations - this is a map of annotations attached to this route, keys must not exceed 128 bytes and must consist of non-whitespace printable ascii characters, and the seralized representation of individual values must not exeed 512 bytes - Annotations map[string]interface{} `json:"annotations,omitempty"` - - // Route configuration - overrides application configuration - Config map[string]string `json:"config,omitempty"` - - // Max usable CPU cores for this route. Value in MilliCPUs (eg. 500m) or as floating-point (eg. 0.5) - Cpus string `json:"cpus,omitempty"` - - // Time when route was created. Always in UTC. - // Read Only: true - CreatedAt strfmt.DateTime `json:"created_at,omitempty"` - - // Payload format sent into function. - Format string `json:"format,omitempty"` - - // Map of http headers that will be sent with the response - Headers map[string][]string `json:"headers,omitempty"` - - // Hot functions idle timeout before termination. Value in Seconds - IDLETimeout *int32 `json:"idle_timeout,omitempty"` - - // Name of Docker image to use in this route. You should include the image tag, which should be a version number, to be more accurate. Can be overridden on a per route basis with route.image. - Image string `json:"image,omitempty"` - - // Max usable memory for this route (MiB). - Memory uint64 `json:"memory,omitempty"` - - // URL path that will be matched to this route - // Read Only: true - Path string `json:"path,omitempty"` - - // Timeout for executions of this route. Value in Seconds - Timeout *int32 `json:"timeout,omitempty"` - - // Route type - Type string `json:"type,omitempty"` - - // Most recent time that route was updated. Always in UTC. - // Read Only: true - UpdatedAt strfmt.DateTime `json:"updated_at,omitempty"` -} - -// Validate validates this route -func (m *Route) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateCreatedAt(formats); err != nil { - // prop - res = append(res, err) - } - - if err := m.validateFormat(formats); err != nil { - // prop - res = append(res, err) - } - - if err := m.validateHeaders(formats); err != nil { - // prop - res = append(res, err) - } - - if err := m.validateType(formats); err != nil { - // prop - res = append(res, err) - } - - if err := m.validateUpdatedAt(formats); err != nil { - // prop - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Route) validateCreatedAt(formats strfmt.Registry) error { - - if swag.IsZero(m.CreatedAt) { // not required - return nil - } - - if err := validate.FormatOf("created_at", "body", "date-time", m.CreatedAt.String(), formats); err != nil { - return err - } - - return nil -} - -var routeTypeFormatPropEnum []interface{} - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["default","http","json"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - routeTypeFormatPropEnum = append(routeTypeFormatPropEnum, v) - } -} - -const ( - - // RouteFormatDefault captures enum value "default" - RouteFormatDefault string = "default" - - // RouteFormatHTTP captures enum value "http" - RouteFormatHTTP string = "http" - - // RouteFormatJSON captures enum value "json" - RouteFormatJSON string = "json" -) - -// prop value enum -func (m *Route) validateFormatEnum(path, location string, value string) error { - if err := validate.Enum(path, location, value, routeTypeFormatPropEnum); err != nil { - return err - } - return nil -} - -func (m *Route) validateFormat(formats strfmt.Registry) error { - - if swag.IsZero(m.Format) { // not required - return nil - } - - // value enum - if err := m.validateFormatEnum("format", "body", m.Format); err != nil { - return err - } - - return nil -} - -func (m *Route) validateHeaders(formats strfmt.Registry) error { - - if swag.IsZero(m.Headers) { // not required - return nil - } - - return nil -} - -var routeTypeTypePropEnum []interface{} - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["sync","async"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - routeTypeTypePropEnum = append(routeTypeTypePropEnum, v) - } -} - -const ( - - // RouteTypeSync captures enum value "sync" - RouteTypeSync string = "sync" - - // RouteTypeAsync captures enum value "async" - RouteTypeAsync string = "async" -) - -// prop value enum -func (m *Route) validateTypeEnum(path, location string, value string) error { - if err := validate.Enum(path, location, value, routeTypeTypePropEnum); err != nil { - return err - } - return nil -} - -func (m *Route) validateType(formats strfmt.Registry) error { - - if swag.IsZero(m.Type) { // not required - return nil - } - - // value enum - if err := m.validateTypeEnum("type", "body", m.Type); err != nil { - return err - } - - return nil -} - -func (m *Route) validateUpdatedAt(formats strfmt.Registry) error { - - if swag.IsZero(m.UpdatedAt) { // not required - return nil - } - - if err := validate.FormatOf("updated_at", "body", "date-time", m.UpdatedAt.String(), formats); err != nil { - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Route) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Route) UnmarshalBinary(b []byte) error { - var res Route - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/route_wrapper.go b/vendor/github.com/fnproject/fn_go/models/route_wrapper.go deleted file mode 100644 index 2f2c38190..000000000 --- a/vendor/github.com/fnproject/fn_go/models/route_wrapper.go +++ /dev/null @@ -1,107 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// RouteWrapper route wrapper -// swagger:model RouteWrapper -type RouteWrapper struct { - - // error - Error *ErrorBody `json:"error,omitempty"` - - // message - Message string `json:"message,omitempty"` - - // route - // Required: true - Route *Route `json:"route"` -} - -// Validate validates this route wrapper -func (m *RouteWrapper) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateError(formats); err != nil { - // prop - res = append(res, err) - } - - if err := m.validateRoute(formats); err != nil { - // prop - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *RouteWrapper) validateError(formats strfmt.Registry) error { - - if swag.IsZero(m.Error) { // not required - return nil - } - - if m.Error != nil { - - if err := m.Error.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("error") - } - return err - } - - } - - return nil -} - -func (m *RouteWrapper) validateRoute(formats strfmt.Registry) error { - - if err := validate.Required("route", "body", m.Route); err != nil { - return err - } - - if m.Route != nil { - - if err := m.Route.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("route") - } - return err - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *RouteWrapper) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *RouteWrapper) UnmarshalBinary(b []byte) error { - var res RouteWrapper - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/routes_wrapper.go b/vendor/github.com/fnproject/fn_go/models/routes_wrapper.go deleted file mode 100644 index 5a0cfdaae..000000000 --- a/vendor/github.com/fnproject/fn_go/models/routes_wrapper.go +++ /dev/null @@ -1,118 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "strconv" - - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// RoutesWrapper routes wrapper -// swagger:model RoutesWrapper -type RoutesWrapper struct { - - // error - Error *ErrorBody `json:"error,omitempty"` - - // cursor to send with subsequent request to receive the next page, if non-empty - // Read Only: true - NextCursor string `json:"next_cursor,omitempty"` - - // routes - // Required: true - Routes []*Route `json:"routes"` -} - -// Validate validates this routes wrapper -func (m *RoutesWrapper) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateError(formats); err != nil { - // prop - res = append(res, err) - } - - if err := m.validateRoutes(formats); err != nil { - // prop - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *RoutesWrapper) validateError(formats strfmt.Registry) error { - - if swag.IsZero(m.Error) { // not required - return nil - } - - if m.Error != nil { - - if err := m.Error.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("error") - } - return err - } - - } - - return nil -} - -func (m *RoutesWrapper) validateRoutes(formats strfmt.Registry) error { - - if err := validate.Required("routes", "body", m.Routes); err != nil { - return err - } - - for i := 0; i < len(m.Routes); i++ { - - if swag.IsZero(m.Routes[i]) { // not required - continue - } - - if m.Routes[i] != nil { - - if err := m.Routes[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("routes" + "." + strconv.Itoa(i)) - } - return err - } - - } - - } - - return nil -} - -// MarshalBinary interface implementation -func (m *RoutesWrapper) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *RoutesWrapper) UnmarshalBinary(b []byte) error { - var res RoutesWrapper - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/routes_wrapper_routes.go b/vendor/github.com/fnproject/fn_go/models/routes_wrapper_routes.go deleted file mode 100644 index 57f486452..000000000 --- a/vendor/github.com/fnproject/fn_go/models/routes_wrapper_routes.go +++ /dev/null @@ -1,47 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "strconv" - - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" -) - -// RoutesWrapperRoutes routes wrapper routes -// swagger:model routesWrapperRoutes -type RoutesWrapperRoutes []*Route - -// Validate validates this routes wrapper routes -func (m RoutesWrapperRoutes) Validate(formats strfmt.Registry) error { - var res []error - - for i := 0; i < len(m); i++ { - - if swag.IsZero(m[i]) { // not required - continue - } - - if m[i] != nil { - - if err := m[i].Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName(strconv.Itoa(i)) - } - return err - } - } - - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/stat.go b/vendor/github.com/fnproject/fn_go/models/stat.go deleted file mode 100644 index f20958848..000000000 --- a/vendor/github.com/fnproject/fn_go/models/stat.go +++ /dev/null @@ -1,96 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Stat stat -// swagger:model Stat -type Stat struct { - - // metrics - Metrics *StatMetrics `json:"metrics,omitempty"` - - // timestamp - Timestamp strfmt.DateTime `json:"timestamp,omitempty"` -} - -// Validate validates this stat -func (m *Stat) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateMetrics(formats); err != nil { - // prop - res = append(res, err) - } - - if err := m.validateTimestamp(formats); err != nil { - // prop - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *Stat) validateMetrics(formats strfmt.Registry) error { - - if swag.IsZero(m.Metrics) { // not required - return nil - } - - if m.Metrics != nil { - - if err := m.Metrics.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("metrics") - } - return err - } - - } - - return nil -} - -func (m *Stat) validateTimestamp(formats strfmt.Registry) error { - - if swag.IsZero(m.Timestamp) { // not required - return nil - } - - if err := validate.FormatOf("timestamp", "body", "date-time", m.Timestamp.String(), formats); err != nil { - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Stat) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Stat) UnmarshalBinary(b []byte) error { - var res Stat - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/stat_metrics.go b/vendor/github.com/fnproject/fn_go/models/stat_metrics.go deleted file mode 100644 index 4382fdf96..000000000 --- a/vendor/github.com/fnproject/fn_go/models/stat_metrics.go +++ /dev/null @@ -1,73 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" -) - -// StatMetrics stat metrics -// swagger:model statMetrics -type StatMetrics struct { - - // cpu kernel - CPUKernel int64 `json:"cpu_kernel,omitempty"` - - // cpu total - CPUTotal int64 `json:"cpu_total,omitempty"` - - // cpu user - CPUUser int64 `json:"cpu_user,omitempty"` - - // disk read - DiskRead int64 `json:"disk_read,omitempty"` - - // disk write - DiskWrite int64 `json:"disk_write,omitempty"` - - // mem limit - MemLimit int64 `json:"mem_limit,omitempty"` - - // mem usage - MemUsage int64 `json:"mem_usage,omitempty"` - - // net rx - NetRx int64 `json:"net_rx,omitempty"` - - // net tx - NetTx int64 `json:"net_tx,omitempty"` -} - -// Validate validates this stat metrics -func (m *StatMetrics) Validate(formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *StatMetrics) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *StatMetrics) UnmarshalBinary(b []byte) error { - var res StatMetrics - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/task.go b/vendor/github.com/fnproject/fn_go/models/task.go deleted file mode 100644 index 7cde715e8..000000000 --- a/vendor/github.com/fnproject/fn_go/models/task.go +++ /dev/null @@ -1,238 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "encoding/json" - - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// Task task -// swagger:model Task - -type Task struct { - NewTask - - // Time when task completed, whether it was successul or failed. Always in UTC. - CompletedAt strfmt.DateTime `json:"completed_at,omitempty"` - - // Time when task was submitted. Always in UTC. - // Read Only: true - CreatedAt strfmt.DateTime `json:"created_at,omitempty"` - - // Env vars for the task. Comes from the ones set on the Group. - EnvVars map[string]string `json:"env_vars,omitempty"` - - // The error message, if status is 'error'. This is errors due to things outside the task itself. Errors from user code will be found in the log. - Error string `json:"error,omitempty"` - - // Group this task belongs to. - // Read Only: true - GroupName string `json:"group_name,omitempty"` - - // Machine usable reason for task being in this state. - // Valid values for error status are `timeout | killed | bad_exit`. - // Valid values for cancelled status are `client_request`. - // For everything else, this is undefined. - // - Reason string `json:"reason,omitempty"` - - // If this field is set, then this task was retried by the task referenced in this field. - // Read Only: true - RetryAt string `json:"retry_at,omitempty"` - - // If this field is set, then this task is a retry of the ID in this field. - // Read Only: true - RetryOf string `json:"retry_of,omitempty"` - - // Time when task started execution. Always in UTC. - StartedAt strfmt.DateTime `json:"started_at,omitempty"` -} - -// UnmarshalJSON unmarshals this object from a JSON structure -func (m *Task) UnmarshalJSON(raw []byte) error { - - var aO0 NewTask - if err := swag.ReadJSON(raw, &aO0); err != nil { - return err - } - m.NewTask = aO0 - - var data struct { - CompletedAt strfmt.DateTime `json:"completed_at,omitempty"` - - CreatedAt strfmt.DateTime `json:"created_at,omitempty"` - - EnvVars map[string]string `json:"env_vars,omitempty"` - - Error string `json:"error,omitempty"` - - GroupName string `json:"group_name,omitempty"` - - Reason string `json:"reason,omitempty"` - - RetryAt string `json:"retry_at,omitempty"` - - RetryOf string `json:"retry_of,omitempty"` - - StartedAt strfmt.DateTime `json:"started_at,omitempty"` - } - if err := swag.ReadJSON(raw, &data); err != nil { - return err - } - - m.CompletedAt = data.CompletedAt - - m.CreatedAt = data.CreatedAt - - m.EnvVars = data.EnvVars - - m.Error = data.Error - - m.GroupName = data.GroupName - - m.Reason = data.Reason - - m.RetryAt = data.RetryAt - - m.RetryOf = data.RetryOf - - m.StartedAt = data.StartedAt - - return nil -} - -// MarshalJSON marshals this object to a JSON structure -func (m Task) MarshalJSON() ([]byte, error) { - var _parts [][]byte - - aO0, err := swag.WriteJSON(m.NewTask) - if err != nil { - return nil, err - } - _parts = append(_parts, aO0) - - var data struct { - CompletedAt strfmt.DateTime `json:"completed_at,omitempty"` - - CreatedAt strfmt.DateTime `json:"created_at,omitempty"` - - EnvVars map[string]string `json:"env_vars,omitempty"` - - Error string `json:"error,omitempty"` - - GroupName string `json:"group_name,omitempty"` - - Reason string `json:"reason,omitempty"` - - RetryAt string `json:"retry_at,omitempty"` - - RetryOf string `json:"retry_of,omitempty"` - - StartedAt strfmt.DateTime `json:"started_at,omitempty"` - } - - data.CompletedAt = m.CompletedAt - - data.CreatedAt = m.CreatedAt - - data.EnvVars = m.EnvVars - - data.Error = m.Error - - data.GroupName = m.GroupName - - data.Reason = m.Reason - - data.RetryAt = m.RetryAt - - data.RetryOf = m.RetryOf - - data.StartedAt = m.StartedAt - - jsonData, err := swag.WriteJSON(data) - if err != nil { - return nil, err - } - _parts = append(_parts, jsonData) - - return swag.ConcatJSON(_parts...), nil -} - -// Validate validates this task -func (m *Task) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.NewTask.Validate(formats); err != nil { - res = append(res, err) - } - - if err := m.validateReason(formats); err != nil { - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -var taskTypeReasonPropEnum []interface{} - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["timeout","killed","bad_exit","client_request"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - taskTypeReasonPropEnum = append(taskTypeReasonPropEnum, v) - } -} - -// property enum -func (m *Task) validateReasonEnum(path, location string, value string) error { - if err := validate.Enum(path, location, value, taskTypeReasonPropEnum); err != nil { - return err - } - return nil -} - -func (m *Task) validateReason(formats strfmt.Registry) error { - - if swag.IsZero(m.Reason) { // not required - return nil - } - - // value enum - if err := m.validateReasonEnum("reason", "body", m.Reason); err != nil { - return err - } - - return nil -} - -// MarshalBinary interface implementation -func (m *Task) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Task) UnmarshalBinary(b []byte) error { - var res Task - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/task_wrapper.go b/vendor/github.com/fnproject/fn_go/models/task_wrapper.go deleted file mode 100644 index 399f3c0e1..000000000 --- a/vendor/github.com/fnproject/fn_go/models/task_wrapper.go +++ /dev/null @@ -1,78 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -// TaskWrapper task wrapper -// swagger:model TaskWrapper - -type TaskWrapper struct { - - // task - // Required: true - Task *Task `json:"task"` -} - -/* polymorph TaskWrapper task false */ - -// Validate validates this task wrapper -func (m *TaskWrapper) Validate(formats strfmt.Registry) error { - var res []error - - if err := m.validateTask(formats); err != nil { - // prop - res = append(res, err) - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -func (m *TaskWrapper) validateTask(formats strfmt.Registry) error { - - if err := validate.Required("task", "body", m.Task); err != nil { - return err - } - - if m.Task != nil { - - if err := m.Task.Validate(formats); err != nil { - if ve, ok := err.(*errors.Validation); ok { - return ve.ValidateName("task") - } - return err - } - } - - return nil -} - -// MarshalBinary interface implementation -func (m *TaskWrapper) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *TaskWrapper) UnmarshalBinary(b []byte) error { - var res TaskWrapper - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/fnproject/fn_go/models/version.go b/vendor/github.com/fnproject/fn_go/models/version.go deleted file mode 100644 index db845cf27..000000000 --- a/vendor/github.com/fnproject/fn_go/models/version.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -package models - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - strfmt "github.com/go-openapi/strfmt" - - "github.com/go-openapi/errors" - "github.com/go-openapi/swag" -) - -// Version version -// swagger:model Version -type Version struct { - - // version - // Read Only: true - Version string `json:"version,omitempty"` -} - -// Validate validates this version -func (m *Version) Validate(formats strfmt.Registry) error { - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// MarshalBinary interface implementation -func (m *Version) MarshalBinary() ([]byte, error) { - if m == nil { - return nil, nil - } - return swag.WriteJSON(m) -} - -// UnmarshalBinary interface implementation -func (m *Version) UnmarshalBinary(b []byte) error { - var res Version - if err := swag.ReadJSON(b, &res); err != nil { - return err - } - *m = res - return nil -} diff --git a/vendor/github.com/go-ini/ini/.travis.yml b/vendor/github.com/go-ini/ini/.travis.yml index 75fe7b74b..3cb77dc9a 100644 --- a/vendor/github.com/go-ini/ini/.travis.yml +++ b/vendor/github.com/go-ini/ini/.travis.yml @@ -13,4 +13,5 @@ script: - go get github.com/smartystreets/goconvey - mkdir -p $HOME/gopath/src/gopkg.in - ln -s $HOME/gopath/src/github.com/go-ini/ini $HOME/gopath/src/gopkg.in/ini.v1 + - cd $HOME/gopath/src/gopkg.in/ini.v1 - go test -v -cover -race diff --git a/vendor/github.com/go-ini/ini/README.md b/vendor/github.com/go-ini/ini/README.md index 6b7b73fed..95d920d6b 100644 --- a/vendor/github.com/go-ini/ini/README.md +++ b/vendor/github.com/go-ini/ini/README.md @@ -5,11 +5,9 @@ INI [![Build Status](https://travis-ci.org/go-ini/ini.svg?branch=master)](https: Package ini provides INI file read and write functionality in Go. -[简体中文](README_ZH.md) +## Features -## Feature - -- Load multiple data sources(`[]byte`, file and `io.ReadCloser`) with overwrites. +- Load from multiple data sources(`[]byte`, file and `io.ReadCloser`) with overwrites. - Read with recursion values. - Read with parent-child sections. - Read with auto-increment key names. @@ -24,766 +22,22 @@ Package ini provides INI file read and write functionality in Go. To use a tagged revision: - go get gopkg.in/ini.v1 +```sh +$ go get gopkg.in/ini.v1 +``` To use with latest changes: - go get github.com/go-ini/ini +```sh +$ go get github.com/go-ini/ini +``` Please add `-u` flag to update in the future. -### Testing - -If you want to test on your machine, please apply `-t` flag: - - go get -t gopkg.in/ini.v1 - -Please add `-u` flag to update in the future. - -## Getting Started - -### Loading from data sources - -A **Data Source** is either raw data in type `[]byte`, a file name with type `string` or `io.ReadCloser`. You can load **as many data sources as you want**. Passing other types will simply return an error. - -```go -cfg, err := ini.Load([]byte("raw data"), "filename", ioutil.NopCloser(bytes.NewReader([]byte("some other data")))) -``` - -Or start with an empty object: - -```go -cfg := ini.Empty() -``` - -When you cannot decide how many data sources to load at the beginning, you will still be able to **Append()** them later. - -```go -err := cfg.Append("other file", []byte("other raw data")) -``` - -If you have a list of files with possibilities that some of them may not available at the time, and you don't know exactly which ones, you can use `LooseLoad` to ignore nonexistent files without returning error. - -```go -cfg, err := ini.LooseLoad("filename", "filename_404") -``` - -The cool thing is, whenever the file is available to load while you're calling `Reload` method, it will be counted as usual. - -#### Ignore cases of key name - -When you do not care about cases of section and key names, you can use `InsensitiveLoad` to force all names to be lowercased while parsing. - -```go -cfg, err := ini.InsensitiveLoad("filename") -//... - -// sec1 and sec2 are the exactly same section object -sec1, err := cfg.GetSection("Section") -sec2, err := cfg.GetSection("SecTIOn") - -// key1 and key2 are the exactly same key object -key1, err := sec1.GetKey("Key") -key2, err := sec2.GetKey("KeY") -``` - -#### MySQL-like boolean key - -MySQL's configuration allows a key without value as follows: - -```ini -[mysqld] -... -skip-host-cache -skip-name-resolve -``` - -By default, this is considered as missing value. But if you know you're going to deal with those cases, you can assign advanced load options: - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{AllowBooleanKeys: true}, "my.cnf")) -``` - -The value of those keys are always `true`, and when you save to a file, it will keep in the same foramt as you read. - -To generate such keys in your program, you could use `NewBooleanKey`: - -```go -key, err := sec.NewBooleanKey("skip-host-cache") -``` - -#### Comment - -Take care that following format will be treated as comment: - -1. Line begins with `#` or `;` -2. Words after `#` or `;` -3. Words after section name (i.e words after `[some section name]`) - -If you want to save a value with `#` or `;`, please quote them with ``` ` ``` or ``` """ ```. - -Alternatively, you can use following `LoadOptions` to completely ignore inline comments: - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: true}, "app.ini")) -``` - -### Working with sections - -To get a section, you would need to: - -```go -section, err := cfg.GetSection("section name") -``` - -For a shortcut for default section, just give an empty string as name: - -```go -section, err := cfg.GetSection("") -``` - -When you're pretty sure the section exists, following code could make your life easier: - -```go -section := cfg.Section("section name") -``` - -What happens when the section somehow does not exist? Don't panic, it automatically creates and returns a new section to you. - -To create a new section: - -```go -err := cfg.NewSection("new section") -``` - -To get a list of sections or section names: - -```go -sections := cfg.Sections() -names := cfg.SectionStrings() -``` - -### Working with keys - -To get a key under a section: - -```go -key, err := cfg.Section("").GetKey("key name") -``` - -Same rule applies to key operations: - -```go -key := cfg.Section("").Key("key name") -``` - -To check if a key exists: - -```go -yes := cfg.Section("").HasKey("key name") -``` - -To create a new key: - -```go -err := cfg.Section("").NewKey("name", "value") -``` - -To get a list of keys or key names: - -```go -keys := cfg.Section("").Keys() -names := cfg.Section("").KeyStrings() -``` - -To get a clone hash of keys and corresponding values: - -```go -hash := cfg.Section("").KeysHash() -``` - -### Working with values - -To get a string value: - -```go -val := cfg.Section("").Key("key name").String() -``` - -To validate key value on the fly: - -```go -val := cfg.Section("").Key("key name").Validate(func(in string) string { - if len(in) == 0 { - return "default" - } - return in -}) -``` - -If you do not want any auto-transformation (such as recursive read) for the values, you can get raw value directly (this way you get much better performance): - -```go -val := cfg.Section("").Key("key name").Value() -``` - -To check if raw value exists: - -```go -yes := cfg.Section("").HasValue("test value") -``` - -To get value with types: - -```go -// For boolean values: -// true when value is: 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On -// false when value is: 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off -v, err = cfg.Section("").Key("BOOL").Bool() -v, err = cfg.Section("").Key("FLOAT64").Float64() -v, err = cfg.Section("").Key("INT").Int() -v, err = cfg.Section("").Key("INT64").Int64() -v, err = cfg.Section("").Key("UINT").Uint() -v, err = cfg.Section("").Key("UINT64").Uint64() -v, err = cfg.Section("").Key("TIME").TimeFormat(time.RFC3339) -v, err = cfg.Section("").Key("TIME").Time() // RFC3339 - -v = cfg.Section("").Key("BOOL").MustBool() -v = cfg.Section("").Key("FLOAT64").MustFloat64() -v = cfg.Section("").Key("INT").MustInt() -v = cfg.Section("").Key("INT64").MustInt64() -v = cfg.Section("").Key("UINT").MustUint() -v = cfg.Section("").Key("UINT64").MustUint64() -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339) -v = cfg.Section("").Key("TIME").MustTime() // RFC3339 - -// Methods start with Must also accept one argument for default value -// when key not found or fail to parse value to given type. -// Except method MustString, which you have to pass a default value. - -v = cfg.Section("").Key("String").MustString("default") -v = cfg.Section("").Key("BOOL").MustBool(true) -v = cfg.Section("").Key("FLOAT64").MustFloat64(1.25) -v = cfg.Section("").Key("INT").MustInt(10) -v = cfg.Section("").Key("INT64").MustInt64(99) -v = cfg.Section("").Key("UINT").MustUint(3) -v = cfg.Section("").Key("UINT64").MustUint64(6) -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339, time.Now()) -v = cfg.Section("").Key("TIME").MustTime(time.Now()) // RFC3339 -``` - -What if my value is three-line long? - -```ini -[advance] -ADDRESS = """404 road, -NotFound, State, 5000 -Earth""" -``` - -Not a problem! - -```go -cfg.Section("advance").Key("ADDRESS").String() - -/* --- start --- -404 road, -NotFound, State, 5000 -Earth ------- end --- */ -``` - -That's cool, how about continuation lines? - -```ini -[advance] -two_lines = how about \ - continuation lines? -lots_of_lines = 1 \ - 2 \ - 3 \ - 4 -``` - -Piece of cake! - -```go -cfg.Section("advance").Key("two_lines").String() // how about continuation lines? -cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4 -``` - -Well, I hate continuation lines, how do I disable that? - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{ - IgnoreContinuation: true, -}, "filename") -``` - -Holy crap! - -Note that single quotes around values will be stripped: - -```ini -foo = "some value" // foo: some value -bar = 'some value' // bar: some value -``` - -Sometimes you downloaded file from [Crowdin](https://crowdin.com/) has values like the following (value is surrounded by double quotes and quotes in the value are escaped): - -```ini -create_repo="created repository %s" -``` - -How do you transform this to regular format automatically? - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{UnescapeValueDoubleQuotes: true}, "en-US.ini")) -cfg.Section("").Key("create_repo").String() -// You got: created repository %s -``` - -That's all? Hmm, no. - -#### Helper methods of working with values - -To get value with given candidates: - -```go -v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"}) -v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75}) -v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30}) -v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30}) -v = cfg.Section("").Key("UINT").InUint(4, []int{3, 6, 9}) -v = cfg.Section("").Key("UINT64").InUint64(8, []int64{3, 6, 9}) -v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3}) -v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339 -``` - -Default value will be presented if value of key is not in candidates you given, and default value does not need be one of candidates. - -To validate value in a given range: - -```go -vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2) -vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20) -vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20) -vals = cfg.Section("").Key("UINT").RangeUint(0, 3, 9) -vals = cfg.Section("").Key("UINT64").RangeUint64(0, 3, 9) -vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime) -vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339 -``` - -##### Auto-split values into a slice - -To use zero value of type for invalid inputs: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [0.0 2.2 0.0 0.0] -vals = cfg.Section("").Key("STRINGS").Strings(",") -vals = cfg.Section("").Key("FLOAT64S").Float64s(",") -vals = cfg.Section("").Key("INTS").Ints(",") -vals = cfg.Section("").Key("INT64S").Int64s(",") -vals = cfg.Section("").Key("UINTS").Uints(",") -vals = cfg.Section("").Key("UINT64S").Uint64s(",") -vals = cfg.Section("").Key("TIMES").Times(",") -``` - -To exclude invalid values out of result slice: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [2.2] -vals = cfg.Section("").Key("FLOAT64S").ValidFloat64s(",") -vals = cfg.Section("").Key("INTS").ValidInts(",") -vals = cfg.Section("").Key("INT64S").ValidInt64s(",") -vals = cfg.Section("").Key("UINTS").ValidUints(",") -vals = cfg.Section("").Key("UINT64S").ValidUint64s(",") -vals = cfg.Section("").Key("TIMES").ValidTimes(",") -``` - -Or to return nothing but error when have invalid inputs: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> error -vals = cfg.Section("").Key("FLOAT64S").StrictFloat64s(",") -vals = cfg.Section("").Key("INTS").StrictInts(",") -vals = cfg.Section("").Key("INT64S").StrictInt64s(",") -vals = cfg.Section("").Key("UINTS").StrictUints(",") -vals = cfg.Section("").Key("UINT64S").StrictUint64s(",") -vals = cfg.Section("").Key("TIMES").StrictTimes(",") -``` - -### Save your configuration - -Finally, it's time to save your configuration to somewhere. - -A typical way to save configuration is writing it to a file: - -```go -// ... -err = cfg.SaveTo("my.ini") -err = cfg.SaveToIndent("my.ini", "\t") -``` - -Another way to save is writing to a `io.Writer` interface: - -```go -// ... -cfg.WriteTo(writer) -cfg.WriteToIndent(writer, "\t") -``` - -By default, spaces are used to align "=" sign between key and values, to disable that: - -```go -ini.PrettyFormat = false -``` - -## Advanced Usage - -### Recursive Values - -For all value of keys, there is a special syntax `%()s`, where `` is the key name in same section or default section, and `%()s` will be replaced by corresponding value(empty string if key not found). You can use this syntax at most 99 level of recursions. - -```ini -NAME = ini - -[author] -NAME = Unknwon -GITHUB = https://github.com/%(NAME)s - -[package] -FULL_NAME = github.com/go-ini/%(NAME)s -``` - -```go -cfg.Section("author").Key("GITHUB").String() // https://github.com/Unknwon -cfg.Section("package").Key("FULL_NAME").String() // github.com/go-ini/ini -``` - -### Parent-child Sections - -You can use `.` in section name to indicate parent-child relationship between two or more sections. If the key not found in the child section, library will try again on its parent section until there is no parent section. - -```ini -NAME = ini -VERSION = v1 -IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s - -[package] -CLONE_URL = https://%(IMPORT_PATH)s - -[package.sub] -``` - -```go -cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1 -``` - -#### Retrieve parent keys available to a child section - -```go -cfg.Section("package.sub").ParentKeys() // ["CLONE_URL"] -``` - -### Same Key with Multiple Values - -Do you ever have a configuration file like this? - -```ini -[remote "origin"] -url = https://github.com/Antergone/test1.git -url = https://github.com/Antergone/test2.git -fetch = +refs/heads/*:refs/remotes/origin/* -``` - -By default, only the last read value will be kept for the key `url`. If you want to keep all copies of value of this key, you can use `ShadowLoad` to achieve it: - -```go -cfg, err := ini.ShadowLoad(".gitconfig") -// ... - -f.Section(`remote "origin"`).Key("url").String() -// Result: https://github.com/Antergone/test1.git - -f.Section(`remote "origin"`).Key("url").ValueWithShadows() -// Result: []string{ -// "https://github.com/Antergone/test1.git", -// "https://github.com/Antergone/test2.git", -// } -``` - -### Unparseable Sections - -Sometimes, you have sections that do not contain key-value pairs but raw content, to handle such case, you can use `LoadOptions.UnparsableSections`: - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{UnparseableSections: []string{"COMMENTS"}}, `[COMMENTS] -<1> This slide has the fuel listed in the wrong units `)) - -body := cfg.Section("COMMENTS").Body() - -/* --- start --- -<1> This slide has the fuel listed in the wrong units ------- end --- */ -``` - -### Auto-increment Key Names - -If key name is `-` in data source, then it would be seen as special syntax for auto-increment key name start from 1, and every section is independent on counter. - -```ini -[features] --: Support read/write comments of keys and sections --: Support auto-increment of key names --: Support load multiple files to overwrite key values -``` - -```go -cfg.Section("features").KeyStrings() // []{"#1", "#2", "#3"} -``` - -### Map To Struct - -Want more objective way to play with INI? Cool. - -```ini -Name = Unknwon -age = 21 -Male = true -Born = 1993-01-01T20:17:05Z - -[Note] -Content = Hi is a good man! -Cities = HangZhou, Boston -``` - -```go -type Note struct { - Content string - Cities []string -} - -type Person struct { - Name string - Age int `ini:"age"` - Male bool - Born time.Time - Note - Created time.Time `ini:"-"` -} - -func main() { - cfg, err := ini.Load("path/to/ini") - // ... - p := new(Person) - err = cfg.MapTo(p) - // ... - - // Things can be simpler. - err = ini.MapTo(p, "path/to/ini") - // ... - - // Just map a section? Fine. - n := new(Note) - err = cfg.Section("Note").MapTo(n) - // ... -} -``` - -Can I have default value for field? Absolutely. - -Assign it before you map to struct. It will keep the value as it is if the key is not presented or got wrong type. - -```go -// ... -p := &Person{ - Name: "Joe", -} -// ... -``` - -It's really cool, but what's the point if you can't give me my file back from struct? - -### Reflect From Struct - -Why not? - -```go -type Embeded struct { - Dates []time.Time `delim:"|" comment:"Time data"` - Places []string `ini:"places,omitempty"` - None []int `ini:",omitempty"` -} - -type Author struct { - Name string `ini:"NAME"` - Male bool - Age int `comment:"Author's age"` - GPA float64 - NeverMind string `ini:"-"` - *Embeded `comment:"Embeded section"` -} - -func main() { - a := &Author{"Unknwon", true, 21, 2.8, "", - &Embeded{ - []time.Time{time.Now(), time.Now()}, - []string{"HangZhou", "Boston"}, - []int{}, - }} - cfg := ini.Empty() - err = ini.ReflectFrom(cfg, a) - // ... -} -``` - -So, what do I get? - -```ini -NAME = Unknwon -Male = true -; Author's age -Age = 21 -GPA = 2.8 - -; Embeded section -[Embeded] -; Time data -Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00 -places = HangZhou,Boston -``` - -#### Name Mapper - -To save your time and make your code cleaner, this library supports [`NameMapper`](https://gowalker.org/gopkg.in/ini.v1#NameMapper) between struct field and actual section and key name. - -There are 2 built-in name mappers: - -- `AllCapsUnderscore`: it converts to format `ALL_CAPS_UNDERSCORE` then match section or key. -- `TitleUnderscore`: it converts to format `title_underscore` then match section or key. - -To use them: - -```go -type Info struct { - PackageName string -} - -func main() { - err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("package_name=ini")) - // ... - - cfg, err := ini.Load([]byte("PACKAGE_NAME=ini")) - // ... - info := new(Info) - cfg.NameMapper = ini.AllCapsUnderscore - err = cfg.MapTo(info) - // ... -} -``` - -Same rules of name mapper apply to `ini.ReflectFromWithMapper` function. - -#### Value Mapper - -To expand values (e.g. from environment variables), you can use the `ValueMapper` to transform values: - -```go -type Env struct { - Foo string `ini:"foo"` -} - -func main() { - cfg, err := ini.Load([]byte("[env]\nfoo = ${MY_VAR}\n") - cfg.ValueMapper = os.ExpandEnv - // ... - env := &Env{} - err = cfg.Section("env").MapTo(env) -} -``` - -This would set the value of `env.Foo` to the value of the environment variable `MY_VAR`. - -#### Other Notes On Map/Reflect - -Any embedded struct is treated as a section by default, and there is no automatic parent-child relations in map/reflect feature: - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child -} - -type Config struct { - City string - Parent -} -``` - -Example configuration: - -```ini -City = Boston - -[Parent] -Name = Unknwon - -[Child] -Age = 21 -``` - -What if, yes, I'm paranoid, I want embedded struct to be in the same section. Well, all roads lead to Rome. - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child `ini:"Parent"` -} - -type Config struct { - City string - Parent -} -``` - -Example configuration: - -```ini -City = Boston - -[Parent] -Name = Unknwon -Age = 21 -``` - ## Getting Help +- [Getting Started](https://ini.unknwon.io/docs/intro/getting_started) - [API Documentation](https://gowalker.org/gopkg.in/ini.v1) -- [File An Issue](https://github.com/go-ini/ini/issues/new) - -## FAQs - -### What does `BlockMode` field do? - -By default, library lets you read and write values so we need a locker to make sure your data is safe. But in cases that you are very sure about only reading data through the library, you can set `cfg.BlockMode = false` to speed up read operations about **50-70%** faster. - -### Why another INI library? - -Many people are using my another INI library [goconfig](https://github.com/Unknwon/goconfig), so the reason for this one is I would like to make more Go style code. Also when you set `cfg.BlockMode = false`, this one is about **10-30%** faster. - -To make those changes I have to confirm API broken, so it's safer to keep it in another place and start using `gopkg.in` to version my package at this time.(PS: shorter import path) ## License diff --git a/vendor/github.com/go-ini/ini/README_ZH.md b/vendor/github.com/go-ini/ini/README_ZH.md deleted file mode 100644 index 67a536302..000000000 --- a/vendor/github.com/go-ini/ini/README_ZH.md +++ /dev/null @@ -1,777 +0,0 @@ -本包提供了 Go 语言中读写 INI 文件的功能。 - -## 功能特性 - -- 支持覆盖加载多个数据源(`[]byte`、文件和 `io.ReadCloser`) -- 支持递归读取键值 -- 支持读取父子分区 -- 支持读取自增键名 -- 支持读取多行的键值 -- 支持大量辅助方法 -- 支持在读取时直接转换为 Go 语言类型 -- 支持读取和 **写入** 分区和键的注释 -- 轻松操作分区、键值和注释 -- 在保存文件时分区和键值会保持原有的顺序 - -## 下载安装 - -使用一个特定版本: - - go get gopkg.in/ini.v1 - -使用最新版: - - go get github.com/go-ini/ini - -如需更新请添加 `-u` 选项。 - -### 测试安装 - -如果您想要在自己的机器上运行测试,请使用 `-t` 标记: - - go get -t gopkg.in/ini.v1 - -如需更新请添加 `-u` 选项。 - -## 开始使用 - -### 从数据源加载 - -一个 **数据源** 可以是 `[]byte` 类型的原始数据,`string` 类型的文件路径或 `io.ReadCloser`。您可以加载 **任意多个** 数据源。如果您传递其它类型的数据源,则会直接返回错误。 - -```go -cfg, err := ini.Load([]byte("raw data"), "filename", ioutil.NopCloser(bytes.NewReader([]byte("some other data")))) -``` - -或者从一个空白的文件开始: - -```go -cfg := ini.Empty() -``` - -当您在一开始无法决定需要加载哪些数据源时,仍可以使用 **Append()** 在需要的时候加载它们。 - -```go -err := cfg.Append("other file", []byte("other raw data")) -``` - -当您想要加载一系列文件,但是不能够确定其中哪些文件是不存在的,可以通过调用函数 `LooseLoad` 来忽略它们(`Load` 会因为文件不存在而返回错误): - -```go -cfg, err := ini.LooseLoad("filename", "filename_404") -``` - -更牛逼的是,当那些之前不存在的文件在重新调用 `Reload` 方法的时候突然出现了,那么它们会被正常加载。 - -#### 忽略键名的大小写 - -有时候分区和键的名称大小写混合非常烦人,这个时候就可以通过 `InsensitiveLoad` 将所有分区和键名在读取里强制转换为小写: - -```go -cfg, err := ini.InsensitiveLoad("filename") -//... - -// sec1 和 sec2 指向同一个分区对象 -sec1, err := cfg.GetSection("Section") -sec2, err := cfg.GetSection("SecTIOn") - -// key1 和 key2 指向同一个键对象 -key1, err := sec1.GetKey("Key") -key2, err := sec2.GetKey("KeY") -``` - -#### 类似 MySQL 配置中的布尔值键 - -MySQL 的配置文件中会出现没有具体值的布尔类型的键: - -```ini -[mysqld] -... -skip-host-cache -skip-name-resolve -``` - -默认情况下这被认为是缺失值而无法完成解析,但可以通过高级的加载选项对它们进行处理: - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{AllowBooleanKeys: true}, "my.cnf")) -``` - -这些键的值永远为 `true`,且在保存到文件时也只会输出键名。 - -如果您想要通过程序来生成此类键,则可以使用 `NewBooleanKey`: - -```go -key, err := sec.NewBooleanKey("skip-host-cache") -``` - -#### 关于注释 - -下述几种情况的内容将被视为注释: - -1. 所有以 `#` 或 `;` 开头的行 -2. 所有在 `#` 或 `;` 之后的内容 -3. 分区标签后的文字 (即 `[分区名]` 之后的内容) - -如果你希望使用包含 `#` 或 `;` 的值,请使用 ``` ` ``` 或 ``` """ ``` 进行包覆。 - -除此之外,您还可以通过 `LoadOptions` 完全忽略行内注释: - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: true}, "app.ini")) -``` - -### 操作分区(Section) - -获取指定分区: - -```go -section, err := cfg.GetSection("section name") -``` - -如果您想要获取默认分区,则可以用空字符串代替分区名: - -```go -section, err := cfg.GetSection("") -``` - -当您非常确定某个分区是存在的,可以使用以下简便方法: - -```go -section := cfg.Section("section name") -``` - -如果不小心判断错了,要获取的分区其实是不存在的,那会发生什么呢?没事的,它会自动创建并返回一个对应的分区对象给您。 - -创建一个分区: - -```go -err := cfg.NewSection("new section") -``` - -获取所有分区对象或名称: - -```go -sections := cfg.Sections() -names := cfg.SectionStrings() -``` - -### 操作键(Key) - -获取某个分区下的键: - -```go -key, err := cfg.Section("").GetKey("key name") -``` - -和分区一样,您也可以直接获取键而忽略错误处理: - -```go -key := cfg.Section("").Key("key name") -``` - -判断某个键是否存在: - -```go -yes := cfg.Section("").HasKey("key name") -``` - -创建一个新的键: - -```go -err := cfg.Section("").NewKey("name", "value") -``` - -获取分区下的所有键或键名: - -```go -keys := cfg.Section("").Keys() -names := cfg.Section("").KeyStrings() -``` - -获取分区下的所有键值对的克隆: - -```go -hash := cfg.Section("").KeysHash() -``` - -### 操作键值(Value) - -获取一个类型为字符串(string)的值: - -```go -val := cfg.Section("").Key("key name").String() -``` - -获取值的同时通过自定义函数进行处理验证: - -```go -val := cfg.Section("").Key("key name").Validate(func(in string) string { - if len(in) == 0 { - return "default" - } - return in -}) -``` - -如果您不需要任何对值的自动转变功能(例如递归读取),可以直接获取原值(这种方式性能最佳): - -```go -val := cfg.Section("").Key("key name").Value() -``` - -判断某个原值是否存在: - -```go -yes := cfg.Section("").HasValue("test value") -``` - -获取其它类型的值: - -```go -// 布尔值的规则: -// true 当值为:1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On -// false 当值为:0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off -v, err = cfg.Section("").Key("BOOL").Bool() -v, err = cfg.Section("").Key("FLOAT64").Float64() -v, err = cfg.Section("").Key("INT").Int() -v, err = cfg.Section("").Key("INT64").Int64() -v, err = cfg.Section("").Key("UINT").Uint() -v, err = cfg.Section("").Key("UINT64").Uint64() -v, err = cfg.Section("").Key("TIME").TimeFormat(time.RFC3339) -v, err = cfg.Section("").Key("TIME").Time() // RFC3339 - -v = cfg.Section("").Key("BOOL").MustBool() -v = cfg.Section("").Key("FLOAT64").MustFloat64() -v = cfg.Section("").Key("INT").MustInt() -v = cfg.Section("").Key("INT64").MustInt64() -v = cfg.Section("").Key("UINT").MustUint() -v = cfg.Section("").Key("UINT64").MustUint64() -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339) -v = cfg.Section("").Key("TIME").MustTime() // RFC3339 - -// 由 Must 开头的方法名允许接收一个相同类型的参数来作为默认值, -// 当键不存在或者转换失败时,则会直接返回该默认值。 -// 但是,MustString 方法必须传递一个默认值。 - -v = cfg.Seciont("").Key("String").MustString("default") -v = cfg.Section("").Key("BOOL").MustBool(true) -v = cfg.Section("").Key("FLOAT64").MustFloat64(1.25) -v = cfg.Section("").Key("INT").MustInt(10) -v = cfg.Section("").Key("INT64").MustInt64(99) -v = cfg.Section("").Key("UINT").MustUint(3) -v = cfg.Section("").Key("UINT64").MustUint64(6) -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339, time.Now()) -v = cfg.Section("").Key("TIME").MustTime(time.Now()) // RFC3339 -``` - -如果我的值有好多行怎么办? - -```ini -[advance] -ADDRESS = """404 road, -NotFound, State, 5000 -Earth""" -``` - -嗯哼?小 case! - -```go -cfg.Section("advance").Key("ADDRESS").String() - -/* --- start --- -404 road, -NotFound, State, 5000 -Earth ------- end --- */ -``` - -赞爆了!那要是我属于一行的内容写不下想要写到第二行怎么办? - -```ini -[advance] -two_lines = how about \ - continuation lines? -lots_of_lines = 1 \ - 2 \ - 3 \ - 4 -``` - -简直是小菜一碟! - -```go -cfg.Section("advance").Key("two_lines").String() // how about continuation lines? -cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4 -``` - -可是我有时候觉得两行连在一起特别没劲,怎么才能不自动连接两行呢? - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{ - IgnoreContinuation: true, -}, "filename") -``` - -哇靠给力啊! - -需要注意的是,值两侧的单引号会被自动剔除: - -```ini -foo = "some value" // foo: some value -bar = 'some value' // bar: some value -``` - -有时您会获得像从 [Crowdin](https://crowdin.com/) 网站下载的文件那样具有特殊格式的值(值使用双引号括起来,内部的双引号被转义): - -```ini -create_repo="创建了仓库 %s" -``` - -那么,怎么自动地将这类值进行处理呢? - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{UnescapeValueDoubleQuotes: true}, "en-US.ini")) -cfg.Section("").Key("create_repo").String() -// You got: 创建了仓库 %s -``` - -这就是全部了?哈哈,当然不是。 - -#### 操作键值的辅助方法 - -获取键值时设定候选值: - -```go -v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"}) -v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75}) -v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30}) -v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30}) -v = cfg.Section("").Key("UINT").InUint(4, []int{3, 6, 9}) -v = cfg.Section("").Key("UINT64").InUint64(8, []int64{3, 6, 9}) -v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3}) -v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339 -``` - -如果获取到的值不是候选值的任意一个,则会返回默认值,而默认值不需要是候选值中的一员。 - -验证获取的值是否在指定范围内: - -```go -vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2) -vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20) -vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20) -vals = cfg.Section("").Key("UINT").RangeUint(0, 3, 9) -vals = cfg.Section("").Key("UINT64").RangeUint64(0, 3, 9) -vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime) -vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339 -``` - -##### 自动分割键值到切片(slice) - -当存在无效输入时,使用零值代替: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [0.0 2.2 0.0 0.0] -vals = cfg.Section("").Key("STRINGS").Strings(",") -vals = cfg.Section("").Key("FLOAT64S").Float64s(",") -vals = cfg.Section("").Key("INTS").Ints(",") -vals = cfg.Section("").Key("INT64S").Int64s(",") -vals = cfg.Section("").Key("UINTS").Uints(",") -vals = cfg.Section("").Key("UINT64S").Uint64s(",") -vals = cfg.Section("").Key("TIMES").Times(",") -``` - -从结果切片中剔除无效输入: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [2.2] -vals = cfg.Section("").Key("FLOAT64S").ValidFloat64s(",") -vals = cfg.Section("").Key("INTS").ValidInts(",") -vals = cfg.Section("").Key("INT64S").ValidInt64s(",") -vals = cfg.Section("").Key("UINTS").ValidUints(",") -vals = cfg.Section("").Key("UINT64S").ValidUint64s(",") -vals = cfg.Section("").Key("TIMES").ValidTimes(",") -``` - -当存在无效输入时,直接返回错误: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> error -vals = cfg.Section("").Key("FLOAT64S").StrictFloat64s(",") -vals = cfg.Section("").Key("INTS").StrictInts(",") -vals = cfg.Section("").Key("INT64S").StrictInt64s(",") -vals = cfg.Section("").Key("UINTS").StrictUints(",") -vals = cfg.Section("").Key("UINT64S").StrictUint64s(",") -vals = cfg.Section("").Key("TIMES").StrictTimes(",") -``` - -### 保存配置 - -终于到了这个时刻,是时候保存一下配置了。 - -比较原始的做法是输出配置到某个文件: - -```go -// ... -err = cfg.SaveTo("my.ini") -err = cfg.SaveToIndent("my.ini", "\t") -``` - -另一个比较高级的做法是写入到任何实现 `io.Writer` 接口的对象中: - -```go -// ... -cfg.WriteTo(writer) -cfg.WriteToIndent(writer, "\t") -``` - -默认情况下,空格将被用于对齐键值之间的等号以美化输出结果,以下代码可以禁用该功能: - -```go -ini.PrettyFormat = false -``` - -## 高级用法 - -### 递归读取键值 - -在获取所有键值的过程中,特殊语法 `%()s` 会被应用,其中 `` 可以是相同分区或者默认分区下的键名。字符串 `%()s` 会被相应的键值所替代,如果指定的键不存在,则会用空字符串替代。您可以最多使用 99 层的递归嵌套。 - -```ini -NAME = ini - -[author] -NAME = Unknwon -GITHUB = https://github.com/%(NAME)s - -[package] -FULL_NAME = github.com/go-ini/%(NAME)s -``` - -```go -cfg.Section("author").Key("GITHUB").String() // https://github.com/Unknwon -cfg.Section("package").Key("FULL_NAME").String() // github.com/go-ini/ini -``` - -### 读取父子分区 - -您可以在分区名称中使用 `.` 来表示两个或多个分区之间的父子关系。如果某个键在子分区中不存在,则会去它的父分区中再次寻找,直到没有父分区为止。 - -```ini -NAME = ini -VERSION = v1 -IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s - -[package] -CLONE_URL = https://%(IMPORT_PATH)s - -[package.sub] -``` - -```go -cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1 -``` - -#### 获取上级父分区下的所有键名 - -```go -cfg.Section("package.sub").ParentKeys() // ["CLONE_URL"] -``` - -### 同个键名包含多个值 - -你是否也曾被下面的配置文件所困扰? - -```ini -[remote "origin"] -url = https://github.com/Antergone/test1.git -url = https://github.com/Antergone/test2.git -fetch = +refs/heads/*:refs/remotes/origin/* -``` - -没错!默认情况下,只有最后一次出现的值会被保存到 `url` 中,可我就是想要保留所有的值怎么办啊?不要紧,用 `ShadowLoad` 轻松解决你的烦恼: - -```go -cfg, err := ini.ShadowLoad(".gitconfig") -// ... - -f.Section(`remote "origin"`).Key("url").String() -// Result: https://github.com/Antergone/test1.git - -f.Section(`remote "origin"`).Key("url").ValueWithShadows() -// Result: []string{ -// "https://github.com/Antergone/test1.git", -// "https://github.com/Antergone/test2.git", -// } -``` - -### 无法解析的分区 - -如果遇到一些比较特殊的分区,它们不包含常见的键值对,而是没有固定格式的纯文本,则可以使用 `LoadOptions.UnparsableSections` 进行处理: - -```go -cfg, err := LoadSources(ini.LoadOptions{UnparseableSections: []string{"COMMENTS"}}, `[COMMENTS] -<1> This slide has the fuel listed in the wrong units `)) - -body := cfg.Section("COMMENTS").Body() - -/* --- start --- -<1> This slide has the fuel listed in the wrong units ------- end --- */ -``` - -### 读取自增键名 - -如果数据源中的键名为 `-`,则认为该键使用了自增键名的特殊语法。计数器从 1 开始,并且分区之间是相互独立的。 - -```ini -[features] --: Support read/write comments of keys and sections --: Support auto-increment of key names --: Support load multiple files to overwrite key values -``` - -```go -cfg.Section("features").KeyStrings() // []{"#1", "#2", "#3"} -``` - -### 映射到结构 - -想要使用更加面向对象的方式玩转 INI 吗?好主意。 - -```ini -Name = Unknwon -age = 21 -Male = true -Born = 1993-01-01T20:17:05Z - -[Note] -Content = Hi is a good man! -Cities = HangZhou, Boston -``` - -```go -type Note struct { - Content string - Cities []string -} - -type Person struct { - Name string - Age int `ini:"age"` - Male bool - Born time.Time - Note - Created time.Time `ini:"-"` -} - -func main() { - cfg, err := ini.Load("path/to/ini") - // ... - p := new(Person) - err = cfg.MapTo(p) - // ... - - // 一切竟可以如此的简单。 - err = ini.MapTo(p, "path/to/ini") - // ... - - // 嗯哼?只需要映射一个分区吗? - n := new(Note) - err = cfg.Section("Note").MapTo(n) - // ... -} -``` - -结构的字段怎么设置默认值呢?很简单,只要在映射之前对指定字段进行赋值就可以了。如果键未找到或者类型错误,该值不会发生改变。 - -```go -// ... -p := &Person{ - Name: "Joe", -} -// ... -``` - -这样玩 INI 真的好酷啊!然而,如果不能还给我原来的配置文件,有什么卵用? - -### 从结构反射 - -可是,我有说不能吗? - -```go -type Embeded struct { - Dates []time.Time `delim:"|" comment:"Time data"` - Places []string `ini:"places,omitempty"` - None []int `ini:",omitempty"` -} - -type Author struct { - Name string `ini:"NAME"` - Male bool - Age int `comment:"Author's age"` - GPA float64 - NeverMind string `ini:"-"` - *Embeded `comment:"Embeded section"` -} - -func main() { - a := &Author{"Unknwon", true, 21, 2.8, "", - &Embeded{ - []time.Time{time.Now(), time.Now()}, - []string{"HangZhou", "Boston"}, - []int{}, - }} - cfg := ini.Empty() - err = ini.ReflectFrom(cfg, a) - // ... -} -``` - -瞧瞧,奇迹发生了。 - -```ini -NAME = Unknwon -Male = true -; Author's age -Age = 21 -GPA = 2.8 - -; Embeded section -[Embeded] -; Time data -Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00 -places = HangZhou,Boston -``` - -#### 名称映射器(Name Mapper) - -为了节省您的时间并简化代码,本库支持类型为 [`NameMapper`](https://gowalker.org/gopkg.in/ini.v1#NameMapper) 的名称映射器,该映射器负责结构字段名与分区名和键名之间的映射。 - -目前有 2 款内置的映射器: - -- `AllCapsUnderscore`:该映射器将字段名转换至格式 `ALL_CAPS_UNDERSCORE` 后再去匹配分区名和键名。 -- `TitleUnderscore`:该映射器将字段名转换至格式 `title_underscore` 后再去匹配分区名和键名。 - -使用方法: - -```go -type Info struct{ - PackageName string -} - -func main() { - err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("package_name=ini")) - // ... - - cfg, err := ini.Load([]byte("PACKAGE_NAME=ini")) - // ... - info := new(Info) - cfg.NameMapper = ini.AllCapsUnderscore - err = cfg.MapTo(info) - // ... -} -``` - -使用函数 `ini.ReflectFromWithMapper` 时也可应用相同的规则。 - -#### 值映射器(Value Mapper) - -值映射器允许使用一个自定义函数自动展开值的具体内容,例如:运行时获取环境变量: - -```go -type Env struct { - Foo string `ini:"foo"` -} - -func main() { - cfg, err := ini.Load([]byte("[env]\nfoo = ${MY_VAR}\n") - cfg.ValueMapper = os.ExpandEnv - // ... - env := &Env{} - err = cfg.Section("env").MapTo(env) -} -``` - -本例中,`env.Foo` 将会是运行时所获取到环境变量 `MY_VAR` 的值。 - -#### 映射/反射的其它说明 - -任何嵌入的结构都会被默认认作一个不同的分区,并且不会自动产生所谓的父子分区关联: - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child -} - -type Config struct { - City string - Parent -} -``` - -示例配置文件: - -```ini -City = Boston - -[Parent] -Name = Unknwon - -[Child] -Age = 21 -``` - -很好,但是,我就是要嵌入结构也在同一个分区。好吧,你爹是李刚! - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child `ini:"Parent"` -} - -type Config struct { - City string - Parent -} -``` - -示例配置文件: - -```ini -City = Boston - -[Parent] -Name = Unknwon -Age = 21 -``` - -## 获取帮助 - -- [API 文档](https://gowalker.org/gopkg.in/ini.v1) -- [创建工单](https://github.com/go-ini/ini/issues/new) - -## 常见问题 - -### 字段 `BlockMode` 是什么? - -默认情况下,本库会在您进行读写操作时采用锁机制来确保数据时间。但在某些情况下,您非常确定只进行读操作。此时,您可以通过设置 `cfg.BlockMode = false` 来将读操作提升大约 **50-70%** 的性能。 - -### 为什么要写另一个 INI 解析库? - -许多人都在使用我的 [goconfig](https://github.com/Unknwon/goconfig) 来完成对 INI 文件的操作,但我希望使用更加 Go 风格的代码。并且当您设置 `cfg.BlockMode = false` 时,会有大约 **10-30%** 的性能提升。 - -为了做出这些改变,我必须对 API 进行破坏,所以新开一个仓库是最安全的做法。除此之外,本库直接使用 `gopkg.in` 来进行版本化发布。(其实真相是导入路径更短了) diff --git a/vendor/github.com/go-ini/ini/file.go b/vendor/github.com/go-ini/ini/file.go index ae6264acf..d7982c323 100644 --- a/vendor/github.com/go-ini/ini/file.go +++ b/vendor/github.com/go-ini/ini/file.go @@ -228,7 +228,7 @@ func (f *File) Append(source interface{}, others ...interface{}) error { func (f *File) writeToBuffer(indent string) (*bytes.Buffer, error) { equalSign := "=" - if PrettyFormat { + if PrettyFormat || PrettyEqual { equalSign = " = " } @@ -305,6 +305,10 @@ func (f *File) writeToBuffer(indent string) (*bytes.Buffer, error) { } else { key.Comment = key.Comment[:1] + " " + strings.TrimSpace(key.Comment[1:]) } + + // Support multiline comments + key.Comment = strings.Replace(key.Comment, "\n", "\n; ", -1) + if _, err := buf.WriteString(key.Comment + LineBreak); err != nil { return nil, err } diff --git a/vendor/github.com/go-ini/ini/file_test.go b/vendor/github.com/go-ini/ini/file_test.go index 593224b58..2a0ca7c75 100644 --- a/vendor/github.com/go-ini/ini/file_test.go +++ b/vendor/github.com/go-ini/ini/file_test.go @@ -264,6 +264,22 @@ func TestFile_WriteTo(t *testing.T) { So(err, ShouldBeNil) So(buf.String(), ShouldEqual, string(expected)) }) + + Convey("Support multiline comments", t, func() { + f := ini.Empty() + f.Section("").Key("test").Comment = "Multiline\nComment" + + var buf bytes.Buffer + _, err := f.WriteTo(&buf) + So(err, ShouldBeNil) + + So(buf.String(), ShouldEqual, `; Multiline +; Comment +test = + +`) + + }) } func TestFile_SaveTo(t *testing.T) { diff --git a/vendor/github.com/go-ini/ini/ini.go b/vendor/github.com/go-ini/ini/ini.go index 9f6ea3b41..15ebc8f72 100644 --- a/vendor/github.com/go-ini/ini/ini.go +++ b/vendor/github.com/go-ini/ini/ini.go @@ -32,7 +32,7 @@ const ( // Maximum allowed depth when recursively substituing variable names. _DEPTH_VALUES = 99 - _VERSION = "1.33.0" + _VERSION = "1.37.0" ) // Version returns current package version literal. @@ -53,6 +53,9 @@ var ( // or reduce all possible spaces for compact format. PrettyFormat = true + // Place spaces around "=" sign even when PrettyFormat is false + PrettyEqual = false + // Explicitly write DEFAULT section header DefaultHeader = false @@ -137,6 +140,16 @@ type LoadOptions struct { // AllowNestedValues indicates whether to allow AWS-like nested values. // Docs: http://docs.aws.amazon.com/cli/latest/topic/config-vars.html#nested-values AllowNestedValues bool + // AllowPythonMultilineValues indicates whether to allow Python-like multi-line values. + // Docs: https://docs.python.org/3/library/configparser.html#supported-ini-file-structure + // Relevant quote: Values can also span multiple lines, as long as they are indented deeper + // than the first line of the value. + AllowPythonMultilineValues bool + // SpaceBeforeInlineComment indicates whether to allow comment symbols (\# and \;) inside value. + // Docs: https://docs.python.org/2/library/configparser.html + // Quote: Comments may appear on their own in an otherwise empty line, or may be entered in lines holding values or section names. + // In the latter case, they need to be preceded by a whitespace character to be recognized as a comment. + SpaceBeforeInlineComment bool // UnescapeValueDoubleQuotes indicates whether to unescape double quotes inside value to regular format // when value is surrounded by double quotes, e.g. key="a \"value\"" => key=a "value" UnescapeValueDoubleQuotes bool diff --git a/vendor/github.com/go-ini/ini/ini_test.go b/vendor/github.com/go-ini/ini/ini_test.go index df5fbe384..d68c7caa3 100644 --- a/vendor/github.com/go-ini/ini/ini_test.go +++ b/vendor/github.com/go-ini/ini/ini_test.go @@ -65,7 +65,7 @@ NAME = Unknwon So(err, ShouldBeNil) So(f, ShouldNotBeNil) - // Vaildate values make sure all sources are loaded correctly + // Validate values make sure all sources are loaded correctly sec := f.Section("") So(sec.Key("NAME").String(), ShouldEqual, "ini") So(sec.Key("VERSION").String(), ShouldEqual, "v1") @@ -87,208 +87,625 @@ NAME = Unknwon So(err, ShouldNotBeNil) }) }) + + Convey("Can't properly parse INI files containing `#` or `;` in value", t, func() { + f, err := ini.Load([]byte(` + [author] + NAME = U#n#k#n#w#o#n + GITHUB = U;n;k;n;w;o;n + `)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + sec := f.Section("author") + nameValue := sec.Key("NAME").String() + githubValue := sec.Key("GITHUB").String() + So(nameValue, ShouldEqual, "U") + So(githubValue, ShouldEqual, "U") + }) + + Convey("Can't parse small python-compatible INI files", t, func() { + f, err := ini.Load([]byte(` +[long] +long_rsa_private_key = -----BEGIN RSA PRIVATE KEY----- + foo + bar + foobar + barfoo + -----END RSA PRIVATE KEY----- +`)) + So(err, ShouldNotBeNil) + So(f, ShouldBeNil) + So(err.Error(), ShouldEqual, "key-value delimiter not found: foo\n") + }) + + Convey("Can't parse big python-compatible INI files", t, func() { + f, err := ini.Load([]byte(` +[long] +long_rsa_private_key = -----BEGIN RSA PRIVATE KEY----- + 1foo + 2bar + 3foobar + 4barfoo + 5foo + 6bar + 7foobar + 8barfoo + 9foo + 10bar + 11foobar + 12barfoo + 13foo + 14bar + 15foobar + 16barfoo + 17foo + 18bar + 19foobar + 20barfoo + 21foo + 22bar + 23foobar + 24barfoo + 25foo + 26bar + 27foobar + 28barfoo + 29foo + 30bar + 31foobar + 32barfoo + 33foo + 34bar + 35foobar + 36barfoo + 37foo + 38bar + 39foobar + 40barfoo + 41foo + 42bar + 43foobar + 44barfoo + 45foo + 46bar + 47foobar + 48barfoo + 49foo + 50bar + 51foobar + 52barfoo + 53foo + 54bar + 55foobar + 56barfoo + 57foo + 58bar + 59foobar + 60barfoo + 61foo + 62bar + 63foobar + 64barfoo + 65foo + 66bar + 67foobar + 68barfoo + 69foo + 70bar + 71foobar + 72barfoo + 73foo + 74bar + 75foobar + 76barfoo + 77foo + 78bar + 79foobar + 80barfoo + 81foo + 82bar + 83foobar + 84barfoo + 85foo + 86bar + 87foobar + 88barfoo + 89foo + 90bar + 91foobar + 92barfoo + 93foo + 94bar + 95foobar + 96barfoo + -----END RSA PRIVATE KEY----- +`)) + So(err, ShouldNotBeNil) + So(f, ShouldBeNil) + So(err.Error(), ShouldEqual, "key-value delimiter not found: 1foo\n") + }) +} + +func TestLooseLoad(t *testing.T) { + Convey("Load from data sources with option `Loose` true", t, func() { + f, err := ini.LoadSources(ini.LoadOptions{Loose: true}, _NOT_FOUND_CONF, _MINIMAL_CONF) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + Convey("Inverse case", func() { + _, err = ini.Load(_NOT_FOUND_CONF) + So(err, ShouldNotBeNil) + }) + }) +} + +func TestInsensitiveLoad(t *testing.T) { + Convey("Insensitive to section and key names", t, func() { + f, err := ini.InsensitiveLoad(_MINIMAL_CONF) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("Author").Key("e-mail").String(), ShouldEqual, "u@gogs.io") + + Convey("Write out", func() { + var buf bytes.Buffer + _, err := f.WriteTo(&buf) + So(err, ShouldBeNil) + So(buf.String(), ShouldEqual, `[author] +e-mail = u@gogs.io + +`) + }) + + Convey("Inverse case", func() { + f, err := ini.Load(_MINIMAL_CONF) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("Author").Key("e-mail").String(), ShouldBeEmpty) + }) + }) } func TestLoadSources(t *testing.T) { Convey("Load from data sources with options", t, func() { - Convey("Ignore nonexistent files", func() { - f, err := ini.LooseLoad(_NOT_FOUND_CONF, _MINIMAL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - Convey("Inverse case", func() { - _, err = ini.Load(_NOT_FOUND_CONF) - So(err, ShouldNotBeNil) - }) - }) - - Convey("Insensitive to section and key names", func() { - f, err := ini.InsensitiveLoad(_MINIMAL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("Author").Key("e-mail").String(), ShouldEqual, "u@gogs.io") - - Convey("Write out", func() { - var buf bytes.Buffer - _, err := f.WriteTo(&buf) + Convey("with true `AllowPythonMultilineValues`", func() { + Convey("Ignore nonexistent files", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true, Loose: true}, _NOT_FOUND_CONF, _MINIMAL_CONF) So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `[author] + So(f, ShouldNotBeNil) + + Convey("Inverse case", func() { + _, err = ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, _NOT_FOUND_CONF) + So(err, ShouldNotBeNil) + }) + }) + + Convey("Insensitive to section and key names", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true, Insensitive: true}, _MINIMAL_CONF) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("Author").Key("e-mail").String(), ShouldEqual, "u@gogs.io") + + Convey("Write out", func() { + var buf bytes.Buffer + _, err := f.WriteTo(&buf) + So(err, ShouldBeNil) + So(buf.String(), ShouldEqual, `[author] e-mail = u@gogs.io `) + }) + + Convey("Inverse case", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, _MINIMAL_CONF) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("Author").Key("e-mail").String(), ShouldBeEmpty) + }) }) - Convey("Inverse case", func() { - f, err := ini.Load(_MINIMAL_CONF) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("Author").Key("e-mail").String(), ShouldBeEmpty) - }) - }) - - Convey("Ignore continuation lines", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - IgnoreContinuation: true, - }, []byte(` + Convey("Ignore continuation lines", func() { + f, err := ini.LoadSources(ini.LoadOptions{ + AllowPythonMultilineValues: true, + IgnoreContinuation: true, + }, []byte(` key1=a\b\ key2=c\d\ key3=value`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) - So(f.Section("").Key("key1").String(), ShouldEqual, `a\b\`) - So(f.Section("").Key("key2").String(), ShouldEqual, `c\d\`) - So(f.Section("").Key("key3").String(), ShouldEqual, "value") + So(f.Section("").Key("key1").String(), ShouldEqual, `a\b\`) + So(f.Section("").Key("key2").String(), ShouldEqual, `c\d\`) + So(f.Section("").Key("key3").String(), ShouldEqual, "value") - Convey("Inverse case", func() { - f, err := ini.Load([]byte(` + Convey("Inverse case", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, []byte(` key1=a\b\ key2=c\d\`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("").Key("key1").String(), ShouldEqual, `a\bkey2=c\d`) + }) + }) + + Convey("Ignore inline comments", func() { + f, err := ini.LoadSources(ini.LoadOptions{ + AllowPythonMultilineValues: true, + IgnoreInlineComment: true, + }, []byte(` +key1=value ;comment +key2=value2 #comment2 +key3=val#ue #comment3`)) So(err, ShouldBeNil) So(f, ShouldNotBeNil) - So(f.Section("").Key("key1").String(), ShouldEqual, `a\bkey2=c\d`) - }) - }) + So(f.Section("").Key("key1").String(), ShouldEqual, `value ;comment`) + So(f.Section("").Key("key2").String(), ShouldEqual, `value2 #comment2`) + So(f.Section("").Key("key3").String(), ShouldEqual, `val#ue #comment3`) - Convey("Ignore inline comments", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - IgnoreInlineComment: true, - }, []byte(` + Convey("Inverse case", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, []byte(` key1=value ;comment key2=value2 #comment2`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) - So(f.Section("").Key("key1").String(), ShouldEqual, `value ;comment`) - So(f.Section("").Key("key2").String(), ShouldEqual, `value2 #comment2`) - - Convey("Inverse case", func() { - f, err := ini.Load([]byte(` -key1=value ;comment -key2=value2 #comment2`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("key1").String(), ShouldEqual, `value`) - So(f.Section("").Key("key1").Comment, ShouldEqual, `;comment`) - So(f.Section("").Key("key2").String(), ShouldEqual, `value2`) - So(f.Section("").Key("key2").Comment, ShouldEqual, `#comment2`) + So(f.Section("").Key("key1").String(), ShouldEqual, `value`) + So(f.Section("").Key("key1").Comment, ShouldEqual, `;comment`) + So(f.Section("").Key("key2").String(), ShouldEqual, `value2`) + So(f.Section("").Key("key2").Comment, ShouldEqual, `#comment2`) + }) }) - }) - Convey("Allow boolean type keys", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - AllowBooleanKeys: true, - }, []byte(` + Convey("Allow boolean type keys", func() { + f, err := ini.LoadSources(ini.LoadOptions{ + AllowPythonMultilineValues: true, + AllowBooleanKeys: true, + }, []byte(` key1=hello #key2 key3`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").KeyStrings(), ShouldResemble, []string{"key1", "key3"}) - So(f.Section("").Key("key3").MustBool(false), ShouldBeTrue) - - Convey("Write out", func() { - var buf bytes.Buffer - _, err := f.WriteTo(&buf) So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `key1 = hello + So(f, ShouldNotBeNil) + + So(f.Section("").KeyStrings(), ShouldResemble, []string{"key1", "key3"}) + So(f.Section("").Key("key3").MustBool(false), ShouldBeTrue) + + Convey("Write out", func() { + var buf bytes.Buffer + _, err := f.WriteTo(&buf) + So(err, ShouldBeNil) + So(buf.String(), ShouldEqual, `key1 = hello # key2 key3 `) - }) + }) - Convey("Inverse case", func() { - _, err := ini.Load([]byte(` + Convey("Inverse case", func() { + _, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, []byte(` key1=hello #key2 key3`)) - So(err, ShouldNotBeNil) + So(err, ShouldNotBeNil) + }) }) - }) - Convey("Allow shadow keys", func() { - f, err := ini.ShadowLoad([]byte(` + Convey("Allow shadow keys", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowShadows: true, AllowPythonMultilineValues: true}, []byte(` [remote "origin"] url = https://github.com/Antergone/test1.git url = https://github.com/Antergone/test2.git fetch = +refs/heads/*:refs/remotes/origin/*`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section(`remote "origin"`).Key("url").String(), ShouldEqual, "https://github.com/Antergone/test1.git") - So(f.Section(`remote "origin"`).Key("url").ValueWithShadows(), ShouldResemble, []string{ - "https://github.com/Antergone/test1.git", - "https://github.com/Antergone/test2.git", - }) - So(f.Section(`remote "origin"`).Key("fetch").String(), ShouldEqual, "+refs/heads/*:refs/remotes/origin/*") - - Convey("Write out", func() { - var buf bytes.Buffer - _, err := f.WriteTo(&buf) So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `[remote "origin"] + So(f, ShouldNotBeNil) + + So(f.Section(`remote "origin"`).Key("url").String(), ShouldEqual, "https://github.com/Antergone/test1.git") + So(f.Section(`remote "origin"`).Key("url").ValueWithShadows(), ShouldResemble, []string{ + "https://github.com/Antergone/test1.git", + "https://github.com/Antergone/test2.git", + }) + So(f.Section(`remote "origin"`).Key("fetch").String(), ShouldEqual, "+refs/heads/*:refs/remotes/origin/*") + + Convey("Write out", func() { + var buf bytes.Buffer + _, err := f.WriteTo(&buf) + So(err, ShouldBeNil) + So(buf.String(), ShouldEqual, `[remote "origin"] url = https://github.com/Antergone/test1.git url = https://github.com/Antergone/test2.git fetch = +refs/heads/*:refs/remotes/origin/* `) - }) + }) - Convey("Inverse case", func() { - f, err := ini.Load([]byte(` + Convey("Inverse case", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, []byte(` [remote "origin"] url = https://github.com/Antergone/test1.git url = https://github.com/Antergone/test2.git`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) - So(f.Section(`remote "origin"`).Key("url").String(), ShouldEqual, "https://github.com/Antergone/test2.git") + So(f.Section(`remote "origin"`).Key("url").String(), ShouldEqual, "https://github.com/Antergone/test2.git") + }) }) - }) - Convey("Unescape double quotes inside value", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - UnescapeValueDoubleQuotes: true, - }, []byte(` -create_repo="创建了仓库 %s"`)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("create_repo").String(), ShouldEqual, `创建了仓库 %s`) - - Convey("Inverse case", func() { - f, err := ini.Load([]byte(` + Convey("Unescape double quotes inside value", func() { + f, err := ini.LoadSources(ini.LoadOptions{ + AllowPythonMultilineValues: true, + UnescapeValueDoubleQuotes: true, + }, []byte(` create_repo="创建了仓库 %s"`)) So(err, ShouldBeNil) So(f, ShouldNotBeNil) - So(f.Section("").Key("create_repo").String(), ShouldEqual, `"创建了仓库 %s"`) - }) - }) + So(f.Section("").Key("create_repo").String(), ShouldEqual, `创建了仓库 %s`) - Convey("Unescape comment symbols inside value", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - IgnoreInlineComment: true, - UnescapeValueCommentSymbols: true, - }, []byte(` + Convey("Inverse case", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, []byte(` +create_repo="创建了仓库 %s"`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("").Key("create_repo").String(), ShouldEqual, `"创建了仓库 %s"`) + }) + }) + + Convey("Unescape comment symbols inside value", func() { + f, err := ini.LoadSources(ini.LoadOptions{ + AllowPythonMultilineValues: true, + IgnoreInlineComment: true, + UnescapeValueCommentSymbols: true, + }, []byte(` key = test value more text `)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) - So(f.Section("").Key("key").String(), ShouldEqual, `test value more text`) - }) + So(f.Section("").Key("key").String(), ShouldEqual, `test value more text`) + }) - Convey("Allow unparseable sections", func() { - f, err := ini.LoadSources(ini.LoadOptions{ - Insensitive: true, - UnparseableSections: []string{"core_lesson", "comments"}, - }, []byte(` + Convey("Can parse small python-compatible INI files", func() { + f, err := ini.LoadSources(ini.LoadOptions{ + AllowPythonMultilineValues: true, + Insensitive: true, + UnparseableSections: []string{"core_lesson", "comments"}, + }, []byte(` +[long] +long_rsa_private_key = -----BEGIN RSA PRIVATE KEY----- + foo + bar + foobar + barfoo + -----END RSA PRIVATE KEY----- +`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("long").Key("long_rsa_private_key").String(), ShouldEqual, "-----BEGIN RSA PRIVATE KEY-----\nfoo\nbar\nfoobar\nbarfoo\n-----END RSA PRIVATE KEY-----") + }) + + Convey("Can parse big python-compatible INI files", func() { + f, err := ini.LoadSources(ini.LoadOptions{ + AllowPythonMultilineValues: true, + Insensitive: true, + UnparseableSections: []string{"core_lesson", "comments"}, + }, []byte(` +[long] +long_rsa_private_key = -----BEGIN RSA PRIVATE KEY----- + 1foo + 2bar + 3foobar + 4barfoo + 5foo + 6bar + 7foobar + 8barfoo + 9foo + 10bar + 11foobar + 12barfoo + 13foo + 14bar + 15foobar + 16barfoo + 17foo + 18bar + 19foobar + 20barfoo + 21foo + 22bar + 23foobar + 24barfoo + 25foo + 26bar + 27foobar + 28barfoo + 29foo + 30bar + 31foobar + 32barfoo + 33foo + 34bar + 35foobar + 36barfoo + 37foo + 38bar + 39foobar + 40barfoo + 41foo + 42bar + 43foobar + 44barfoo + 45foo + 46bar + 47foobar + 48barfoo + 49foo + 50bar + 51foobar + 52barfoo + 53foo + 54bar + 55foobar + 56barfoo + 57foo + 58bar + 59foobar + 60barfoo + 61foo + 62bar + 63foobar + 64barfoo + 65foo + 66bar + 67foobar + 68barfoo + 69foo + 70bar + 71foobar + 72barfoo + 73foo + 74bar + 75foobar + 76barfoo + 77foo + 78bar + 79foobar + 80barfoo + 81foo + 82bar + 83foobar + 84barfoo + 85foo + 86bar + 87foobar + 88barfoo + 89foo + 90bar + 91foobar + 92barfoo + 93foo + 94bar + 95foobar + 96barfoo + -----END RSA PRIVATE KEY----- +`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("long").Key("long_rsa_private_key").String(), ShouldEqual, `-----BEGIN RSA PRIVATE KEY----- +1foo +2bar +3foobar +4barfoo +5foo +6bar +7foobar +8barfoo +9foo +10bar +11foobar +12barfoo +13foo +14bar +15foobar +16barfoo +17foo +18bar +19foobar +20barfoo +21foo +22bar +23foobar +24barfoo +25foo +26bar +27foobar +28barfoo +29foo +30bar +31foobar +32barfoo +33foo +34bar +35foobar +36barfoo +37foo +38bar +39foobar +40barfoo +41foo +42bar +43foobar +44barfoo +45foo +46bar +47foobar +48barfoo +49foo +50bar +51foobar +52barfoo +53foo +54bar +55foobar +56barfoo +57foo +58bar +59foobar +60barfoo +61foo +62bar +63foobar +64barfoo +65foo +66bar +67foobar +68barfoo +69foo +70bar +71foobar +72barfoo +73foo +74bar +75foobar +76barfoo +77foo +78bar +79foobar +80barfoo +81foo +82bar +83foobar +84barfoo +85foo +86bar +87foobar +88barfoo +89foo +90bar +91foobar +92barfoo +93foo +94bar +95foobar +96barfoo +-----END RSA PRIVATE KEY-----`) + }) + + Convey("Allow unparsable sections", func() { + f, err := ini.LoadSources(ini.LoadOptions{ + AllowPythonMultilineValues: true, + Insensitive: true, + UnparseableSections: []string{"core_lesson", "comments"}, + }, []byte(` Lesson_Location = 87 Lesson_Status = C Score = 3 @@ -300,20 +717,20 @@ my lesson state data – 1111111111111111111000000000000000001110000 [COMMENTS] <1> This slide has the fuel listed in the wrong units `)) - So(err, ShouldBeNil) - So(f, ShouldNotBeNil) - - So(f.Section("").Key("score").String(), ShouldEqual, "3") - So(f.Section("").Body(), ShouldBeEmpty) - So(f.Section("core_lesson").Body(), ShouldEqual, `my lesson state data – 1111111111111111111000000000000000001110000 -111111111111111111100000000000111000000000 – end my lesson state data`) - So(f.Section("comments").Body(), ShouldEqual, `<1> This slide has the fuel listed in the wrong units `) - - Convey("Write out", func() { - var buf bytes.Buffer - _, err := f.WriteTo(&buf) So(err, ShouldBeNil) - So(buf.String(), ShouldEqual, `lesson_location = 87 + So(f, ShouldNotBeNil) + + So(f.Section("").Key("score").String(), ShouldEqual, "3") + So(f.Section("").Body(), ShouldBeEmpty) + So(f.Section("core_lesson").Body(), ShouldEqual, `my lesson state data – 1111111111111111111000000000000000001110000 +111111111111111111100000000000111000000000 – end my lesson state data`) + So(f.Section("comments").Body(), ShouldEqual, `<1> This slide has the fuel listed in the wrong units `) + + Convey("Write out", func() { + var buf bytes.Buffer + _, err := f.WriteTo(&buf) + So(err, ShouldBeNil) + So(buf.String(), ShouldEqual, `lesson_location = 87 lesson_status = C score = 3 time = 00:02:30 @@ -325,14 +742,468 @@ my lesson state data – 1111111111111111111000000000000000001110000 [comments] <1> This slide has the fuel listed in the wrong units `) - }) + }) - Convey("Inverse case", func() { - _, err := ini.Load([]byte(` + Convey("Inverse case", func() { + _, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, []byte(` [CORE_LESSON] my lesson state data – 1111111111111111111000000000000000001110000 111111111111111111100000000000111000000000 – end my lesson state data`)) + So(err, ShouldNotBeNil) + }) + }) + + Convey("And false `SpaceBeforeInlineComment`", func() { + Convey("Can't parse INI files containing `#` or `;` in value", func() { + f, err := ini.LoadSources( + ini.LoadOptions{AllowPythonMultilineValues: false, SpaceBeforeInlineComment: false}, + []byte(` +[author] +NAME = U#n#k#n#w#o#n +GITHUB = U;n;k;n;w;o;n +`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + sec := f.Section("author") + nameValue := sec.Key("NAME").String() + githubValue := sec.Key("GITHUB").String() + So(nameValue, ShouldEqual, "U") + So(githubValue, ShouldEqual, "U") + }) + }) + + Convey("And true `SpaceBeforeInlineComment`", func() { + Convey("Can parse INI files containing `#` or `;` in value", func() { + f, err := ini.LoadSources( + ini.LoadOptions{AllowPythonMultilineValues: false, SpaceBeforeInlineComment: true}, + []byte(` +[author] +NAME = U#n#k#n#w#o#n +GITHUB = U;n;k;n;w;o;n +`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + sec := f.Section("author") + nameValue := sec.Key("NAME").String() + githubValue := sec.Key("GITHUB").String() + So(nameValue, ShouldEqual, "U#n#k#n#w#o#n") + So(githubValue, ShouldEqual, "U;n;k;n;w;o;n") + }) + }) + }) + + Convey("with false `AllowPythonMultilineValues`", func() { + Convey("Ignore nonexistent files", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false, Loose: true}, _NOT_FOUND_CONF, _MINIMAL_CONF) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + Convey("Inverse case", func() { + _, err = ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, _NOT_FOUND_CONF) + So(err, ShouldNotBeNil) + }) + }) + + Convey("Insensitive to section and key names", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false, Insensitive: true}, _MINIMAL_CONF) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("Author").Key("e-mail").String(), ShouldEqual, "u@gogs.io") + + Convey("Write out", func() { + var buf bytes.Buffer + _, err := f.WriteTo(&buf) + So(err, ShouldBeNil) + So(buf.String(), ShouldEqual, `[author] +e-mail = u@gogs.io + +`) + }) + + Convey("Inverse case", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, _MINIMAL_CONF) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("Author").Key("e-mail").String(), ShouldBeEmpty) + }) + }) + + Convey("Ignore continuation lines", func() { + f, err := ini.LoadSources(ini.LoadOptions{ + AllowPythonMultilineValues: false, + IgnoreContinuation: true, + }, []byte(` +key1=a\b\ +key2=c\d\ +key3=value`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("").Key("key1").String(), ShouldEqual, `a\b\`) + So(f.Section("").Key("key2").String(), ShouldEqual, `c\d\`) + So(f.Section("").Key("key3").String(), ShouldEqual, "value") + + Convey("Inverse case", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` +key1=a\b\ +key2=c\d\`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("").Key("key1").String(), ShouldEqual, `a\bkey2=c\d`) + }) + }) + + Convey("Ignore inline comments", func() { + f, err := ini.LoadSources(ini.LoadOptions{ + AllowPythonMultilineValues: false, + IgnoreInlineComment: true, + }, []byte(` +key1=value ;comment +key2=value2 #comment2 +key3=val#ue #comment3`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("").Key("key1").String(), ShouldEqual, `value ;comment`) + So(f.Section("").Key("key2").String(), ShouldEqual, `value2 #comment2`) + So(f.Section("").Key("key3").String(), ShouldEqual, `val#ue #comment3`) + + Convey("Inverse case", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` +key1=value ;comment +key2=value2 #comment2`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("").Key("key1").String(), ShouldEqual, `value`) + So(f.Section("").Key("key1").Comment, ShouldEqual, `;comment`) + So(f.Section("").Key("key2").String(), ShouldEqual, `value2`) + So(f.Section("").Key("key2").Comment, ShouldEqual, `#comment2`) + }) + }) + + Convey("Allow boolean type keys", func() { + f, err := ini.LoadSources(ini.LoadOptions{ + AllowPythonMultilineValues: false, + AllowBooleanKeys: true, + }, []byte(` +key1=hello +#key2 +key3`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("").KeyStrings(), ShouldResemble, []string{"key1", "key3"}) + So(f.Section("").Key("key3").MustBool(false), ShouldBeTrue) + + Convey("Write out", func() { + var buf bytes.Buffer + _, err := f.WriteTo(&buf) + So(err, ShouldBeNil) + So(buf.String(), ShouldEqual, `key1 = hello +# key2 +key3 +`) + }) + + Convey("Inverse case", func() { + _, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` +key1=hello +#key2 +key3`)) + So(err, ShouldNotBeNil) + }) + }) + + Convey("Allow shadow keys", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false, AllowShadows: true}, []byte(` +[remote "origin"] +url = https://github.com/Antergone/test1.git +url = https://github.com/Antergone/test2.git +fetch = +refs/heads/*:refs/remotes/origin/*`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section(`remote "origin"`).Key("url").String(), ShouldEqual, "https://github.com/Antergone/test1.git") + So(f.Section(`remote "origin"`).Key("url").ValueWithShadows(), ShouldResemble, []string{ + "https://github.com/Antergone/test1.git", + "https://github.com/Antergone/test2.git", + }) + So(f.Section(`remote "origin"`).Key("fetch").String(), ShouldEqual, "+refs/heads/*:refs/remotes/origin/*") + + Convey("Write out", func() { + var buf bytes.Buffer + _, err := f.WriteTo(&buf) + So(err, ShouldBeNil) + So(buf.String(), ShouldEqual, `[remote "origin"] +url = https://github.com/Antergone/test1.git +url = https://github.com/Antergone/test2.git +fetch = +refs/heads/*:refs/remotes/origin/* + +`) + }) + + Convey("Inverse case", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` +[remote "origin"] +url = https://github.com/Antergone/test1.git +url = https://github.com/Antergone/test2.git`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section(`remote "origin"`).Key("url").String(), ShouldEqual, "https://github.com/Antergone/test2.git") + }) + }) + + Convey("Unescape double quotes inside value", func() { + f, err := ini.LoadSources(ini.LoadOptions{ + AllowPythonMultilineValues: false, + UnescapeValueDoubleQuotes: true, + }, []byte(` +create_repo="创建了仓库 %s"`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("").Key("create_repo").String(), ShouldEqual, `创建了仓库 %s`) + + Convey("Inverse case", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` +create_repo="创建了仓库 %s"`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("").Key("create_repo").String(), ShouldEqual, `"创建了仓库 %s"`) + }) + }) + + Convey("Unescape comment symbols inside value", func() { + f, err := ini.LoadSources(ini.LoadOptions{ + AllowPythonMultilineValues: false, + IgnoreInlineComment: true, + UnescapeValueCommentSymbols: true, + }, []byte(` +key = test value more text +`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("").Key("key").String(), ShouldEqual, `test value more text`) + }) + + Convey("Can't parse small python-compatible INI files", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` +[long] +long_rsa_private_key = -----BEGIN RSA PRIVATE KEY----- + foo + bar + foobar + barfoo + -----END RSA PRIVATE KEY----- +`)) So(err, ShouldNotBeNil) + So(f, ShouldBeNil) + So(err.Error(), ShouldEqual, "key-value delimiter not found: foo\n") + }) + + Convey("Can't parse big python-compatible INI files", func() { + f, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` +[long] +long_rsa_private_key = -----BEGIN RSA PRIVATE KEY----- + 1foo + 2bar + 3foobar + 4barfoo + 5foo + 6bar + 7foobar + 8barfoo + 9foo + 10bar + 11foobar + 12barfoo + 13foo + 14bar + 15foobar + 16barfoo + 17foo + 18bar + 19foobar + 20barfoo + 21foo + 22bar + 23foobar + 24barfoo + 25foo + 26bar + 27foobar + 28barfoo + 29foo + 30bar + 31foobar + 32barfoo + 33foo + 34bar + 35foobar + 36barfoo + 37foo + 38bar + 39foobar + 40barfoo + 41foo + 42bar + 43foobar + 44barfoo + 45foo + 46bar + 47foobar + 48barfoo + 49foo + 50bar + 51foobar + 52barfoo + 53foo + 54bar + 55foobar + 56barfoo + 57foo + 58bar + 59foobar + 60barfoo + 61foo + 62bar + 63foobar + 64barfoo + 65foo + 66bar + 67foobar + 68barfoo + 69foo + 70bar + 71foobar + 72barfoo + 73foo + 74bar + 75foobar + 76barfoo + 77foo + 78bar + 79foobar + 80barfoo + 81foo + 82bar + 83foobar + 84barfoo + 85foo + 86bar + 87foobar + 88barfoo + 89foo + 90bar + 91foobar + 92barfoo + 93foo + 94bar + 95foobar + 96barfoo + -----END RSA PRIVATE KEY----- +`)) + So(err, ShouldNotBeNil) + So(f, ShouldBeNil) + So(err.Error(), ShouldEqual, "key-value delimiter not found: 1foo\n") + }) + + Convey("Allow unparsable sections", func() { + f, err := ini.LoadSources(ini.LoadOptions{ + AllowPythonMultilineValues: false, + Insensitive: true, + UnparseableSections: []string{"core_lesson", "comments"}, + }, []byte(` +Lesson_Location = 87 +Lesson_Status = C +Score = 3 +Time = 00:02:30 + +[CORE_LESSON] +my lesson state data – 1111111111111111111000000000000000001110000 +111111111111111111100000000000111000000000 – end my lesson state data + +[COMMENTS] +<1> This slide has the fuel listed in the wrong units `)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + + So(f.Section("").Key("score").String(), ShouldEqual, "3") + So(f.Section("").Body(), ShouldBeEmpty) + So(f.Section("core_lesson").Body(), ShouldEqual, `my lesson state data – 1111111111111111111000000000000000001110000 +111111111111111111100000000000111000000000 – end my lesson state data`) + So(f.Section("comments").Body(), ShouldEqual, `<1> This slide has the fuel listed in the wrong units `) + + Convey("Write out", func() { + var buf bytes.Buffer + _, err := f.WriteTo(&buf) + So(err, ShouldBeNil) + So(buf.String(), ShouldEqual, `lesson_location = 87 +lesson_status = C +score = 3 +time = 00:02:30 + +[core_lesson] +my lesson state data – 1111111111111111111000000000000000001110000 +111111111111111111100000000000111000000000 – end my lesson state data + +[comments] +<1> This slide has the fuel listed in the wrong units +`) + }) + + Convey("Inverse case", func() { + _, err := ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: false}, []byte(` +[CORE_LESSON] +my lesson state data – 1111111111111111111000000000000000001110000 +111111111111111111100000000000111000000000 – end my lesson state data`)) + So(err, ShouldNotBeNil) + }) + }) + + Convey("And false `SpaceBeforeInlineComment`", func() { + Convey("Can't parse INI files containing `#` or `;` in value", func() { + f, err := ini.LoadSources( + ini.LoadOptions{AllowPythonMultilineValues: true, SpaceBeforeInlineComment: false}, + []byte(` +[author] +NAME = U#n#k#n#w#o#n +GITHUB = U;n;k;n;w;o;n +`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + sec := f.Section("author") + nameValue := sec.Key("NAME").String() + githubValue := sec.Key("GITHUB").String() + So(nameValue, ShouldEqual, "U") + So(githubValue, ShouldEqual, "U") + }) + }) + + Convey("And true `SpaceBeforeInlineComment`", func() { + Convey("Can parse INI files containing `#` or `;` in value", func() { + f, err := ini.LoadSources( + ini.LoadOptions{AllowPythonMultilineValues: true, SpaceBeforeInlineComment: true}, + []byte(` +[author] +NAME = U#n#k#n#w#o#n +GITHUB = U;n;k;n;w;o;n +`)) + So(err, ShouldBeNil) + So(f, ShouldNotBeNil) + sec := f.Section("author") + nameValue := sec.Key("NAME").String() + githubValue := sec.Key("GITHUB").String() + So(nameValue, ShouldEqual, "U#n#k#n#w#o#n") + So(githubValue, ShouldEqual, "U;n;k;n;w;o;n") + }) }) }) }) diff --git a/vendor/github.com/go-ini/ini/parser.go b/vendor/github.com/go-ini/ini/parser.go index db3af8f00..d5aa2db60 100644 --- a/vendor/github.com/go-ini/ini/parser.go +++ b/vendor/github.com/go-ini/ini/parser.go @@ -19,11 +19,14 @@ import ( "bytes" "fmt" "io" + "regexp" "strconv" "strings" "unicode" ) +var pythonMultiline = regexp.MustCompile("^(\\s+)([^\n]+)") + type tokenType int const ( @@ -194,7 +197,8 @@ func hasSurroundedQuote(in string, quote byte) bool { } func (p *parser) readValue(in []byte, - ignoreContinuation, ignoreInlineComment, unescapeValueDoubleQuotes, unescapeValueCommentSymbols bool) (string, error) { + parserBufferSize int, + ignoreContinuation, ignoreInlineComment, unescapeValueDoubleQuotes, unescapeValueCommentSymbols, allowPythonMultilines, spaceBeforeInlineComment bool) (string, error) { line := strings.TrimLeftFunc(string(in), unicode.IsSpace) if len(line) == 0 { @@ -224,21 +228,34 @@ func (p *parser) readValue(in []byte, return line[startIdx : pos+startIdx], nil } + lastChar := line[len(line)-1] // Won't be able to reach here if value only contains whitespace line = strings.TrimSpace(line) + trimmedLastChar := line[len(line)-1] // Check continuation lines when desired - if !ignoreContinuation && line[len(line)-1] == '\\' { + if !ignoreContinuation && trimmedLastChar == '\\' { return p.readContinuationLines(line[:len(line)-1]) } // Check if ignore inline comment if !ignoreInlineComment { - i := strings.IndexAny(line, "#;") + var i int + if spaceBeforeInlineComment { + i = strings.Index(line, " #") + if i == -1 { + i = strings.Index(line, " ;") + } + + } else { + i = strings.IndexAny(line, "#;") + } + if i > -1 { p.comment.WriteString(line[i:]) line = strings.TrimSpace(line[:i]) } + } // Trim single and double quotes @@ -252,7 +269,50 @@ func (p *parser) readValue(in []byte, if strings.Contains(line, `\#`) { line = strings.Replace(line, `\#`, "#", -1) } + } else if allowPythonMultilines && lastChar == '\n' { + parserBufferPeekResult, _ := p.buf.Peek(parserBufferSize) + peekBuffer := bytes.NewBuffer(parserBufferPeekResult) + + identSize := -1 + val := line + + for { + peekData, peekErr := peekBuffer.ReadBytes('\n') + if peekErr != nil { + if peekErr == io.EOF { + return val, nil + } + return "", peekErr + } + + peekMatches := pythonMultiline.FindStringSubmatch(string(peekData)) + if len(peekMatches) != 3 { + return val, nil + } + + currentIdentSize := len(peekMatches[1]) + // NOTE: Return if not a python-ini multi-line value. + if currentIdentSize < 0 { + return val, nil + } + identSize = currentIdentSize + + // NOTE: Just advance the parser reader (buffer) in-sync with the peek buffer. + _, err := p.readUntil('\n') + if err != nil { + return "", err + } + + val += fmt.Sprintf("\n%s", peekMatches[2]) + } + + // NOTE: If it was a Python multi-line value, + // return the appended value. + if identSize > 0 { + return val, nil + } } + return line, nil } @@ -276,6 +336,29 @@ func (f *File) parse(reader io.Reader) (err error) { var line []byte var inUnparseableSection bool + + // NOTE: Iterate and increase `currentPeekSize` until + // the size of the parser buffer is found. + // TODO: When Golang 1.10 is the lowest version supported, + // replace with `parserBufferSize := p.buf.Size()`. + parserBufferSize := 0 + // NOTE: Peek 1kb at a time. + currentPeekSize := 1024 + + if f.options.AllowPythonMultilineValues { + for { + peekBytes, _ := p.buf.Peek(currentPeekSize) + peekBytesLength := len(peekBytes) + + if parserBufferSize >= peekBytesLength { + break + } + + currentPeekSize *= 2 + parserBufferSize = peekBytesLength + } + } + for !p.isEOF { line, err = p.readUntil('\n') if err != nil { @@ -352,10 +435,13 @@ func (f *File) parse(reader io.Reader) (err error) { // Treat as boolean key when desired, and whole line is key name. if IsErrDelimiterNotFound(err) && f.options.AllowBooleanKeys { kname, err := p.readValue(line, + parserBufferSize, f.options.IgnoreContinuation, f.options.IgnoreInlineComment, f.options.UnescapeValueDoubleQuotes, - f.options.UnescapeValueCommentSymbols) + f.options.UnescapeValueCommentSymbols, + f.options.AllowPythonMultilineValues, + f.options.SpaceBeforeInlineComment) if err != nil { return err } @@ -379,10 +465,13 @@ func (f *File) parse(reader io.Reader) (err error) { } value, err := p.readValue(line[offset:], + parserBufferSize, f.options.IgnoreContinuation, f.options.IgnoreInlineComment, f.options.UnescapeValueDoubleQuotes, - f.options.UnescapeValueCommentSymbols) + f.options.UnescapeValueCommentSymbols, + f.options.AllowPythonMultilineValues, + f.options.SpaceBeforeInlineComment) if err != nil { return err } diff --git a/vendor/github.com/go-openapi/analysis/.github/CONTRIBUTING.md b/vendor/github.com/go-openapi/analysis/.github/CONTRIBUTING.md deleted file mode 100644 index 7dea4240d..000000000 --- a/vendor/github.com/go-openapi/analysis/.github/CONTRIBUTING.md +++ /dev/null @@ -1,117 +0,0 @@ -## Contribution Guidelines - -### Pull requests are always welcome - -We are always thrilled to receive pull requests, and do our best to -process them as fast as possible. Not sure if that typo is worth a pull -request? Do it! We will appreciate it. - -If your pull request is not accepted on the first try, don't be -discouraged! If there's a problem with the implementation, hopefully you -received feedback on what to improve. - -We're trying very hard to keep go-swagger lean and focused. We don't want it -to do everything for everybody. This means that we might decide against -incorporating a new feature. However, there might be a way to implement -that feature *on top of* go-swagger. - - -### Conventions - -Fork the repo and make changes on your fork in a feature branch: - -- If it's a bugfix branch, name it XXX-something where XXX is the number of the - issue -- If it's a feature branch, create an enhancement issue to announce your - intentions, and name it XXX-something where XXX is the number of the issue. - -Submit unit tests for your changes. Go has a great test framework built in; use -it! Take a look at existing tests for inspiration. Run the full test suite on -your branch before submitting a pull request. - -Update the documentation when creating or modifying features. Test -your documentation changes for clarity, concision, and correctness, as -well as a clean documentation build. See ``docs/README.md`` for more -information on building the docs and how docs get released. - -Write clean code. Universally formatted code promotes ease of writing, reading, -and maintenance. Always run `gofmt -s -w file.go` on each changed file before -committing your changes. Most editors have plugins that do this automatically. - -Pull requests descriptions should be as clear as possible and include a -reference to all the issues that they address. - -Pull requests must not contain commits from other users or branches. - -Commit messages must start with a capitalized and short summary (max. 50 -chars) written in the imperative, followed by an optional, more detailed -explanatory text which is separated from the summary by an empty line. - -Code review comments may be added to your pull request. Discuss, then make the -suggested modifications and push additional commits to your feature branch. Be -sure to post a comment after pushing. The new commits will show up in the pull -request automatically, but the reviewers will not be notified unless you -comment. - -Before the pull request is merged, make sure that you squash your commits into -logical units of work using `git rebase -i` and `git push -f`. After every -commit the test suite should be passing. Include documentation changes in the -same commit so that a revert would remove all traces of the feature or fix. - -Commits that fix or close an issue should include a reference like `Closes #XXX` -or `Fixes #XXX`, which will automatically close the issue when merged. - -### Sign your work - -The sign-off is a simple line at the end of the explanation for the -patch, which certifies that you wrote it or otherwise have the right to -pass it on as an open-source patch. The rules are pretty simple: if you -can certify the below (from -[developercertificate.org](http://developercertificate.org/)): - -``` -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` - -then you just add a line to every git commit message: - - Signed-off-by: Joe Smith - -using your real name (sorry, no pseudonyms or anonymous contributions.) - -You can add the sign off when creating the git commit via `git commit -s`. diff --git a/vendor/github.com/go-openapi/analysis/.gitignore b/vendor/github.com/go-openapi/analysis/.gitignore deleted file mode 100644 index c96f0b231..000000000 --- a/vendor/github.com/go-openapi/analysis/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -secrets.yml -coverage.out -.idea diff --git a/vendor/github.com/go-openapi/analysis/.travis.yml b/vendor/github.com/go-openapi/analysis/.travis.yml deleted file mode 100644 index 3aa42ab3a..000000000 --- a/vendor/github.com/go-openapi/analysis/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -language: go -go: -- 1.7 -install: -- go get -u github.com/stretchr/testify/assert -- go get -u gopkg.in/yaml.v2 -- go get -u github.com/go-openapi/swag -- go get -u github.com/go-openapi/jsonpointer -- go get -u github.com/go-openapi/spec -- go get -u github.com/go-openapi/strfmt -- go get -u github.com/go-openapi/loads/fmts -script: -- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./... -after_success: -- bash <(curl -s https://codecov.io/bash) -notifications: - slack: - secure: Sf7kZf7ZGbnwWUMpffHwMu5A0cHkLK2MYY32LNTPj4+/3qC3Ghl7+9v4TSLOqOlCwdRNjOGblAq7s+GDJed6/xgRQl1JtCi1klzZNrYX4q01pgTPvvGcwbBkIYgeMaPeIRcK9OZnud7sRXdttozgTOpytps2U6Js32ip7uj5mHSg2ub0FwoSJwlS6dbezZ8+eDhoha0F/guY99BEwx8Bd+zROrT2TFGsSGOFGN6wFc7moCqTHO/YkWib13a2QNXqOxCCVBy/lt76Wp+JkeFppjHlzs/2lP3EAk13RIUAaesdEUHvIHrzCyNJEd3/+KO2DzsWOYfpktd+KBCvgaYOsoo7ubdT3IROeAegZdCgo/6xgCEsmFc9ZcqCfN5yNx2A+BZ2Vwmpws+bQ1E1+B5HDzzaiLcYfG4X2O210QVGVDLWsv1jqD+uPYeHY2WRfh5ZsIUFvaqgUEnwHwrK44/8REAhQavt1QAj5uJpsRd7CkRVPWRNK+yIky+wgbVUFEchRNmS55E7QWf+W4+4QZkQi7vUTMc9nbTUu2Es9NfvfudOpM2wZbn98fjpb/qq/nRv6Bk+ca+7XD5/IgNLMbWp2ouDdzbiHLCOfDUiHiDJhLfFZx9Bwo7ZwfzeOlbrQX66bx7xRKYmOe4DLrXhNcpbsMa8qbfxlZRCmYbubB/Y8h4= diff --git a/vendor/github.com/go-openapi/analysis/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/analysis/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e..000000000 --- a/vendor/github.com/go-openapi/analysis/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/analysis/LICENSE b/vendor/github.com/go-openapi/analysis/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/go-openapi/analysis/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/go-openapi/analysis/README.md b/vendor/github.com/go-openapi/analysis/README.md deleted file mode 100644 index d32c30d45..000000000 --- a/vendor/github.com/go-openapi/analysis/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# OpenAPI initiative analysis [![Build Status](https://travis-ci.org/go-openapi/analysis.svg?branch=master)](https://travis-ci.org/go-openapi/analysis) [![codecov](https://codecov.io/gh/go-openapi/analysis/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/analysis) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/analysis/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/analysis?status.svg)](http://godoc.org/github.com/go-openapi/analysis) - - -A foundational library to analyze an OAI specification document for easier reasoning about the content. \ No newline at end of file diff --git a/vendor/github.com/go-openapi/analysis/analyzer.go b/vendor/github.com/go-openapi/analysis/analyzer.go deleted file mode 100644 index 532182d29..000000000 --- a/vendor/github.com/go-openapi/analysis/analyzer.go +++ /dev/null @@ -1,837 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package analysis - -import ( - "fmt" - slashpath "path" - "strconv" - "strings" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/spec" - "github.com/go-openapi/swag" -) - -type referenceAnalysis struct { - schemas map[string]spec.Ref - responses map[string]spec.Ref - parameters map[string]spec.Ref - items map[string]spec.Ref - headerItems map[string]spec.Ref - parameterItems map[string]spec.Ref - allRefs map[string]spec.Ref - pathItems map[string]spec.Ref -} - -func (r *referenceAnalysis) addRef(key string, ref spec.Ref) { - r.allRefs["#"+key] = ref -} - -func (r *referenceAnalysis) addItemsRef(key string, items *spec.Items, location string) { - r.items["#"+key] = items.Ref - r.addRef(key, items.Ref) - if location == "header" { - r.headerItems["#"+key] = items.Ref - } else { - r.parameterItems["#"+key] = items.Ref - } -} - -func (r *referenceAnalysis) addSchemaRef(key string, ref SchemaRef) { - r.schemas["#"+key] = ref.Schema.Ref - r.addRef(key, ref.Schema.Ref) -} - -func (r *referenceAnalysis) addResponseRef(key string, resp *spec.Response) { - r.responses["#"+key] = resp.Ref - r.addRef(key, resp.Ref) -} - -func (r *referenceAnalysis) addParamRef(key string, param *spec.Parameter) { - r.parameters["#"+key] = param.Ref - r.addRef(key, param.Ref) -} - -func (r *referenceAnalysis) addPathItemRef(key string, pathItem *spec.PathItem) { - r.pathItems["#"+key] = pathItem.Ref - r.addRef(key, pathItem.Ref) -} - -type patternAnalysis struct { - parameters map[string]string - headers map[string]string - items map[string]string - schemas map[string]string - allPatterns map[string]string -} - -func (p *patternAnalysis) addPattern(key, pattern string) { - p.allPatterns["#"+key] = pattern -} - -func (p *patternAnalysis) addParameterPattern(key, pattern string) { - p.parameters["#"+key] = pattern - p.addPattern(key, pattern) -} - -func (p *patternAnalysis) addHeaderPattern(key, pattern string) { - p.headers["#"+key] = pattern - p.addPattern(key, pattern) -} - -func (p *patternAnalysis) addItemsPattern(key, pattern string) { - p.items["#"+key] = pattern - p.addPattern(key, pattern) -} - -func (p *patternAnalysis) addSchemaPattern(key, pattern string) { - p.schemas["#"+key] = pattern - p.addPattern(key, pattern) -} - -// New takes a swagger spec object and returns an analyzed spec document. -// The analyzed document contains a number of indices that make it easier to -// reason about semantics of a swagger specification for use in code generation -// or validation etc. -func New(doc *spec.Swagger) *Spec { - a := &Spec{ - spec: doc, - consumes: make(map[string]struct{}, 150), - produces: make(map[string]struct{}, 150), - authSchemes: make(map[string]struct{}, 150), - operations: make(map[string]map[string]*spec.Operation, 150), - allSchemas: make(map[string]SchemaRef, 150), - allOfs: make(map[string]SchemaRef, 150), - references: referenceAnalysis{ - schemas: make(map[string]spec.Ref, 150), - pathItems: make(map[string]spec.Ref, 150), - responses: make(map[string]spec.Ref, 150), - parameters: make(map[string]spec.Ref, 150), - items: make(map[string]spec.Ref, 150), - headerItems: make(map[string]spec.Ref, 150), - parameterItems: make(map[string]spec.Ref, 150), - allRefs: make(map[string]spec.Ref, 150), - }, - patterns: patternAnalysis{ - parameters: make(map[string]string, 150), - headers: make(map[string]string, 150), - items: make(map[string]string, 150), - schemas: make(map[string]string, 150), - allPatterns: make(map[string]string, 150), - }, - } - a.initialize() - return a -} - -// Spec takes a swagger spec object and turns it into a registry -// with a bunch of utility methods to act on the information in the spec -type Spec struct { - spec *spec.Swagger - consumes map[string]struct{} - produces map[string]struct{} - authSchemes map[string]struct{} - operations map[string]map[string]*spec.Operation - references referenceAnalysis - patterns patternAnalysis - allSchemas map[string]SchemaRef - allOfs map[string]SchemaRef -} - -func (s *Spec) reset() { - s.consumes = make(map[string]struct{}, 150) - s.produces = make(map[string]struct{}, 150) - s.authSchemes = make(map[string]struct{}, 150) - s.operations = make(map[string]map[string]*spec.Operation, 150) - s.allSchemas = make(map[string]SchemaRef, 150) - s.allOfs = make(map[string]SchemaRef, 150) - s.references.schemas = make(map[string]spec.Ref, 150) - s.references.pathItems = make(map[string]spec.Ref, 150) - s.references.responses = make(map[string]spec.Ref, 150) - s.references.parameters = make(map[string]spec.Ref, 150) - s.references.items = make(map[string]spec.Ref, 150) - s.references.headerItems = make(map[string]spec.Ref, 150) - s.references.parameterItems = make(map[string]spec.Ref, 150) - s.references.allRefs = make(map[string]spec.Ref, 150) - s.patterns.parameters = make(map[string]string, 150) - s.patterns.headers = make(map[string]string, 150) - s.patterns.items = make(map[string]string, 150) - s.patterns.schemas = make(map[string]string, 150) - s.patterns.allPatterns = make(map[string]string, 150) -} - -func (s *Spec) reload() { - s.reset() - s.initialize() -} - -func (s *Spec) initialize() { - for _, c := range s.spec.Consumes { - s.consumes[c] = struct{}{} - } - for _, c := range s.spec.Produces { - s.produces[c] = struct{}{} - } - for _, ss := range s.spec.Security { - for k := range ss { - s.authSchemes[k] = struct{}{} - } - } - for path, pathItem := range s.AllPaths() { - s.analyzeOperations(path, &pathItem) - } - - for name, parameter := range s.spec.Parameters { - refPref := slashpath.Join("/parameters", jsonpointer.Escape(name)) - if parameter.Items != nil { - s.analyzeItems("items", parameter.Items, refPref, "parameter") - } - if parameter.In == "body" && parameter.Schema != nil { - s.analyzeSchema("schema", *parameter.Schema, refPref) - } - if parameter.Pattern != "" { - s.patterns.addParameterPattern(refPref, parameter.Pattern) - } - } - - for name, response := range s.spec.Responses { - refPref := slashpath.Join("/responses", jsonpointer.Escape(name)) - for k, v := range response.Headers { - hRefPref := slashpath.Join(refPref, "headers", k) - if v.Items != nil { - s.analyzeItems("items", v.Items, hRefPref, "header") - } - if v.Pattern != "" { - s.patterns.addHeaderPattern(hRefPref, v.Pattern) - } - } - if response.Schema != nil { - s.analyzeSchema("schema", *response.Schema, refPref) - } - } - - for name, schema := range s.spec.Definitions { - s.analyzeSchema(name, schema, "/definitions") - } - // TODO: after analyzing all things and flattening schemas etc - // resolve all the collected references to their final representations - // best put in a separate method because this could get expensive -} - -func (s *Spec) analyzeOperations(path string, pi *spec.PathItem) { - // TODO: resolve refs here? - op := pi - if pi.Ref.String() != "" { - key := slashpath.Join("/paths", jsonpointer.Escape(path)) - s.references.addPathItemRef(key, pi) - } - s.analyzeOperation("GET", path, op.Get) - s.analyzeOperation("PUT", path, op.Put) - s.analyzeOperation("POST", path, op.Post) - s.analyzeOperation("PATCH", path, op.Patch) - s.analyzeOperation("DELETE", path, op.Delete) - s.analyzeOperation("HEAD", path, op.Head) - s.analyzeOperation("OPTIONS", path, op.Options) - for i, param := range op.Parameters { - refPref := slashpath.Join("/paths", jsonpointer.Escape(path), "parameters", strconv.Itoa(i)) - if param.Ref.String() != "" { - s.references.addParamRef(refPref, ¶m) - } - if param.Pattern != "" { - s.patterns.addParameterPattern(refPref, param.Pattern) - } - if param.Items != nil { - s.analyzeItems("items", param.Items, refPref, "parameter") - } - if param.Schema != nil { - s.analyzeSchema("schema", *param.Schema, refPref) - } - } -} - -func (s *Spec) analyzeItems(name string, items *spec.Items, prefix, location string) { - if items == nil { - return - } - refPref := slashpath.Join(prefix, name) - s.analyzeItems(name, items.Items, refPref, location) - if items.Ref.String() != "" { - s.references.addItemsRef(refPref, items, location) - } - if items.Pattern != "" { - s.patterns.addItemsPattern(refPref, items.Pattern) - } -} - -func (s *Spec) analyzeOperation(method, path string, op *spec.Operation) { - if op == nil { - return - } - - for _, c := range op.Consumes { - s.consumes[c] = struct{}{} - } - for _, c := range op.Produces { - s.produces[c] = struct{}{} - } - for _, ss := range op.Security { - for k := range ss { - s.authSchemes[k] = struct{}{} - } - } - if _, ok := s.operations[method]; !ok { - s.operations[method] = make(map[string]*spec.Operation) - } - s.operations[method][path] = op - prefix := slashpath.Join("/paths", jsonpointer.Escape(path), strings.ToLower(method)) - for i, param := range op.Parameters { - refPref := slashpath.Join(prefix, "parameters", strconv.Itoa(i)) - if param.Ref.String() != "" { - s.references.addParamRef(refPref, ¶m) - } - if param.Pattern != "" { - s.patterns.addParameterPattern(refPref, param.Pattern) - } - s.analyzeItems("items", param.Items, refPref, "parameter") - if param.In == "body" && param.Schema != nil { - s.analyzeSchema("schema", *param.Schema, refPref) - } - } - if op.Responses != nil { - if op.Responses.Default != nil { - refPref := slashpath.Join(prefix, "responses", "default") - if op.Responses.Default.Ref.String() != "" { - s.references.addResponseRef(refPref, op.Responses.Default) - } - for k, v := range op.Responses.Default.Headers { - hRefPref := slashpath.Join(refPref, "headers", k) - s.analyzeItems("items", v.Items, hRefPref, "header") - if v.Pattern != "" { - s.patterns.addHeaderPattern(hRefPref, v.Pattern) - } - } - if op.Responses.Default.Schema != nil { - s.analyzeSchema("schema", *op.Responses.Default.Schema, refPref) - } - } - for k, res := range op.Responses.StatusCodeResponses { - refPref := slashpath.Join(prefix, "responses", strconv.Itoa(k)) - if res.Ref.String() != "" { - s.references.addResponseRef(refPref, &res) - } - for k, v := range res.Headers { - hRefPref := slashpath.Join(refPref, "headers", k) - s.analyzeItems("items", v.Items, hRefPref, "header") - if v.Pattern != "" { - s.patterns.addHeaderPattern(hRefPref, v.Pattern) - } - } - if res.Schema != nil { - s.analyzeSchema("schema", *res.Schema, refPref) - } - } - } -} - -func (s *Spec) analyzeSchema(name string, schema spec.Schema, prefix string) { - refURI := slashpath.Join(prefix, jsonpointer.Escape(name)) - schRef := SchemaRef{ - Name: name, - Schema: &schema, - Ref: spec.MustCreateRef("#" + refURI), - TopLevel: prefix == "/definitions", - } - - s.allSchemas["#"+refURI] = schRef - - if schema.Ref.String() != "" { - s.references.addSchemaRef(refURI, schRef) - } - if schema.Pattern != "" { - s.patterns.addSchemaPattern(refURI, schema.Pattern) - } - - for k, v := range schema.Definitions { - s.analyzeSchema(k, v, slashpath.Join(refURI, "definitions")) - } - for k, v := range schema.Properties { - s.analyzeSchema(k, v, slashpath.Join(refURI, "properties")) - } - for k, v := range schema.PatternProperties { - s.analyzeSchema(k, v, slashpath.Join(refURI, "patternProperties")) - } - for i, v := range schema.AllOf { - s.analyzeSchema(strconv.Itoa(i), v, slashpath.Join(refURI, "allOf")) - } - if len(schema.AllOf) > 0 { - s.allOfs["#"+refURI] = schRef - } - for i, v := range schema.AnyOf { - s.analyzeSchema(strconv.Itoa(i), v, slashpath.Join(refURI, "anyOf")) - } - for i, v := range schema.OneOf { - s.analyzeSchema(strconv.Itoa(i), v, slashpath.Join(refURI, "oneOf")) - } - if schema.Not != nil { - s.analyzeSchema("not", *schema.Not, refURI) - } - if schema.AdditionalProperties != nil && schema.AdditionalProperties.Schema != nil { - s.analyzeSchema("additionalProperties", *schema.AdditionalProperties.Schema, refURI) - } - if schema.AdditionalItems != nil && schema.AdditionalItems.Schema != nil { - s.analyzeSchema("additionalItems", *schema.AdditionalItems.Schema, refURI) - } - if schema.Items != nil { - if schema.Items.Schema != nil { - s.analyzeSchema("items", *schema.Items.Schema, refURI) - } - for i, sch := range schema.Items.Schemas { - s.analyzeSchema(strconv.Itoa(i), sch, slashpath.Join(refURI, "items")) - } - } -} - -// SecurityRequirement is a representation of a security requirement for an operation -type SecurityRequirement struct { - Name string - Scopes []string -} - -// SecurityRequirementsFor gets the security requirements for the operation -func (s *Spec) SecurityRequirementsFor(operation *spec.Operation) []SecurityRequirement { - if s.spec.Security == nil && operation.Security == nil { - return nil - } - - schemes := s.spec.Security - if operation.Security != nil { - schemes = operation.Security - } - - unique := make(map[string]SecurityRequirement) - for _, scheme := range schemes { - for k, v := range scheme { - if _, ok := unique[k]; !ok { - unique[k] = SecurityRequirement{Name: k, Scopes: v} - } - } - } - - var result []SecurityRequirement - for _, v := range unique { - result = append(result, v) - } - return result -} - -// SecurityDefinitionsFor gets the matching security definitions for a set of requirements -func (s *Spec) SecurityDefinitionsFor(operation *spec.Operation) map[string]spec.SecurityScheme { - requirements := s.SecurityRequirementsFor(operation) - if len(requirements) == 0 { - return nil - } - result := make(map[string]spec.SecurityScheme) - for _, v := range requirements { - if definition, ok := s.spec.SecurityDefinitions[v.Name]; ok { - if definition != nil { - result[v.Name] = *definition - } - } - } - return result -} - -// ConsumesFor gets the mediatypes for the operation -func (s *Spec) ConsumesFor(operation *spec.Operation) []string { - - if len(operation.Consumes) == 0 { - cons := make(map[string]struct{}, len(s.spec.Consumes)) - for _, k := range s.spec.Consumes { - cons[k] = struct{}{} - } - return s.structMapKeys(cons) - } - - cons := make(map[string]struct{}, len(operation.Consumes)) - for _, c := range operation.Consumes { - cons[c] = struct{}{} - } - return s.structMapKeys(cons) -} - -// ProducesFor gets the mediatypes for the operation -func (s *Spec) ProducesFor(operation *spec.Operation) []string { - if len(operation.Produces) == 0 { - prod := make(map[string]struct{}, len(s.spec.Produces)) - for _, k := range s.spec.Produces { - prod[k] = struct{}{} - } - return s.structMapKeys(prod) - } - - prod := make(map[string]struct{}, len(operation.Produces)) - for _, c := range operation.Produces { - prod[c] = struct{}{} - } - return s.structMapKeys(prod) -} - -func mapKeyFromParam(param *spec.Parameter) string { - return fmt.Sprintf("%s#%s", param.In, fieldNameFromParam(param)) -} - -func fieldNameFromParam(param *spec.Parameter) string { - if nm, ok := param.Extensions.GetString("go-name"); ok { - return nm - } - return swag.ToGoName(param.Name) -} - -// ErrorOnParamFunc is a callback function to be invoked -// whenever an error is encountered while resolving references -// on parameters. -// This function takes as input the spec.Parameter which triggered the -// error and the error itself. -// If the callback function returns false, the calling function should bail. -// If it returns true, the calling function should continue evaluating parameters. -// A nil ErrorOnParamFunc must be evaluated as equivalent to panic(). -type ErrorOnParamFunc func(spec.Parameter, error) bool - -func (s *Spec) paramsAsMap(parameters []spec.Parameter, res map[string]spec.Parameter, callmeOnError ErrorOnParamFunc) { - for _, param := range parameters { - pr := param - if pr.Ref.String() != "" { - obj, _, err := pr.Ref.GetPointer().Get(s.spec) - if err != nil { - if callmeOnError != nil { - if callmeOnError(param, fmt.Errorf("invalid reference: %q", pr.Ref.String())) { - continue - } - break - } else { - panic(fmt.Sprintf("invalid reference: %q", pr.Ref.String())) - } - } - if objAsParam, ok := obj.(spec.Parameter); ok { - pr = objAsParam - } else { - if callmeOnError != nil { - if callmeOnError(param, fmt.Errorf("resolved reference is not a parameter: %q", pr.Ref.String())) { - continue - } - break - } else { - panic(fmt.Sprintf("resolved reference is not a parameter: %q", pr.Ref.String())) - } - } - } - res[mapKeyFromParam(&pr)] = pr - } -} - -// ParametersFor the specified operation id. -// Assumes parameters properly resolve references if any and that -// such references actually resolve to a parameter object. -// Otherwise, panics. -func (s *Spec) ParametersFor(operationID string) []spec.Parameter { - return s.SafeParametersFor(operationID, nil) -} - -// SafeParametersFor the specified operation id. -// Do not assume parameters properly resolve references or that -// such references actually resolve to a parameter object. -// Upon error, invoke a ErrorOnParamFunc callback with the erroneous -// parameter. If the callback is set to nil, panics upon errors. -func (s *Spec) SafeParametersFor(operationID string, callmeOnError ErrorOnParamFunc) []spec.Parameter { - gatherParams := func(pi *spec.PathItem, op *spec.Operation) []spec.Parameter { - bag := make(map[string]spec.Parameter) - s.paramsAsMap(pi.Parameters, bag, callmeOnError) - s.paramsAsMap(op.Parameters, bag, callmeOnError) - - var res []spec.Parameter - for _, v := range bag { - res = append(res, v) - } - return res - } - for _, pi := range s.spec.Paths.Paths { - if pi.Get != nil && pi.Get.ID == operationID { - return gatherParams(&pi, pi.Get) - } - if pi.Head != nil && pi.Head.ID == operationID { - return gatherParams(&pi, pi.Head) - } - if pi.Options != nil && pi.Options.ID == operationID { - return gatherParams(&pi, pi.Options) - } - if pi.Post != nil && pi.Post.ID == operationID { - return gatherParams(&pi, pi.Post) - } - if pi.Patch != nil && pi.Patch.ID == operationID { - return gatherParams(&pi, pi.Patch) - } - if pi.Put != nil && pi.Put.ID == operationID { - return gatherParams(&pi, pi.Put) - } - if pi.Delete != nil && pi.Delete.ID == operationID { - return gatherParams(&pi, pi.Delete) - } - } - return nil -} - -// ParamsFor the specified method and path. Aggregates them with the defaults etc, so it's all the params that -// apply for the method and path. -// Assumes parameters properly resolve references if any and that -// such references actually resolve to a parameter object. -// Otherwise, panics. -func (s *Spec) ParamsFor(method, path string) map[string]spec.Parameter { - return s.SafeParamsFor(method, path, nil) -} - -// SafeParamsFor the specified method and path. Aggregates them with the defaults etc, so it's all the params that -// Do not assume parameters properly resolve references or that -// such references actually resolve to a parameter object. -// Upon error, invoke a ErrorOnParamFunc callback with the erroneous -// parameter. If the callback is set to nil, panics upon errors. -func (s *Spec) SafeParamsFor(method, path string, callmeOnError ErrorOnParamFunc) map[string]spec.Parameter { - res := make(map[string]spec.Parameter) - if pi, ok := s.spec.Paths.Paths[path]; ok { - s.paramsAsMap(pi.Parameters, res, callmeOnError) - s.paramsAsMap(s.operations[strings.ToUpper(method)][path].Parameters, res, callmeOnError) - } - return res -} - -// OperationForName gets the operation for the given id -func (s *Spec) OperationForName(operationID string) (string, string, *spec.Operation, bool) { - for method, pathItem := range s.operations { - for path, op := range pathItem { - if operationID == op.ID { - return method, path, op, true - } - } - } - return "", "", nil, false -} - -// OperationFor the given method and path -func (s *Spec) OperationFor(method, path string) (*spec.Operation, bool) { - if mp, ok := s.operations[strings.ToUpper(method)]; ok { - op, fn := mp[path] - return op, fn - } - return nil, false -} - -// Operations gathers all the operations specified in the spec document -func (s *Spec) Operations() map[string]map[string]*spec.Operation { - return s.operations -} - -func (s *Spec) structMapKeys(mp map[string]struct{}) []string { - if len(mp) == 0 { - return nil - } - - result := make([]string, 0, len(mp)) - for k := range mp { - result = append(result, k) - } - return result -} - -// AllPaths returns all the paths in the swagger spec -func (s *Spec) AllPaths() map[string]spec.PathItem { - if s.spec == nil || s.spec.Paths == nil { - return nil - } - return s.spec.Paths.Paths -} - -// OperationIDs gets all the operation ids based on method an dpath -func (s *Spec) OperationIDs() []string { - if len(s.operations) == 0 { - return nil - } - result := make([]string, 0, len(s.operations)) - for method, v := range s.operations { - for p, o := range v { - if o.ID != "" { - result = append(result, o.ID) - } else { - result = append(result, fmt.Sprintf("%s %s", strings.ToUpper(method), p)) - } - } - } - return result -} - -// OperationMethodPaths gets all the operation ids based on method an dpath -func (s *Spec) OperationMethodPaths() []string { - if len(s.operations) == 0 { - return nil - } - result := make([]string, 0, len(s.operations)) - for method, v := range s.operations { - for p := range v { - result = append(result, fmt.Sprintf("%s %s", strings.ToUpper(method), p)) - } - } - return result -} - -// RequiredConsumes gets all the distinct consumes that are specified in the specification document -func (s *Spec) RequiredConsumes() []string { - return s.structMapKeys(s.consumes) -} - -// RequiredProduces gets all the distinct produces that are specified in the specification document -func (s *Spec) RequiredProduces() []string { - return s.structMapKeys(s.produces) -} - -// RequiredSecuritySchemes gets all the distinct security schemes that are specified in the swagger spec -func (s *Spec) RequiredSecuritySchemes() []string { - return s.structMapKeys(s.authSchemes) -} - -// SchemaRef is a reference to a schema -type SchemaRef struct { - Name string - Ref spec.Ref - Schema *spec.Schema - TopLevel bool -} - -// SchemasWithAllOf returns schema references to all schemas that are defined -// with an allOf key -func (s *Spec) SchemasWithAllOf() (result []SchemaRef) { - for _, v := range s.allOfs { - result = append(result, v) - } - return -} - -// AllDefinitions returns schema references for all the definitions that were discovered -func (s *Spec) AllDefinitions() (result []SchemaRef) { - for _, v := range s.allSchemas { - result = append(result, v) - } - return -} - -// AllDefinitionReferences returns json refs for all the discovered schemas -func (s *Spec) AllDefinitionReferences() (result []string) { - for _, v := range s.references.schemas { - result = append(result, v.String()) - } - return -} - -// AllParameterReferences returns json refs for all the discovered parameters -func (s *Spec) AllParameterReferences() (result []string) { - for _, v := range s.references.parameters { - result = append(result, v.String()) - } - return -} - -// AllResponseReferences returns json refs for all the discovered responses -func (s *Spec) AllResponseReferences() (result []string) { - for _, v := range s.references.responses { - result = append(result, v.String()) - } - return -} - -// AllPathItemReferences returns the references for all the items -func (s *Spec) AllPathItemReferences() (result []string) { - for _, v := range s.references.pathItems { - result = append(result, v.String()) - } - return -} - -// AllItemsReferences returns the references for all the items -func (s *Spec) AllItemsReferences() (result []string) { - for _, v := range s.references.items { - result = append(result, v.String()) - } - return -} - -// AllReferences returns all the references found in the document -func (s *Spec) AllReferences() (result []string) { - for _, v := range s.references.allRefs { - result = append(result, v.String()) - } - return -} - -// AllRefs returns all the unique references found in the document -func (s *Spec) AllRefs() (result []spec.Ref) { - set := make(map[string]struct{}) - for _, v := range s.references.allRefs { - a := v.String() - if a == "" { - continue - } - if _, ok := set[a]; !ok { - set[a] = struct{}{} - result = append(result, v) - } - } - return -} - -func cloneStringMap(source map[string]string) map[string]string { - res := make(map[string]string, len(source)) - for k, v := range source { - res[k] = v - } - return res -} - -// ParameterPatterns returns all the patterns found in parameters -// the map is cloned to avoid accidental changes -func (s *Spec) ParameterPatterns() map[string]string { - return cloneStringMap(s.patterns.parameters) -} - -// HeaderPatterns returns all the patterns found in response headers -// the map is cloned to avoid accidental changes -func (s *Spec) HeaderPatterns() map[string]string { - return cloneStringMap(s.patterns.headers) -} - -// ItemsPatterns returns all the patterns found in simple array items -// the map is cloned to avoid accidental changes -func (s *Spec) ItemsPatterns() map[string]string { - return cloneStringMap(s.patterns.items) -} - -// SchemaPatterns returns all the patterns found in schemas -// the map is cloned to avoid accidental changes -func (s *Spec) SchemaPatterns() map[string]string { - return cloneStringMap(s.patterns.schemas) -} - -// AllPatterns returns all the patterns found in the spec -// the map is cloned to avoid accidental changes -func (s *Spec) AllPatterns() map[string]string { - return cloneStringMap(s.patterns.allPatterns) -} diff --git a/vendor/github.com/go-openapi/analysis/analyzer_test.go b/vendor/github.com/go-openapi/analysis/analyzer_test.go deleted file mode 100644 index 5029d140b..000000000 --- a/vendor/github.com/go-openapi/analysis/analyzer_test.go +++ /dev/null @@ -1,588 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package analysis - -import ( - "encoding/json" - "fmt" - "log" - "os" - "path/filepath" - "sort" - "testing" - - "github.com/go-openapi/loads/fmts" - "github.com/go-openapi/spec" - "github.com/go-openapi/swag" - "github.com/stretchr/testify/assert" -) - -func schemeNames(schemes []SecurityRequirement) []string { - var names []string - for _, v := range schemes { - names = append(names, v.Name) - } - sort.Sort(sort.StringSlice(names)) - return names -} - -func TestAnalyzer(t *testing.T) { - formatParam := spec.QueryParam("format").Typed("string", "") - - limitParam := spec.QueryParam("limit").Typed("integer", "int32") - limitParam.Extensions = spec.Extensions(map[string]interface{}{}) - limitParam.Extensions.Add("go-name", "Limit") - - skipParam := spec.QueryParam("skip").Typed("integer", "int32") - pi := spec.PathItem{} - pi.Parameters = []spec.Parameter{*limitParam} - - op := &spec.Operation{} - op.Consumes = []string{"application/x-yaml"} - op.Produces = []string{"application/x-yaml"} - op.Security = []map[string][]string{ - map[string][]string{"oauth2": []string{}}, - map[string][]string{"basic": nil}, - } - op.ID = "someOperation" - op.Parameters = []spec.Parameter{*skipParam} - pi.Get = op - - pi2 := spec.PathItem{} - pi2.Parameters = []spec.Parameter{*limitParam} - op2 := &spec.Operation{} - op2.ID = "anotherOperation" - op2.Parameters = []spec.Parameter{*skipParam} - pi2.Get = op2 - - spec := &spec.Swagger{ - SwaggerProps: spec.SwaggerProps{ - Consumes: []string{"application/json"}, - Produces: []string{"application/json"}, - Security: []map[string][]string{ - map[string][]string{"apikey": nil}, - }, - SecurityDefinitions: map[string]*spec.SecurityScheme{ - "basic": spec.BasicAuth(), - "apiKey": spec.APIKeyAuth("api_key", "query"), - "oauth2": spec.OAuth2AccessToken("http://authorize.com", "http://token.com"), - }, - Parameters: map[string]spec.Parameter{"format": *formatParam}, - Paths: &spec.Paths{ - Paths: map[string]spec.PathItem{ - "/": pi, - "/items": pi2, - }, - }, - }, - } - analyzer := New(spec) - - assert.Len(t, analyzer.consumes, 2) - assert.Len(t, analyzer.produces, 2) - assert.Len(t, analyzer.operations, 1) - assert.Equal(t, analyzer.operations["GET"]["/"], spec.Paths.Paths["/"].Get) - - expected := []string{"application/x-yaml"} - sort.Sort(sort.StringSlice(expected)) - consumes := analyzer.ConsumesFor(spec.Paths.Paths["/"].Get) - sort.Sort(sort.StringSlice(consumes)) - assert.Equal(t, expected, consumes) - - produces := analyzer.ProducesFor(spec.Paths.Paths["/"].Get) - sort.Sort(sort.StringSlice(produces)) - assert.Equal(t, expected, produces) - - expected = []string{"application/json"} - sort.Sort(sort.StringSlice(expected)) - consumes = analyzer.ConsumesFor(spec.Paths.Paths["/items"].Get) - sort.Sort(sort.StringSlice(consumes)) - assert.Equal(t, expected, consumes) - - produces = analyzer.ProducesFor(spec.Paths.Paths["/items"].Get) - sort.Sort(sort.StringSlice(produces)) - assert.Equal(t, expected, produces) - - expectedSchemes := []SecurityRequirement{SecurityRequirement{"oauth2", []string{}}, SecurityRequirement{"basic", nil}} - schemes := analyzer.SecurityRequirementsFor(spec.Paths.Paths["/"].Get) - assert.Equal(t, schemeNames(expectedSchemes), schemeNames(schemes)) - - securityDefinitions := analyzer.SecurityDefinitionsFor(spec.Paths.Paths["/"].Get) - assert.Equal(t, securityDefinitions["basic"], *spec.SecurityDefinitions["basic"]) - assert.Equal(t, securityDefinitions["oauth2"], *spec.SecurityDefinitions["oauth2"]) - - parameters := analyzer.ParamsFor("GET", "/") - assert.Len(t, parameters, 2) - - operations := analyzer.OperationIDs() - assert.Len(t, operations, 2) - - producers := analyzer.RequiredProduces() - assert.Len(t, producers, 2) - consumers := analyzer.RequiredConsumes() - assert.Len(t, consumers, 2) - authSchemes := analyzer.RequiredSecuritySchemes() - assert.Len(t, authSchemes, 3) - - ops := analyzer.Operations() - assert.Len(t, ops, 1) - assert.Len(t, ops["GET"], 2) - - op, ok := analyzer.OperationFor("get", "/") - assert.True(t, ok) - assert.NotNil(t, op) - - op, ok = analyzer.OperationFor("delete", "/") - assert.False(t, ok) - assert.Nil(t, op) -} - -func TestDefinitionAnalysis(t *testing.T) { - doc, err := loadSpec(filepath.Join("fixtures", "definitions.yml")) - if assert.NoError(t, err) { - analyzer := New(doc) - definitions := analyzer.allSchemas - // parameters - assertSchemaRefExists(t, definitions, "#/parameters/someParam/schema") - assertSchemaRefExists(t, definitions, "#/paths/~1some~1where~1{id}/parameters/1/schema") - assertSchemaRefExists(t, definitions, "#/paths/~1some~1where~1{id}/get/parameters/1/schema") - // responses - assertSchemaRefExists(t, definitions, "#/responses/someResponse/schema") - assertSchemaRefExists(t, definitions, "#/paths/~1some~1where~1{id}/get/responses/default/schema") - assertSchemaRefExists(t, definitions, "#/paths/~1some~1where~1{id}/get/responses/200/schema") - // definitions - assertSchemaRefExists(t, definitions, "#/definitions/tag") - assertSchemaRefExists(t, definitions, "#/definitions/tag/properties/id") - assertSchemaRefExists(t, definitions, "#/definitions/tag/properties/value") - assertSchemaRefExists(t, definitions, "#/definitions/tag/definitions/category") - assertSchemaRefExists(t, definitions, "#/definitions/tag/definitions/category/properties/id") - assertSchemaRefExists(t, definitions, "#/definitions/tag/definitions/category/properties/value") - assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalProps") - assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalProps/additionalProperties") - assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalItems") - assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalItems/items/0") - assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalItems/items/1") - assertSchemaRefExists(t, definitions, "#/definitions/withAdditionalItems/additionalItems") - assertSchemaRefExists(t, definitions, "#/definitions/withNot") - assertSchemaRefExists(t, definitions, "#/definitions/withNot/not") - assertSchemaRefExists(t, definitions, "#/definitions/withAnyOf") - assertSchemaRefExists(t, definitions, "#/definitions/withAnyOf/anyOf/0") - assertSchemaRefExists(t, definitions, "#/definitions/withAnyOf/anyOf/1") - assertSchemaRefExists(t, definitions, "#/definitions/withAllOf") - assertSchemaRefExists(t, definitions, "#/definitions/withAllOf/allOf/0") - assertSchemaRefExists(t, definitions, "#/definitions/withAllOf/allOf/1") - allOfs := analyzer.allOfs - assert.Len(t, allOfs, 1) - assert.Contains(t, allOfs, "#/definitions/withAllOf") - } -} - -func loadSpec(path string) (*spec.Swagger, error) { - spec.PathLoader = func(path string) (json.RawMessage, error) { - ext := filepath.Ext(path) - if ext == ".yml" || ext == ".yaml" { - return fmts.YAMLDoc(path) - } - data, err := swag.LoadFromFileOrHTTP(path) - if err != nil { - return nil, err - } - return json.RawMessage(data), nil - } - data, err := fmts.YAMLDoc(path) - if err != nil { - return nil, err - } - - var sw spec.Swagger - if err := json.Unmarshal(data, &sw); err != nil { - return nil, err - } - return &sw, nil -} - -func TestReferenceAnalysis(t *testing.T) { - doc, err := loadSpec(filepath.Join("fixtures", "references.yml")) - if assert.NoError(t, err) { - definitions := New(doc).references - - // parameters - assertRefExists(t, definitions.parameters, "#/paths/~1some~1where~1{id}/parameters/0") - assertRefExists(t, definitions.parameters, "#/paths/~1some~1where~1{id}/get/parameters/0") - - // path items - assertRefExists(t, definitions.pathItems, "#/paths/~1other~1place") - - // responses - assertRefExists(t, definitions.responses, "#/paths/~1some~1where~1{id}/get/responses/404") - - // definitions - assertRefExists(t, definitions.schemas, "#/responses/notFound/schema") - assertRefExists(t, definitions.schemas, "#/paths/~1some~1where~1{id}/get/responses/200/schema") - assertRefExists(t, definitions.schemas, "#/definitions/tag/properties/audit") - - // items - assertRefExists(t, definitions.allRefs, "#/paths/~1some~1where~1{id}/get/parameters/1/items") - } -} - -func assertRefExists(t testing.TB, data map[string]spec.Ref, key string) bool { - if _, ok := data[key]; !ok { - return assert.Fail(t, fmt.Sprintf("expected %q to exist in the ref bag", key)) - } - return true -} - -func assertSchemaRefExists(t testing.TB, data map[string]SchemaRef, key string) bool { - if _, ok := data[key]; !ok { - return assert.Fail(t, fmt.Sprintf("expected %q to exist in schema ref bag", key)) - } - return true -} - -func TestPatternAnalysis(t *testing.T) { - doc, err := loadSpec(filepath.Join("fixtures", "patterns.yml")) - if assert.NoError(t, err) { - pt := New(doc).patterns - - // parameters - assertPattern(t, pt.parameters, "#/parameters/idParam", "a[A-Za-Z0-9]+") - assertPattern(t, pt.parameters, "#/paths/~1some~1where~1{id}/parameters/1", "b[A-Za-z0-9]+") - assertPattern(t, pt.parameters, "#/paths/~1some~1where~1{id}/get/parameters/0", "[abc][0-9]+") - - // responses - assertPattern(t, pt.headers, "#/responses/notFound/headers/ContentLength", "[0-9]+") - assertPattern(t, pt.headers, "#/paths/~1some~1where~1{id}/get/responses/200/headers/X-Request-Id", "d[A-Za-z0-9]+") - - // definitions - assertPattern(t, pt.schemas, "#/paths/~1other~1place/post/parameters/0/schema/properties/value", "e[A-Za-z0-9]+") - assertPattern(t, pt.schemas, "#/paths/~1other~1place/post/responses/200/schema/properties/data", "[0-9]+[abd]") - assertPattern(t, pt.schemas, "#/definitions/named", "f[A-Za-z0-9]+") - assertPattern(t, pt.schemas, "#/definitions/tag/properties/value", "g[A-Za-z0-9]+") - - // items - assertPattern(t, pt.items, "#/paths/~1some~1where~1{id}/get/parameters/1/items", "c[A-Za-z0-9]+") - assertPattern(t, pt.items, "#/paths/~1other~1place/post/responses/default/headers/Via/items", "[A-Za-z]+") - } -} - -func assertPattern(t testing.TB, data map[string]string, key, pattern string) bool { - if assert.Contains(t, data, key) { - return assert.Equal(t, pattern, data[key]) - } - return false -} - -func panickerParamsAsMap() { - s := prepareTestParamsInvalid("fixture-342.yaml") - if s == nil { - return - } - m := make(map[string]spec.Parameter) - if pi, ok := s.spec.Paths.Paths["/fixture"]; ok { - pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters - s.paramsAsMap(pi.Parameters, m, nil) - } -} - -func panickerParamsAsMap2() { - s := prepareTestParamsInvalid("fixture-342-2.yaml") - if s == nil { - return - } - m := make(map[string]spec.Parameter) - if pi, ok := s.spec.Paths.Paths["/fixture"]; ok { - pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters - s.paramsAsMap(pi.Parameters, m, nil) - } -} - -func panickerParamsAsMap3() { - s := prepareTestParamsInvalid("fixture-342-3.yaml") - if s == nil { - return - } - m := make(map[string]spec.Parameter) - if pi, ok := s.spec.Paths.Paths["/fixture"]; ok { - pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters - s.paramsAsMap(pi.Parameters, m, nil) - } -} - -func TestAnalyzer_paramsAsMap(Pt *testing.T) { - s := prepareTestParamsValid() - if assert.NotNil(Pt, s) { - m := make(map[string]spec.Parameter) - pi, ok := s.spec.Paths.Paths["/items"] - if assert.True(Pt, ok) { - //func (s *Spec) paramsAsMap(parameters []spec.Parameter, res map[string]spec.Parameter, callmeOnError ErrorOnParamFunc) { - s.paramsAsMap(pi.Parameters, m, nil) - // TODO: Assert? - } - } - - // An invalid spec, but passes this step (errors are figured out at a higher level) - s = prepareTestParamsInvalid("fixture-1289-param.yaml") - if assert.NotNil(Pt, s) { - m := make(map[string]spec.Parameter) - pi, ok := s.spec.Paths.Paths["/fixture"] - if assert.True(Pt, ok) { - pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters - //func (s *Spec) paramsAsMap(parameters []spec.Parameter, res map[string]spec.Parameter, callmeOnError ErrorOnParamFunc) { - s.paramsAsMap(pi.Parameters, m, nil) - // TODO: Assert? - } - } -} - -func TestAnalyzer_paramsAsMapWithCallback(Pt *testing.T) { - s := prepareTestParamsInvalid("fixture-342.yaml") - if assert.NotNil(Pt, s) { - // No bail out callback - m := make(map[string]spec.Parameter) - e := []string{} - pi, ok := s.spec.Paths.Paths["/fixture"] - if assert.True(Pt, ok) { - //func (s *Spec) paramsAsMap(parameters []spec.Parameter, res map[string]spec.Parameter, callmeOnError ErrorOnParamFunc) { - pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters - s.paramsAsMap(pi.Parameters, m, func(param spec.Parameter, err error) bool { - //Pt.Logf("ERROR on %+v : %v", param, err) - e = append(e, err.Error()) - return true // Continue - }) - } - assert.Contains(Pt, e, `resolved reference is not a parameter: "#/definitions/sample_info/properties/sid"`) - assert.Contains(Pt, e, `invalid reference: "#/definitions/sample_info/properties/sids"`) - - // bail out callback - m = make(map[string]spec.Parameter) - e = []string{} - pi, ok = s.spec.Paths.Paths["/fixture"] - if assert.True(Pt, ok) { - //func (s *Spec) paramsAsMap(parameters []spec.Parameter, res map[string]spec.Parameter, callmeOnError ErrorOnParamFunc) { - pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters - s.paramsAsMap(pi.Parameters, m, func(param spec.Parameter, err error) bool { - //Pt.Logf("ERROR on %+v : %v", param, err) - e = append(e, err.Error()) - return false // Bail out - }) - } - // We got one then bail out - assert.Len(Pt, e, 1) - } - - // Bail out after ref failure: exercising another path - s = prepareTestParamsInvalid("fixture-342-2.yaml") - if assert.NotNil(Pt, s) { - // bail out callback - m := make(map[string]spec.Parameter) - e := []string{} - pi, ok := s.spec.Paths.Paths["/fixture"] - if assert.True(Pt, ok) { - //func (s *Spec) paramsAsMap(parameters []spec.Parameter, res map[string]spec.Parameter, callmeOnError ErrorOnParamFunc) { - pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters - s.paramsAsMap(pi.Parameters, m, func(param spec.Parameter, err error) bool { - //Pt.Logf("ERROR on %+v : %v", param, err) - e = append(e, err.Error()) - return false // Bail out - }) - } - // We got one then bail out - assert.Len(Pt, e, 1) - } - - // Bail out after ref failure: exercising another path - s = prepareTestParamsInvalid("fixture-342-3.yaml") - if assert.NotNil(Pt, s) { - // bail out callback - m := make(map[string]spec.Parameter) - e := []string{} - pi, ok := s.spec.Paths.Paths["/fixture"] - if assert.True(Pt, ok) { - //func (s *Spec) paramsAsMap(parameters []spec.Parameter, res map[string]spec.Parameter, callmeOnError ErrorOnParamFunc) { - pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters - s.paramsAsMap(pi.Parameters, m, func(param spec.Parameter, err error) bool { - //Pt.Logf("ERROR on %+v : %v", param, err) - e = append(e, err.Error()) - return false // Bail out - }) - } - // We got one then bail out - assert.Len(Pt, e, 1) - } -} - -func TestAnalyzer_paramsAsMap_Panic(Pt *testing.T) { - assert.Panics(Pt, panickerParamsAsMap) - - // Specifically on invalid resolved type - assert.Panics(Pt, panickerParamsAsMap2) - - // Specifically on invalid ref - assert.Panics(Pt, panickerParamsAsMap3) -} - -func TestAnalyzer_SafeParamsFor(Pt *testing.T) { - s := prepareTestParamsInvalid("fixture-342.yaml") - if assert.NotNil(Pt, s) { - e := []string{} - pi, ok := s.spec.Paths.Paths["/fixture"] - if assert.True(Pt, ok) { - pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters - //func (s *Spec) SafeParamsFor(method, path string, callmeOnError ErrorOnParamFunc) map[string]spec.Parameter { - for range s.SafeParamsFor("Get", "/fixture", func(param spec.Parameter, err error) bool { - e = append(e, err.Error()) - return true // Continue - }) { - assert.Fail(Pt, "There should be no safe parameter in this testcase") - } - } - assert.Contains(Pt, e, `resolved reference is not a parameter: "#/definitions/sample_info/properties/sid"`) - assert.Contains(Pt, e, `invalid reference: "#/definitions/sample_info/properties/sids"`) - - } -} - -func panickerParamsFor() { - s := prepareTestParamsInvalid("fixture-342.yaml") - pi, ok := s.spec.Paths.Paths["/fixture"] - if ok { - pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters - //func (s *Spec) ParamsFor(method, path string) map[string]spec.Parameter { - s.ParamsFor("Get", "/fixture") - } -} - -func TestAnalyzer_ParamsFor(Pt *testing.T) { - // Valid example - s := prepareTestParamsValid() - if assert.NotNil(Pt, s) { - - params := s.ParamsFor("Get", "/items") - assert.True(Pt, len(params) > 0) - } - - // Invalid example - assert.Panics(Pt, panickerParamsFor) -} - -func TestAnalyzer_SafeParametersFor(Pt *testing.T) { - s := prepareTestParamsInvalid("fixture-342.yaml") - if assert.NotNil(Pt, s) { - e := []string{} - pi, ok := s.spec.Paths.Paths["/fixture"] - if assert.True(Pt, ok) { - pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters - //func (s *Spec) SafeParametersFor(operationID string, callmeOnError ErrorOnParamFunc) []spec.Parameter { - for range s.SafeParametersFor("fixtureOp", func(param spec.Parameter, err error) bool { - e = append(e, err.Error()) - return true // Continue - }) { - assert.Fail(Pt, "There should be no safe parameter in this testcase") - } - } - assert.Contains(Pt, e, `resolved reference is not a parameter: "#/definitions/sample_info/properties/sid"`) - assert.Contains(Pt, e, `invalid reference: "#/definitions/sample_info/properties/sids"`) - } -} - -func panickerParametersFor() { - s := prepareTestParamsInvalid("fixture-342.yaml") - if s == nil { - return - } - pi, ok := s.spec.Paths.Paths["/fixture"] - if ok { - pi.Parameters = pi.PathItemProps.Get.OperationProps.Parameters - //func (s *Spec) ParametersFor(operationID string) []spec.Parameter { - s.ParametersFor("fixtureOp") - } -} - -func TestAnalyzer_ParametersFor(Pt *testing.T) { - // Valid example - s := prepareTestParamsValid() - params := s.ParamsFor("Get", "/items") - assert.True(Pt, len(params) > 0) - - // Invalid example - assert.Panics(Pt, panickerParametersFor) -} - -func prepareTestParamsValid() *Spec { - formatParam := spec.QueryParam("format").Typed("string", "") - - limitParam := spec.QueryParam("limit").Typed("integer", "int32") - limitParam.Extensions = spec.Extensions(map[string]interface{}{}) - limitParam.Extensions.Add("go-name", "Limit") - - skipParam := spec.QueryParam("skip").Typed("integer", "int32") - pi := spec.PathItem{} - pi.Parameters = []spec.Parameter{*limitParam} - - op := &spec.Operation{} - op.Consumes = []string{"application/x-yaml"} - op.Produces = []string{"application/x-yaml"} - op.Security = []map[string][]string{ - map[string][]string{"oauth2": []string{}}, - map[string][]string{"basic": nil}, - } - op.ID = "someOperation" - op.Parameters = []spec.Parameter{*skipParam} - pi.Get = op - - pi2 := spec.PathItem{} - pi2.Parameters = []spec.Parameter{*limitParam} - op2 := &spec.Operation{} - op2.ID = "anotherOperation" - op2.Parameters = []spec.Parameter{*skipParam} - pi2.Get = op2 - - spec := &spec.Swagger{ - SwaggerProps: spec.SwaggerProps{ - Consumes: []string{"application/json"}, - Produces: []string{"application/json"}, - Security: []map[string][]string{ - map[string][]string{"apikey": nil}, - }, - SecurityDefinitions: map[string]*spec.SecurityScheme{ - "basic": spec.BasicAuth(), - "apiKey": spec.APIKeyAuth("api_key", "query"), - "oauth2": spec.OAuth2AccessToken("http://authorize.com", "http://token.com"), - }, - Parameters: map[string]spec.Parameter{"format": *formatParam}, - Paths: &spec.Paths{ - Paths: map[string]spec.PathItem{ - "/": pi, - "/items": pi2, - }, - }, - }, - } - analyzer := New(spec) - return analyzer -} - -func prepareTestParamsInvalid(fixture string) *Spec { - cwd, _ := os.Getwd() - bp := filepath.Join(cwd, "fixtures", fixture) - spec, err := loadSpec(bp) - if err != nil { - log.Printf("Warning: fixture %s could not be loaded: %v", fixture, err) - return nil - } - analyzer := New(spec) - return analyzer -} diff --git a/vendor/github.com/go-openapi/analysis/fixtures/allOf.yml b/vendor/github.com/go-openapi/analysis/fixtures/allOf.yml deleted file mode 100644 index 531c33aa6..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/allOf.yml +++ /dev/null @@ -1,43 +0,0 @@ ---- -swagger: "2.0" -info: - version: "0.1.0" - title: allOf analysis -paths: - "/some/where/{id}": - parameters: - - name: id - in: path - type: integer - format: int32 - - name: bodyId - in: body - schema: - type: object - get: - parameters: - - name: limit - in: query - type: integer - format: int32 - required: false - - name: body - in: body - schema: - type: object - responses: - default: - schema: - type: object - 200: - schema: - type: object -definitions: - tag: - type: object - properties: - id: - type: integer - format: int64 - value: - type: string diff --git a/vendor/github.com/go-openapi/analysis/fixtures/bar-crud.yml b/vendor/github.com/go-openapi/analysis/fixtures/bar-crud.yml deleted file mode 100644 index 90000f46b..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/bar-crud.yml +++ /dev/null @@ -1,180 +0,0 @@ ---- -swagger: '2.0' -info: - title: bar CRUD API - version: 4.2.0 -schemes: - - http -basePath: /api -consumes: - - application/json -produces: - - application/json -paths: - /common: - get: - operationId: commonGet - summary: here to test path collisons - responses: - '200': - description: OK - schema: - $ref: "#/definitions/bar" - /bars: - post: - operationId: create - summary: Create a new bar - parameters: - - name: info - in: body - schema: - $ref: "#/definitions/bar" - responses: - '201': - description: created - schema: - $ref: "#/definitions/barId" - default: - description: error - schema: - $ref: "#/definitions/error" - /bars/{barid}: - get: - operationId: get - summary: Get a bar by id - parameters: - - $ref: "#/parameters/barid" - responses: - '200': - description: OK - schema: - $ref: "#/definitions/bar" - '401': - $ref: "#/responses/401" - '404': - $ref: "#/responses/404" - default: - description: error - schema: - $ref: "#/definitions/error" - delete: - operationId: delete - summary: delete a bar by id - parameters: - - name: barid - in: path - required: true - type: string - responses: - '200': - description: OK - '401': - description: unauthorized - schema: - $ref: "#/definitions/error" - '404': - description: resource not found - schema: - $ref: "#/definitions/error" - default: - description: error - schema: - $ref: "#/definitions/error" - post: - operationId: update - summary: update a bar by id - parameters: - - name: barid - in: path - required: true - type: string - - name: info - in: body - schema: - $ref: "#/definitions/bar" - responses: - '200': - description: OK - '401': - description: unauthorized - schema: - $ref: "#/definitions/error" - '404': - description: resource not found - schema: - $ref: "#/definitions/error" - default: - description: error - schema: - $ref: "#/definitions/error" - -definitions: - common: - type: object - required: - - id - properties: - id: - type: string - format: string - minLength: 1 - bar: - type: object - required: - - name - - description - properties: - id: - type: string - format: string - readOnly: true - name: - type: string - format: string - minLength: 1 - description: - type: string - format: string - minLength: 1 - barId: - type: object - required: - - id - properties: - id: - type: string - format: string - minLength: 1 - error: - type: object - required: - - message - properties: - code: - type: string - format: string - message: - type: string - fields: - type: string - -parameters: - common: - name: common - in: query - type: string - barid: - name: barid - in: path - required: true - type: string - -responses: - 401: - description: bar unauthorized - schema: - $ref: "#/definitions/error" - 404: - description: bar resource not found - schema: - $ref: "#/definitions/error" diff --git a/vendor/github.com/go-openapi/analysis/fixtures/definitions.yml b/vendor/github.com/go-openapi/analysis/fixtures/definitions.yml deleted file mode 100644 index 63cb17a65..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/definitions.yml +++ /dev/null @@ -1,86 +0,0 @@ ---- -swagger: "2.0" -info: - version: "0.1.0" - title: Definition analysis -parameters: - someParam: - name: someParam - in: body - schema: - type: object -responses: - someResponse: - schema: - type: object -paths: - "/some/where/{id}": - parameters: - - name: id - in: path - type: integer - format: int32 - - name: bodyId - in: body - schema: - type: object - get: - parameters: - - name: limit - in: query - type: integer - format: int32 - required: false - - name: body - in: body - schema: - type: object - responses: - default: - schema: - type: object - 200: - schema: - type: object -definitions: - tag: - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - definitions: - category: - type: object - properties: - id: - type: integer - format: int32 - value: - type: string - withAdditionalProps: - type: object - additionalProperties: - type: boolean - withAdditionalItems: - type: array - items: - - type: string - - type: bool - additionalItems: - type: integer - format: int32 - withNot: - type: object - not: - $ref: "#/definitions/tag" - withAnyOf: - anyOf: - - type: object - - type: string - withAllOf: - allOf: - - type: object - - type: string diff --git a/vendor/github.com/go-openapi/analysis/fixtures/empty-paths.json b/vendor/github.com/go-openapi/analysis/fixtures/empty-paths.json deleted file mode 100644 index 30e600923..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/empty-paths.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "title": "empty-paths", - "version": "79.2.1" - }, - "paths": {} -} diff --git a/vendor/github.com/go-openapi/analysis/fixtures/external/definitions.yml b/vendor/github.com/go-openapi/analysis/fixtures/external/definitions.yml deleted file mode 100644 index 009cba27c..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/external/definitions.yml +++ /dev/null @@ -1,50 +0,0 @@ -definitions: - named: - type: string - tag: - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - audit: - $ref: "#/definitions/record" - record: - type: object - properties: - createdAt: - type: string - format: date-time - - nestedThing: - type: object - properties: - record: - type: array - items: - - type: string - format: date-time - - type: object - properties: - createdAt: - type: string - format: date-time - - allOf: - - type: string - format: date - - type: object - additionalProperties: - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - properties: - value: - type: string - name: - $ref: "definitions2.yml#/coordinate" \ No newline at end of file diff --git a/vendor/github.com/go-openapi/analysis/fixtures/external/definitions2.yml b/vendor/github.com/go-openapi/analysis/fixtures/external/definitions2.yml deleted file mode 100644 index 08f70c0ea..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/external/definitions2.yml +++ /dev/null @@ -1,9 +0,0 @@ -coordinate: - type: object - properties: - id: - type: integer - format: int64 - createdAt: - type: string - format: date-time \ No newline at end of file diff --git a/vendor/github.com/go-openapi/analysis/fixtures/external/errors.yml b/vendor/github.com/go-openapi/analysis/fixtures/external/errors.yml deleted file mode 100644 index d37a1bdd4..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/external/errors.yml +++ /dev/null @@ -1,13 +0,0 @@ -error: - type: object - required: - - id - - message - properties: - id: - type: integer - format: int64 - readOnly: true - message: - type: string - readOnly: true diff --git a/vendor/github.com/go-openapi/analysis/fixtures/external/nestedParams.yml b/vendor/github.com/go-openapi/analysis/fixtures/external/nestedParams.yml deleted file mode 100644 index c11c0d8f0..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/external/nestedParams.yml +++ /dev/null @@ -1,35 +0,0 @@ -bodyParam: - name: body - in: body - schema: - type: object - properties: - record: - type: array - items: - - type: string - format: date-time - - type: object - properties: - createdAt: - type: string - format: date-time - - allOf: - - type: string - format: date - - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - name: - type: object - properties: - id: - type: integer - format: int64 - createdAt: - type: string - format: date-time \ No newline at end of file diff --git a/vendor/github.com/go-openapi/analysis/fixtures/external/nestedResponses.yml b/vendor/github.com/go-openapi/analysis/fixtures/external/nestedResponses.yml deleted file mode 100644 index 2d6583c05..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/external/nestedResponses.yml +++ /dev/null @@ -1,32 +0,0 @@ -genericResponse: - type: object - properties: - record: - type: array - items: - - type: string - format: date-time - - type: object - properties: - createdAt: - type: string - format: date-time - - allOf: - - type: string - format: date - - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - name: - type: object - properties: - id: - type: integer - format: int64 - createdAt: - type: string - format: date-time \ No newline at end of file diff --git a/vendor/github.com/go-openapi/analysis/fixtures/external/parameters.yml b/vendor/github.com/go-openapi/analysis/fixtures/external/parameters.yml deleted file mode 100644 index b31a4485a..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/external/parameters.yml +++ /dev/null @@ -1,12 +0,0 @@ -parameters: - idParam: - name: id - in: path - type: integer - format: int32 - limitParam: - name: limit - in: query - type: integer - format: int32 - required: false \ No newline at end of file diff --git a/vendor/github.com/go-openapi/analysis/fixtures/external/pathItem.yml b/vendor/github.com/go-openapi/analysis/fixtures/external/pathItem.yml deleted file mode 100644 index 22a7aa634..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/external/pathItem.yml +++ /dev/null @@ -1,9 +0,0 @@ -get: - operationId: modelOp - summary: many model variations - description: Used to see if a codegen can render all the possible parameter variations for a header param - tags: - - testcgen - responses: - default: - description: Generic Out \ No newline at end of file diff --git a/vendor/github.com/go-openapi/analysis/fixtures/external/responses.yml b/vendor/github.com/go-openapi/analysis/fixtures/external/responses.yml deleted file mode 100644 index 8730d64c1..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/external/responses.yml +++ /dev/null @@ -1,4 +0,0 @@ -responses: - notFound: - schema: - $ref: "errors.yml#/error" \ No newline at end of file diff --git a/vendor/github.com/go-openapi/analysis/fixtures/external_definitions.yml b/vendor/github.com/go-openapi/analysis/fixtures/external_definitions.yml deleted file mode 100644 index 032f2f320..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/external_definitions.yml +++ /dev/null @@ -1,95 +0,0 @@ ---- -swagger: "2.0" -info: - version: "0.1.0" - title: reference analysis - -parameters: - someParam: - name: someParam - in: body - schema: - $ref: "external/definitions.yml#/definitions/record" -responses: - someResponse: - schema: - $ref: "external/definitions.yml#/definitions/record" -paths: - "/some/where/{id}": - parameters: - - $ref: "external/parameters.yml#/parameters/idParam" - - - name: bodyId - in: body - schema: - $ref: "external/definitions.yml#/definitions/record" - get: - parameters: - - $ref: "external/parameters.yml#/parameters/limitParam" - - name: other - in: query - type: array - items: - $ref: "external/definitions.yml#/definitions/named" - - name: body - in: body - schema: - $ref: "external/definitions.yml#/definitions/record" - responses: - default: - schema: - $ref: "external/definitions.yml#/definitions/record" - 404: - $ref: "external/responses.yml#/responses/notFound" - 200: - schema: - $ref: "external/definitions.yml#/definitions/tag" - "/other/place": - $ref: "external/pathItem.yml" - -definitions: - namedAgain: - $ref: "external/definitions.yml#/definitions/named" - - datedTag: - allOf: - - type: string - format: date - - $ref: "external/definitions.yml#/definitions/tag" - - records: - type: array - items: - - $ref: "external/definitions.yml#/definitions/record" - - datedRecords: - type: array - items: - - type: string - format: date-time - - $ref: "external/definitions.yml#/definitions/record" - - datedTaggedRecords: - type: array - items: - - type: string - format: date-time - - $ref: "external/definitions.yml#/definitions/record" - additionalItems: - $ref: "external/definitions.yml#/definitions/tag" - - otherRecords: - type: array - items: - $ref: "external/definitions.yml#/definitions/record" - - tags: - type: object - additionalProperties: - $ref: "external/definitions.yml#/definitions/tag" - - namedThing: - type: object - properties: - name: - $ref: "external/definitions.yml#/definitions/named" \ No newline at end of file diff --git a/vendor/github.com/go-openapi/analysis/fixtures/fixture-1289-param.yaml b/vendor/github.com/go-openapi/analysis/fixtures/fixture-1289-param.yaml deleted file mode 100644 index 59cb01ce8..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/fixture-1289-param.yaml +++ /dev/null @@ -1,31 +0,0 @@ ---- -swagger: '2.0' -info: - title: 'fixture 1289' - description: an invalid spec but which passes the analysis stage - version: '1.0' -produces: - - application/json -paths: - '/fixture': - get: - operationId: fixtureOp - parameters: - - $ref: '#/parameters/getSomeIds' - responses: - '200': - -parameters: - getSomeIds: - name: despicableMe - in: body - description: a bad parameter description - schema: - type: object - properties: - someIds: - # Wrong now - $ref: '#/definitions/someIds' - type: array - someIds: - type: string diff --git a/vendor/github.com/go-openapi/analysis/fixtures/fixture-342-2.yaml b/vendor/github.com/go-openapi/analysis/fixtures/fixture-342-2.yaml deleted file mode 100644 index 76d25ef04..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/fixture-342-2.yaml +++ /dev/null @@ -1,38 +0,0 @@ -swagger: '2.0' -info: - title: issue-342-2 - description: | - A spec which triggers a panic because of invalid ref - version: 0.0.1 - license: - name: MIT -host: localhost:8081 -basePath: /api/v1 -schemes: - - http -consumes: - - application/json -produces: - - application/json -paths: - /fixture: - get: - tags: - - maindata - operationID: fixtureOp - parameters: - # Wrong: a whole schema replaces the parameter - - name: wrongme - in: query - required: true - $ref: "#/definitions/sample_info/properties/sid" - responses: - '200': - -definitions: - sample_info: - type: object - properties: - sid: - type: string - diff --git a/vendor/github.com/go-openapi/analysis/fixtures/fixture-342-3.yaml b/vendor/github.com/go-openapi/analysis/fixtures/fixture-342-3.yaml deleted file mode 100644 index 5210e5c94..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/fixture-342-3.yaml +++ /dev/null @@ -1,38 +0,0 @@ -swagger: '2.0' -info: - title: issue-342 - description: | - A spec which triggers a panic because of invalid type assertion on parameters - version: 0.0.1 - license: - name: MIT -host: localhost:8081 -basePath: /api/v1 -schemes: - - http -consumes: - - application/json -produces: - - application/json -paths: - /fixture: - get: - tags: - - maindata - operationID: fixtureOp - parameters: - # Wrong: invalid ref - - name: despicableme - in: query - required: true - $ref: "#/definitions/sample_info/properties/sids" - responses: - '200': - -definitions: - sample_info: - type: object - properties: - sid: - type: string - diff --git a/vendor/github.com/go-openapi/analysis/fixtures/fixture-342.yaml b/vendor/github.com/go-openapi/analysis/fixtures/fixture-342.yaml deleted file mode 100644 index c806e09cf..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/fixture-342.yaml +++ /dev/null @@ -1,43 +0,0 @@ -swagger: '2.0' -info: - title: issue-342 - description: | - A spec which triggers a panic because of invalid type assertion on parameters - version: 0.0.1 - license: - name: MIT -host: localhost:8081 -basePath: /api/v1 -schemes: - - http -consumes: - - application/json -produces: - - application/json -paths: - /fixture: - get: - tags: - - maindata - operationID: fixtureOp - parameters: - # Wrong: a whole schema replaces the parameter - - name: wrongme - in: query - required: true - $ref: "#/definitions/sample_info/properties/sid" - # Wrong: invalid ref - - name: despicableme - in: query - required: true - $ref: "#/definitions/sample_info/properties/sids" - responses: - '200': - -definitions: - sample_info: - type: object - properties: - sid: - type: string - diff --git a/vendor/github.com/go-openapi/analysis/fixtures/flatten.yml b/vendor/github.com/go-openapi/analysis/fixtures/flatten.yml deleted file mode 100644 index d3bd8d9a5..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/flatten.yml +++ /dev/null @@ -1,85 +0,0 @@ ---- -swagger: "2.0" -info: - version: "0.1.0" - title: reference analysis - -parameters: - someParam: - name: some - in: query - type: string -responses: - notFound: - description: "Not Found" - schema: - $ref: "external/errors.yml#/error" - -paths: - "/some/where/{id}": - parameters: - - $ref: "external/parameters.yml#/parameters/idParam" - - get: - parameters: - - $ref: "external/parameters.yml#/parameters/limitParam" - - $ref: "#/parameters/someParam" - - name: other - in: query - type: string - - $ref: "external/nestedParams.yml#/bodyParam" - - responses: - default: - $ref: "external/nestedResponses.yml#/genericResponse" - 404: - $ref: "#/responses/notFound" - 200: - description: "RecordHolder" - schema: - type: object - properties: - record: - $ref: "external/definitions.yml#/definitions/nestedThing" - "/other/place": - $ref: "external/pathItem.yml" - -definitions: - namedAgain: - $ref: "external/definitions.yml#/definitions/named" - - datedTag: - allOf: - - type: string - format: date - - $ref: "external/definitions.yml#/definitions/tag" - - records: - type: array - items: - - $ref: "external/definitions.yml#/definitions/record" - - datedRecords: - type: array - items: - - type: string - format: date-time - - $ref: "external/definitions.yml#/definitions/record" - - otherRecords: - type: array - items: - $ref: "external/definitions.yml#/definitions/record" - - tags: - type: object - additionalProperties: - $ref: "external/definitions.yml#/definitions/tag" - - namedThing: - type: object - properties: - name: - $ref: "external/definitions.yml#/definitions/named" - namedAgain: - $ref: "#/definitions/namedAgain" diff --git a/vendor/github.com/go-openapi/analysis/fixtures/foo-crud.yml b/vendor/github.com/go-openapi/analysis/fixtures/foo-crud.yml deleted file mode 100644 index 2e3d1f60f..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/foo-crud.yml +++ /dev/null @@ -1,180 +0,0 @@ ---- -swagger: '2.0' -info: - title: foo CRUD API - version: 4.2.0 -schemes: - - http -basePath: /api -consumes: - - application/json -produces: - - application/json -paths: - /common: - get: - operationId: commonGet - summary: here to test path collisons - responses: - '200': - description: OK - schema: - $ref: "#/definitions/foo" - /foos: - post: - operationId: create - summary: Create a new foo - parameters: - - name: info - in: body - schema: - $ref: "#/definitions/foo" - responses: - '201': - description: created - schema: - $ref: "#/definitions/fooId" - default: - description: error - schema: - $ref: "#/definitions/error" - /foos/{fooid}: - get: - operationId: get - summary: Get a foo by id - parameters: - - $ref: "#/parameters/fooid" - responses: - '200': - description: OK - schema: - $ref: "#/definitions/foo" - '401': - $ref: "#/responses/401" - '404': - $ref: "#/responses/404" - default: - description: error - schema: - $ref: "#/definitions/error" - delete: - operationId: delete - summary: delete a foo by id - parameters: - - name: fooid - in: path - required: true - type: string - responses: - '200': - description: OK - '401': - description: unauthorized - schema: - $ref: "#/definitions/error" - '404': - description: resource not found - schema: - $ref: "#/definitions/error" - default: - description: error - schema: - $ref: "#/definitions/error" - post: - operationId: update - summary: update a foo by id - parameters: - - name: fooid - in: path - required: true - type: string - - name: info - in: body - schema: - $ref: "#/definitions/foo" - responses: - '200': - description: OK - '401': - description: unauthorized - schema: - $ref: "#/definitions/error" - '404': - description: resource not found - schema: - $ref: "#/definitions/error" - default: - description: error - schema: - $ref: "#/definitions/error" - -definitions: - common: - type: object - required: - - id - properties: - id: - type: string - format: string - minLength: 1 - foo: - type: object - required: - - name - - description - properties: - id: - type: string - format: string - readOnly: true - name: - type: string - format: string - minLength: 1 - description: - type: string - format: string - minLength: 1 - fooId: - type: object - required: - - id - properties: - id: - type: string - format: string - minLength: 1 - error: - type: object - required: - - message - properties: - code: - type: string - format: string - message: - type: string - fields: - type: string - -parameters: - common: - name: common - in: query - type: string - fooid: - name: fooid - in: path - required: true - type: string - -responses: - 401: - description: foo unauthorized - schema: - $ref: "#/definitions/error" - 404: - description: foo resource not found - schema: - $ref: "#/definitions/error" diff --git a/vendor/github.com/go-openapi/analysis/fixtures/inline_schemas.yml b/vendor/github.com/go-openapi/analysis/fixtures/inline_schemas.yml deleted file mode 100644 index 59699571e..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/inline_schemas.yml +++ /dev/null @@ -1,187 +0,0 @@ ---- -swagger: "2.0" -info: - version: "0.1.0" - title: reference analysis - -parameters: - someParam: - name: someParam - in: body - schema: - type: object - properties: - createdAt: - type: string - format: date-time -responses: - someResponse: - schema: - type: object - properties: - createdAt: - type: string - format: date-time -paths: - "/some/where/{id}": - parameters: - - name: id - in: path - type: integer - format: int32 - - - name: bodyId - in: body - schema: - type: object - properties: - createdAt: - type: string - format: date-time - post: - responses: - default: - description: all good - get: - parameters: - - name: limit - in: query - type: integer - format: int32 - required: false - - name: other - in: query - type: array - items: - type: object - properties: - id: - type: integer - format: int64 - - name: body - in: body - schema: - type: object - properties: - createdAt: - type: string - format: date-time - responses: - default: - schema: - type: object - properties: - createdAt: - type: string - format: date-time - 404: - schema: - $ref: "errors.yml#/error" - 200: - schema: - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - "/other/place": - $ref: "external/pathItem.yml" - -definitions: - namedAgain: - type: object - properties: - id: - type: integer - format: int64 - - datedTag: - allOf: - - type: string - format: date - - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - - records: - type: array - items: - - type: object - properties: - createdAt: - type: string - format: date-time - - datedRecords: - type: array - items: - - type: string - format: date-time - - type: object - properties: - createdAt: - type: string - format: date-time - - datedTaggedRecords: - type: array - items: - - type: string - format: date-time - - type: object - properties: - createdAt: - type: string - format: date-time - additionalItems: - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - - otherRecords: - type: array - items: - type: object - properties: - createdAt: - type: string - format: date-time - - tags: - type: object - additionalProperties: - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - - namedThing: - type: object - properties: - name: - type: object - properties: - id: - type: integer - format: int64 - - # depth first should have this at the bottom, it's just a very long name - pneumonoultramicroscopicsilicovolcanoconiosisAntidisestablishmentarianism: - type: object - properties: - floccinaucinihilipilificationCreatedAt: - type: integer - format: int64 diff --git a/vendor/github.com/go-openapi/analysis/fixtures/nested_inline_schemas.yml b/vendor/github.com/go-openapi/analysis/fixtures/nested_inline_schemas.yml deleted file mode 100644 index 6acf3b340..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/nested_inline_schemas.yml +++ /dev/null @@ -1,298 +0,0 @@ ---- -swagger: "2.0" -info: - version: "0.1.0" - title: reference analysis - -parameters: - someParam: - name: someParam - in: body - schema: - type: object - properties: - createdAt: - type: string - format: date-time -responses: - someResponse: - schema: - type: object - properties: - createdAt: - type: string - format: date-time -paths: - "/some/where/{id}": - parameters: - - name: id - in: path - type: integer - format: int32 - - - name: bodyId - in: body - schema: - type: array - items: - type: object - properties: - createdAt: - type: string - format: date-time - post: - responses: - default: - description: all good - get: - parameters: - - name: limit - in: query - type: integer - format: int32 - required: false - - name: other - in: query - type: array - items: - type: object - properties: - id: - type: integer - format: int64 - - name: body - in: body - schema: - type: object - properties: - record: - type: array - items: - - type: string - format: date-time - - type: object - properties: - createdAt: - type: string - format: date-time - - allOf: - - type: string - format: date - - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - name: - type: object - properties: - id: - type: integer - format: int64 - createdAt: - type: string - format: date-time - responses: - default: - schema: - type: object - properties: - record: - type: array - items: - - type: string - format: date-time - - type: object - properties: - createdAt: - type: string - format: date-time - - allOf: - - type: string - format: date - - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - name: - type: object - properties: - id: - type: integer - format: int64 - createdAt: - type: string - format: date-time - 404: - schema: - $ref: "errors.yml#/error" - 200: - schema: - type: object - properties: - record: - type: array - items: - - type: string - format: date-time - - type: object - properties: - createdAt: - type: string - format: date-time - - allOf: - - type: string - format: date - - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - name: - type: object - properties: - id: - type: integer - format: int64 - createdAt: - type: string - format: date-time - "/other/place": - $ref: "external/pathItem.yml" - -definitions: - namedAgain: - type: object - properties: - id: - type: integer - format: int64 - - datedTag: - allOf: - - type: string - format: date - - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - - records: - type: array - items: - - type: object - properties: - createdAt: - type: string - format: date-time - - datedRecords: - type: array - items: - - type: string - format: date-time - - type: object - properties: - createdAt: - type: string - format: date-time - - datedTaggedRecords: - type: array - items: - - type: string - format: date-time - - type: object - properties: - createdAt: - type: string - format: date-time - additionalItems: - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - - otherRecords: - type: array - items: - type: object - properties: - createdAt: - type: string - format: date-time - - tags: - type: object - additionalProperties: - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - - namedThing: - type: object - properties: - name: - type: object - properties: - id: - type: integer - format: int64 - - nestedThing: - type: object - properties: - record: - type: array - items: - - type: string - format: date-time - - type: object - properties: - createdAt: - type: string - format: date-time - - allOf: - - type: string - format: date - - type: object - additionalProperties: - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - properties: - id: - type: integer - format: int64 - value: - type: string - name: - type: object - properties: - id: - type: integer - format: int64 - createdAt: - type: string - format: date-time \ No newline at end of file diff --git a/vendor/github.com/go-openapi/analysis/fixtures/no-paths.yml b/vendor/github.com/go-openapi/analysis/fixtures/no-paths.yml deleted file mode 100644 index 783f59c42..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/no-paths.yml +++ /dev/null @@ -1,38 +0,0 @@ ---- -swagger: '2.0' -info: - title: no paths API - version: 4.1.7 -schemes: - - http -basePath: /wooble -consumes: - - application/json -produces: - - application/json -paths: -definitions: - common: - type: object - required: - - id - properties: - id: - type: string - format: string - minLength: 1 -parameters: - common: - name: common - in: query - type: string - -responses: - 401: - description: bar unauthorized - schema: - $ref: "#/definitions/error" - 404: - description: bar resource not found - schema: - $ref: "#/definitions/error" diff --git a/vendor/github.com/go-openapi/analysis/fixtures/patterns.yml b/vendor/github.com/go-openapi/analysis/fixtures/patterns.yml deleted file mode 100644 index 3fe1ab516..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/patterns.yml +++ /dev/null @@ -1,124 +0,0 @@ ---- -swagger: "2.0" -info: - version: "0.1.0" - title: reference analysis - -parameters: - idParam: - name: id - in: path - type: string - pattern: 'a[A-Za-Z0-9]+' - -responses: - notFound: - headers: - ContentLength: - type: string - pattern: '[0-9]+' - schema: - $ref: "#/definitions/error" - -paths: - "/some/where/{id}": - parameters: - - $ref: "#/parameters/idParam" - - name: name - in: query - pattern: 'b[A-Za-z0-9]+' - - name: bodyId - in: body - schema: - type: object - get: - parameters: - - name: filter - in: query - type: string - pattern: "[abc][0-9]+" - - name: other - in: query - type: array - items: - type: string - pattern: 'c[A-Za-z0-9]+' - - name: body - in: body - schema: - type: object - - responses: - default: - schema: - type: object - 404: - $ref: "#/responses/notFound" - 200: - headers: - X-Request-Id: - type: string - pattern: 'd[A-Za-z0-9]+' - schema: - $ref: "#/definitions/tag" - "/other/place": - post: - parameters: - - name: body - in: body - schema: - type: object - properties: - value: - type: string - pattern: 'e[A-Za-z0-9]+' - responses: - default: - headers: - Via: - type: array - items: - type: string - pattern: '[A-Za-z]+' - 200: - schema: - type: object - properties: - data: - type: string - pattern: "[0-9]+[abd]" - -definitions: - named: - type: string - pattern: 'f[A-Za-z0-9]+' - tag: - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - pattern: 'g[A-Za-z0-9]+' - audit: - $ref: "#/definitions/record" - record: - type: object - properties: - createdAt: - type: string - format: date-time - error: - type: object - required: - - id - - message - properties: - id: - type: integer - format: int64 - readOnly: true - message: - type: string - readOnly: true diff --git a/vendor/github.com/go-openapi/analysis/fixtures/references.yml b/vendor/github.com/go-openapi/analysis/fixtures/references.yml deleted file mode 100644 index b57176635..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/references.yml +++ /dev/null @@ -1,89 +0,0 @@ ---- -swagger: "2.0" -info: - version: "0.1.0" - title: reference analysis - -parameters: - idParam: - name: id - in: path - type: integer - format: int32 - limitParam: - name: limit - in: query - type: integer - format: int32 - required: false - -responses: - notFound: - schema: - $ref: "#/definitions/error" - -paths: - "/some/where/{id}": - parameters: - - $ref: "#/parameters/idParam" - - - name: bodyId - in: body - schema: - type: object - get: - parameters: - - $ref: "#/parameters/limitParam" - - name: other - in: query - type: array - items: - $ref: "#/definitions/named" - - name: body - in: body - schema: - type: object - responses: - default: - schema: - type: object - 404: - $ref: "#/responses/notFound" - 200: - schema: - $ref: "#/definitions/tag" - "/other/place": - $ref: "#/x-shared-path/getItems" - -definitions: - named: - type: string - tag: - type: object - properties: - id: - type: integer - format: int64 - value: - type: string - audit: - $ref: "#/definitions/record" - record: - type: object - properties: - createdAt: - type: string - format: date-time - error: - type: object - required: - - id - - message - properties: - id: - type: integer - format: int64 - readOnly: true - message: - type: string - readOnly: true diff --git a/vendor/github.com/go-openapi/analysis/fixtures/widget-crud.yml b/vendor/github.com/go-openapi/analysis/fixtures/widget-crud.yml deleted file mode 100644 index d1acb9277..000000000 --- a/vendor/github.com/go-openapi/analysis/fixtures/widget-crud.yml +++ /dev/null @@ -1,181 +0,0 @@ ---- -swagger: '2.0' -info: - title: widget CRUD API - version: 4.2.0 -schemes: - - http -basePath: /api -consumes: - - application/json -produces: - - application/json -paths: - /common: - get: - operationId: commonGet - summary: here to test path collisons - responses: - '200': - description: OK - schema: - $ref: "#/definitions/widget" - - /widgets: - post: - operationId: create - summary: Create a new widget - parameters: - - name: info - in: body - schema: - $ref: "#/definitions/widget" - responses: - '201': - description: created - schema: - $ref: "#/definitions/widgetId" - default: - description: error - schema: - $ref: "#/definitions/error" - /widgets/{widgetid}: - get: - operationId: get - summary: Get a widget by id - parameters: - - $ref: "#/parameters/widgetid" - responses: - '200': - description: OK - schema: - $ref: "#/definitions/widget" - '401': - $ref: "#/responses/401" - '404': - $ref: "#/responses/404" - default: - description: error - schema: - $ref: "#/definitions/error" - delete: - operationId: delete - summary: delete a widget by id - parameters: - - name: widgetid - in: path - required: true - type: string - responses: - '200': - description: OK - '401': - description: unauthorized - schema: - $ref: "#/definitions/error" - '404': - description: resource not found - schema: - $ref: "#/definitions/error" - default: - description: error - schema: - $ref: "#/definitions/error" - post: - operationId: update - summary: update a widget by id - parameters: - - name: widgetid - in: path - required: true - type: string - - name: info - in: body - schema: - $ref: "#/definitions/widget" - responses: - '200': - description: OK - '401': - description: unauthorized - schema: - $ref: "#/definitions/error" - '404': - description: resource not found - schema: - $ref: "#/definitions/error" - default: - description: error - schema: - $ref: "#/definitions/error" - -definitions: - common: - type: object - required: - - id - properties: - id: - type: string - format: string - minLength: 1 - widget: - type: object - required: - - name - - description - properties: - id: - type: string - format: string - readOnly: true - name: - type: string - format: string - minLength: 1 - description: - type: string - format: string - minLength: 1 - widgetId: - type: object - required: - - id - properties: - id: - type: string - format: string - minLength: 1 - error: - type: object - required: - - message - properties: - code: - type: string - format: string - message: - type: string - fields: - type: string - -parameters: - common: - name: common - in: query - type: string - widgetid: - name: widgetid - in: path - required: true - type: string - -responses: - 401: - description: widget unauthorized - schema: - $ref: "#/definitions/error" - 404: - description: widget resource not found - schema: - $ref: "#/definitions/error" diff --git a/vendor/github.com/go-openapi/analysis/flatten.go b/vendor/github.com/go-openapi/analysis/flatten.go deleted file mode 100644 index 610994d51..000000000 --- a/vendor/github.com/go-openapi/analysis/flatten.go +++ /dev/null @@ -1,800 +0,0 @@ -package analysis - -import ( - "fmt" - "log" - "net/http" - "os" - "path" - "path/filepath" - "sort" - "strings" - - "strconv" - - "github.com/go-openapi/jsonpointer" - swspec "github.com/go-openapi/spec" - "github.com/go-openapi/swag" -) - -// FlattenOpts configuration for flattening a swagger specification. -type FlattenOpts struct { - // If Expand is true, we skip flattening the spec and expand it instead - Expand bool - Spec *Spec - BasePath string - - _ struct{} // require keys -} - -// ExpandOpts creates a spec.ExpandOptions to configure expanding a specification document. -func (f *FlattenOpts) ExpandOpts(skipSchemas bool) *swspec.ExpandOptions { - return &swspec.ExpandOptions{RelativeBase: f.BasePath, SkipSchemas: skipSchemas} -} - -// Swagger gets the swagger specification for this flatten operation -func (f *FlattenOpts) Swagger() *swspec.Swagger { - return f.Spec.spec -} - -// Flatten an analyzed spec. -// -// To flatten a spec means: -// -// Expand the parameters, responses, path items, parameter items and header items. -// Import external (http, file) references so they become internal to the document. -// Move every inline schema to be a definition with an auto-generated name in a depth-first fashion. -// Rewritten schemas get a vendor extension x-go-gen-location so we know in which package they need to be rendered. -func Flatten(opts FlattenOpts) error { - // Make sure opts.BasePath is an absolute path - if !filepath.IsAbs(opts.BasePath) { - cwd, _ := os.Getwd() - opts.BasePath = filepath.Join(cwd, opts.BasePath) - } - // recursively expand responses, parameters, path items and items - err := swspec.ExpandSpec(opts.Swagger(), &swspec.ExpandOptions{ - RelativeBase: opts.BasePath, - SkipSchemas: !opts.Expand, - }) - if err != nil { - return err - } - opts.Spec.reload() // re-analyze - - // at this point there are no other references left but schemas - if err := importExternalReferences(&opts); err != nil { - return err - } - opts.Spec.reload() // re-analyze - - // rewrite the inline schemas (schemas that aren't simple types or arrays of simple types) - if err := nameInlinedSchemas(&opts); err != nil { - return err - } - opts.Spec.reload() // re-analyze - - // TODO: simplifiy known schema patterns to flat objects with properties? - return nil -} - -func nameInlinedSchemas(opts *FlattenOpts) error { - namer := &inlineSchemaNamer{Spec: opts.Swagger(), Operations: opRefsByRef(gatherOperations(opts.Spec, nil))} - depthFirst := sortDepthFirst(opts.Spec.allSchemas) - for _, key := range depthFirst { - sch := opts.Spec.allSchemas[key] - if sch.Schema != nil && sch.Schema.Ref.String() == "" && !sch.TopLevel { // inline schema - asch, err := Schema(SchemaOpts{Schema: sch.Schema, Root: opts.Swagger(), BasePath: opts.BasePath}) - if err != nil { - return fmt.Errorf("schema analysis [%s]: %v", sch.Ref.String(), err) - } - - if !asch.IsSimpleSchema && !asch.IsArray { // complex schemas get moved - if err := namer.Name(key, sch.Schema, asch); err != nil { - return err - } - } - } - } - return nil -} - -var depthGroupOrder = []string{"sharedOpParam", "opParam", "codeResponse", "defaultResponse", "definition"} - -func sortDepthFirst(data map[string]SchemaRef) (sorted []string) { - // group by category (shared params, op param, statuscode response, default response, definitions) - // sort groups internally by number of parts in the key and lexical names - // flatten groups into a single list of keys - grouped := make(map[string]keys, len(data)) - for k := range data { - split := keyParts(k) - var pk string - if split.IsSharedOperationParam() { - pk = "sharedOpParam" - } - if split.IsOperationParam() { - pk = "opParam" - } - if split.IsStatusCodeResponse() { - pk = "codeResponse" - } - if split.IsDefaultResponse() { - pk = "defaultResponse" - } - if split.IsDefinition() { - pk = "definition" - } - grouped[pk] = append(grouped[pk], key{len(split), k}) - } - - for _, pk := range depthGroupOrder { - res := grouped[pk] - sort.Sort(res) - for _, v := range res { - sorted = append(sorted, v.Key) - } - } - - return -} - -type key struct { - Segments int - Key string -} -type keys []key - -func (k keys) Len() int { return len(k) } -func (k keys) Swap(i, j int) { k[i], k[j] = k[j], k[i] } -func (k keys) Less(i, j int) bool { - return k[i].Segments > k[j].Segments || (k[i].Segments == k[j].Segments && k[i].Key < k[j].Key) -} - -type inlineSchemaNamer struct { - Spec *swspec.Swagger - Operations map[string]opRef -} - -func opRefsByRef(oprefs map[string]opRef) map[string]opRef { - result := make(map[string]opRef, len(oprefs)) - for _, v := range oprefs { - result[v.Ref.String()] = v - } - return result -} - -func (isn *inlineSchemaNamer) Name(key string, schema *swspec.Schema, aschema *AnalyzedSchema) error { - if swspec.Debug { - log.Printf("naming inlined schema at %s", key) - } - - parts := keyParts(key) - for _, name := range namesFromKey(parts, aschema, isn.Operations) { - if name != "" { - // create unique name - newName := uniqifyName(isn.Spec.Definitions, swag.ToJSONName(name)) - - // clone schema - sch, err := cloneSchema(schema) - if err != nil { - return err - } - - // replace values on schema - if err := rewriteSchemaToRef(isn.Spec, key, swspec.MustCreateRef("#/definitions/"+newName)); err != nil { - return fmt.Errorf("name inlined schema: %v", err) - } - - sch.AddExtension("x-go-gen-location", genLocation(parts)) - // fmt.Printf("{\n %q,\n \"\",\n spec.MustCreateRef(%q),\n \"\",\n},\n", key, "#/definitions/"+newName) - // save cloned schema to definitions - saveSchema(isn.Spec, newName, sch) - } - } - return nil -} - -func genLocation(parts splitKey) string { - if parts.IsOperation() { - return "operations" - } - if parts.IsDefinition() { - return "models" - } - return "" -} - -func uniqifyName(definitions swspec.Definitions, name string) string { - if name == "" { - name = "oaiGen" - } - if len(definitions) == 0 { - return name - } - - unq := true - for k := range definitions { - if strings.ToLower(k) == strings.ToLower(name) { - unq = false - break - } - } - - if unq { - return name - } - - name += "OAIGen" - var idx int - unique := name - _, known := definitions[unique] - for known { - idx++ - unique = fmt.Sprintf("%s%d", name, idx) - _, known = definitions[unique] - } - return unique -} - -func namesFromKey(parts splitKey, aschema *AnalyzedSchema, operations map[string]opRef) []string { - var baseNames [][]string - var startIndex int - if parts.IsOperation() { - // params - if parts.IsOperationParam() || parts.IsSharedOperationParam() { - piref := parts.PathItemRef() - if piref.String() != "" && parts.IsOperationParam() { - if op, ok := operations[piref.String()]; ok { - startIndex = 5 - baseNames = append(baseNames, []string{op.ID, "params", "body"}) - } - } else if parts.IsSharedOperationParam() { - pref := parts.PathRef() - for k, v := range operations { - if strings.HasPrefix(k, pref.String()) { - startIndex = 4 - baseNames = append(baseNames, []string{v.ID, "params", "body"}) - } - } - } - } - // responses - if parts.IsOperationResponse() { - piref := parts.PathItemRef() - if piref.String() != "" { - if op, ok := operations[piref.String()]; ok { - startIndex = 6 - baseNames = append(baseNames, []string{op.ID, parts.ResponseName(), "body"}) - } - } - } - } - - // definitions - if parts.IsDefinition() { - nm := parts.DefinitionName() - if nm != "" { - startIndex = 2 - baseNames = append(baseNames, []string{parts.DefinitionName()}) - } - } - - var result []string - for _, segments := range baseNames { - nm := parts.BuildName(segments, startIndex, aschema) - if nm != "" { - result = append(result, nm) - } - } - sort.Strings(result) - return result -} - -const ( - pths = "paths" - responses = "responses" - parameters = "parameters" - definitions = "definitions" -) - -var ignoredKeys map[string]struct{} - -func init() { - ignoredKeys = map[string]struct{}{ - "schema": {}, - "properties": {}, - "not": {}, - "anyOf": {}, - "oneOf": {}, - } -} - -type splitKey []string - -func (s splitKey) IsDefinition() bool { - return len(s) > 1 && s[0] == definitions -} - -func (s splitKey) DefinitionName() string { - if !s.IsDefinition() { - return "" - } - return s[1] -} - -func (s splitKey) isKeyName(i int) bool { - if i <= 0 { - return false - } - count := 0 - for idx := i - 1; idx > 0; idx-- { - if s[idx] != "properties" { - break - } - count++ - } - - if count%2 != 0 { - return true - } - return false -} - -func (s splitKey) BuildName(segments []string, startIndex int, aschema *AnalyzedSchema) string { - for i, part := range s[startIndex:] { - if _, ignored := ignoredKeys[part]; !ignored || s.isKeyName(startIndex+i) { - if part == "items" || part == "additionalItems" { - if aschema.IsTuple || aschema.IsTupleWithExtra { - segments = append(segments, "tuple") - } else { - segments = append(segments, "items") - } - if part == "additionalItems" { - segments = append(segments, part) - } - continue - } - segments = append(segments, part) - } - } - return strings.Join(segments, " ") -} - -func (s splitKey) IsOperation() bool { - return len(s) > 1 && s[0] == pths -} - -func (s splitKey) IsSharedOperationParam() bool { - return len(s) > 2 && s[0] == pths && s[2] == parameters -} - -func (s splitKey) IsOperationParam() bool { - return len(s) > 3 && s[0] == pths && s[3] == parameters -} - -func (s splitKey) IsOperationResponse() bool { - return len(s) > 3 && s[0] == pths && s[3] == responses -} - -func (s splitKey) IsDefaultResponse() bool { - return len(s) > 4 && s[0] == pths && s[3] == responses && s[4] == "default" -} - -func (s splitKey) IsStatusCodeResponse() bool { - isInt := func() bool { - _, err := strconv.Atoi(s[4]) - return err == nil - } - return len(s) > 4 && s[0] == pths && s[3] == responses && isInt() -} - -func (s splitKey) ResponseName() string { - if s.IsStatusCodeResponse() { - code, _ := strconv.Atoi(s[4]) - return http.StatusText(code) - } - if s.IsDefaultResponse() { - return "Default" - } - return "" -} - -var validMethods map[string]struct{} - -func init() { - validMethods = map[string]struct{}{ - "GET": {}, - "HEAD": {}, - "OPTIONS": {}, - "PATCH": {}, - "POST": {}, - "PUT": {}, - "DELETE": {}, - } -} - -func (s splitKey) PathItemRef() swspec.Ref { - if len(s) < 3 { - return swspec.Ref{} - } - pth, method := s[1], s[2] - if _, validMethod := validMethods[strings.ToUpper(method)]; !validMethod && !strings.HasPrefix(method, "x-") { - return swspec.Ref{} - } - return swspec.MustCreateRef("#" + path.Join("/", pths, jsonpointer.Escape(pth), strings.ToUpper(method))) -} - -func (s splitKey) PathRef() swspec.Ref { - if !s.IsOperation() { - return swspec.Ref{} - } - return swspec.MustCreateRef("#" + path.Join("/", pths, jsonpointer.Escape(s[1]))) -} - -func keyParts(key string) splitKey { - var res []string - for _, part := range strings.Split(key[1:], "/") { - if part != "" { - res = append(res, jsonpointer.Unescape(part)) - } - } - return res -} - -func rewriteSchemaToRef(spec *swspec.Swagger, key string, ref swspec.Ref) error { - if swspec.Debug { - log.Printf("rewriting schema to ref for %s with %s", key, ref.String()) - } - pth := key[1:] - ptr, err := jsonpointer.New(pth) - if err != nil { - return err - } - - value, _, err := ptr.Get(spec) - if err != nil { - return err - } - - switch refable := value.(type) { - case *swspec.Schema: - return rewriteParentRef(spec, key, ref) - case *swspec.SchemaOrBool: - if refable.Schema != nil { - refable.Schema = &swspec.Schema{SchemaProps: swspec.SchemaProps{Ref: ref}} - } - case *swspec.SchemaOrArray: - if refable.Schema != nil { - refable.Schema = &swspec.Schema{SchemaProps: swspec.SchemaProps{Ref: ref}} - } - case swspec.Schema: - return rewriteParentRef(spec, key, ref) - default: - return fmt.Errorf("no schema with ref found at %s for %T", key, value) - } - - return nil -} - -func rewriteParentRef(spec *swspec.Swagger, key string, ref swspec.Ref) error { - pth := key[1:] - parent, entry := path.Dir(pth), path.Base(pth) - if swspec.Debug { - log.Println("getting schema holder at:", parent) - } - - pptr, err := jsonpointer.New(parent) - if err != nil { - return err - } - pvalue, _, err := pptr.Get(spec) - if err != nil { - return fmt.Errorf("can't get parent for %s: %v", parent, err) - } - if swspec.Debug { - log.Printf("rewriting holder for %T", pvalue) - } - - switch container := pvalue.(type) { - case swspec.Response: - if err := rewriteParentRef(spec, "#"+parent, ref); err != nil { - return err - } - - case *swspec.Response: - container.Schema = &swspec.Schema{SchemaProps: swspec.SchemaProps{Ref: ref}} - - case *swspec.Responses: - statusCode, err := strconv.Atoi(entry) - if err != nil { - return fmt.Errorf("%s not a number: %v", pth, err) - } - resp := container.StatusCodeResponses[statusCode] - resp.Schema = &swspec.Schema{SchemaProps: swspec.SchemaProps{Ref: ref}} - container.StatusCodeResponses[statusCode] = resp - - case map[string]swspec.Response: - resp := container[entry] - resp.Schema = &swspec.Schema{SchemaProps: swspec.SchemaProps{Ref: ref}} - container[entry] = resp - - case swspec.Parameter: - if err := rewriteParentRef(spec, "#"+parent, ref); err != nil { - return err - } - - case map[string]swspec.Parameter: - param := container[entry] - param.Schema = &swspec.Schema{SchemaProps: swspec.SchemaProps{Ref: ref}} - container[entry] = param - - case []swspec.Parameter: - idx, err := strconv.Atoi(entry) - if err != nil { - return fmt.Errorf("%s not a number: %v", pth, err) - } - param := container[idx] - param.Schema = &swspec.Schema{SchemaProps: swspec.SchemaProps{Ref: ref}} - container[idx] = param - - case swspec.Definitions: - container[entry] = swspec.Schema{SchemaProps: swspec.SchemaProps{Ref: ref}} - - case map[string]swspec.Schema: - container[entry] = swspec.Schema{SchemaProps: swspec.SchemaProps{Ref: ref}} - - case []swspec.Schema: - idx, err := strconv.Atoi(entry) - if err != nil { - return fmt.Errorf("%s not a number: %v", pth, err) - } - container[idx] = swspec.Schema{SchemaProps: swspec.SchemaProps{Ref: ref}} - - case *swspec.SchemaOrArray: - idx, err := strconv.Atoi(entry) - if err != nil { - return fmt.Errorf("%s not a number: %v", pth, err) - } - container.Schemas[idx] = swspec.Schema{SchemaProps: swspec.SchemaProps{Ref: ref}} - default: - return fmt.Errorf("unhandled parent schema rewrite %s (%T)", key, pvalue) - } - return nil -} - -func cloneSchema(schema *swspec.Schema) (*swspec.Schema, error) { - var sch swspec.Schema - if err := swag.FromDynamicJSON(schema, &sch); err != nil { - return nil, fmt.Errorf("name inlined schema: %v", err) - } - return &sch, nil -} - -func importExternalReferences(opts *FlattenOpts) error { - groupedRefs := reverseIndexForSchemaRefs(opts) - - for refStr, entry := range groupedRefs { - if !entry.Ref.HasFragmentOnly { - if swspec.Debug { - log.Printf("importing external schema for [%s] from %s", strings.Join(entry.Keys, ", "), refStr) - } - // resolve to actual schema - sch := new(swspec.Schema) - sch.Ref = entry.Ref - expandOpts := swspec.ExpandOptions{ - RelativeBase: opts.BasePath, - SkipSchemas: false, - } - err := swspec.ExpandSchemaWithBasePath(sch, nil, &expandOpts) - if err != nil { - return err - } - if sch == nil { - return fmt.Errorf("no schema found at %s for [%s]", refStr, strings.Join(entry.Keys, ", ")) - } - if swspec.Debug { - log.Printf("importing external schema for [%s] from %s", strings.Join(entry.Keys, ", "), refStr) - } - - // generate a unique name - newName := uniqifyName(opts.Swagger().Definitions, nameFromRef(entry.Ref)) - if swspec.Debug { - log.Printf("new name for [%s]: %s", strings.Join(entry.Keys, ", "), newName) - } - - // rewrite the external refs to local ones - for _, key := range entry.Keys { - if err := updateRef(opts.Swagger(), key, swspec.MustCreateRef("#"+path.Join("/definitions", newName))); err != nil { - return err - } - } - - // add the resolved schema to the definitions - saveSchema(opts.Swagger(), newName, sch) - } - } - return nil -} - -type refRevIdx struct { - Ref swspec.Ref - Keys []string -} - -func reverseIndexForSchemaRefs(opts *FlattenOpts) map[string]refRevIdx { - collected := make(map[string]refRevIdx) - for key, schRef := range opts.Spec.references.schemas { - if entry, ok := collected[schRef.String()]; ok { - entry.Keys = append(entry.Keys, key) - collected[schRef.String()] = entry - } else { - collected[schRef.String()] = refRevIdx{ - Ref: schRef, - Keys: []string{key}, - } - } - } - return collected -} - -func nameFromRef(ref swspec.Ref) string { - u := ref.GetURL() - if u.Fragment != "" { - return swag.ToJSONName(path.Base(u.Fragment)) - } - if u.Path != "" { - bn := path.Base(u.Path) - if bn != "" && bn != "/" { - ext := path.Ext(bn) - if ext != "" { - return swag.ToJSONName(bn[:len(bn)-len(ext)]) - } - return swag.ToJSONName(bn) - } - } - return swag.ToJSONName(strings.Replace(u.Host, ".", " ", -1)) -} - -func saveSchema(spec *swspec.Swagger, name string, schema *swspec.Schema) { - if schema == nil { - return - } - if spec.Definitions == nil { - spec.Definitions = make(map[string]swspec.Schema, 150) - } - spec.Definitions[name] = *schema -} - -func updateRef(spec *swspec.Swagger, key string, ref swspec.Ref) error { - if swspec.Debug { - log.Printf("updating ref for %s with %s", key, ref.String()) - } - pth := key[1:] - ptr, err := jsonpointer.New(pth) - if err != nil { - return err - } - - value, _, err := ptr.Get(spec) - if err != nil { - return err - } - - switch refable := value.(type) { - case *swspec.Schema: - refable.Ref = ref - case *swspec.SchemaOrBool: - if refable.Schema != nil { - refable.Schema.Ref = ref - } - case *swspec.SchemaOrArray: - if refable.Schema != nil { - refable.Schema.Ref = ref - } - case swspec.Schema: - parent, entry := path.Dir(pth), path.Base(pth) - if swspec.Debug { - log.Println("getting schema holder at:", parent) - } - - pptr, err := jsonpointer.New(parent) - if err != nil { - return err - } - pvalue, _, err := pptr.Get(spec) - if err != nil { - return fmt.Errorf("can't get parent for %s: %v", parent, err) - } - - switch container := pvalue.(type) { - case swspec.Definitions: - container[entry] = swspec.Schema{SchemaProps: swspec.SchemaProps{Ref: ref}} - - case map[string]swspec.Schema: - container[entry] = swspec.Schema{SchemaProps: swspec.SchemaProps{Ref: ref}} - - case []swspec.Schema: - idx, err := strconv.Atoi(entry) - if err != nil { - return fmt.Errorf("%s not a number: %v", pth, err) - } - container[idx] = swspec.Schema{SchemaProps: swspec.SchemaProps{Ref: ref}} - - case *swspec.SchemaOrArray: - idx, err := strconv.Atoi(entry) - if err != nil { - return fmt.Errorf("%s not a number: %v", pth, err) - } - container.Schemas[idx] = swspec.Schema{SchemaProps: swspec.SchemaProps{Ref: ref}} - - } - - default: - return fmt.Errorf("no schema with ref found at %s for %T", key, value) - } - - return nil -} - -func containsString(names []string, name string) bool { - for _, nm := range names { - if nm == name { - return true - } - } - return false -} - -type opRef struct { - Method string - Path string - Key string - ID string - Op *swspec.Operation - Ref swspec.Ref -} - -type opRefs []opRef - -func (o opRefs) Len() int { return len(o) } -func (o opRefs) Swap(i, j int) { o[i], o[j] = o[j], o[i] } -func (o opRefs) Less(i, j int) bool { return o[i].Key < o[j].Key } - -func gatherOperations(specDoc *Spec, operationIDs []string) map[string]opRef { - var oprefs opRefs - - for method, pathItem := range specDoc.Operations() { - for pth, operation := range pathItem { - vv := *operation - oprefs = append(oprefs, opRef{ - Key: swag.ToGoName(strings.ToLower(method) + " " + pth), - Method: method, - Path: pth, - ID: vv.ID, - Op: &vv, - Ref: swspec.MustCreateRef("#" + path.Join("/paths", jsonpointer.Escape(pth), method)), - }) - } - } - - sort.Sort(oprefs) - - operations := make(map[string]opRef) - for _, opr := range oprefs { - nm := opr.ID - if nm == "" { - nm = opr.Key - } - - oo, found := operations[nm] - if found && oo.Method != opr.Method && oo.Path != opr.Path { - nm = opr.Key - } - if len(operationIDs) == 0 || containsString(operationIDs, opr.ID) || containsString(operationIDs, nm) { - opr.ID = nm - opr.Op.ID = nm - operations[nm] = opr - } - } - - return operations -} diff --git a/vendor/github.com/go-openapi/analysis/flatten_test.go b/vendor/github.com/go-openapi/analysis/flatten_test.go deleted file mode 100644 index f5ec51c84..000000000 --- a/vendor/github.com/go-openapi/analysis/flatten_test.go +++ /dev/null @@ -1,822 +0,0 @@ -package analysis - -import ( - "os" - "path/filepath" - "strings" - "testing" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/spec" - "github.com/stretchr/testify/assert" -) - -func TestSaveDefinition(t *testing.T) { - sp := &spec.Swagger{} - saveSchema(sp, "theName", spec.StringProperty()) - assert.Contains(t, sp.Definitions, "theName") -} - -func TestNameFromRef(t *testing.T) { - values := []struct{ Source, Expected string }{ - {"#/definitions/errorModel", "errorModel"}, - {"http://somewhere.com/definitions/errorModel", "errorModel"}, - {"http://somewhere.com/definitions/errorModel.json", "errorModel"}, - {"/definitions/errorModel", "errorModel"}, - {"/definitions/errorModel.json", "errorModel"}, - {"http://somewhere.com", "somewhereCom"}, - {"#", ""}, - } - - for _, v := range values { - assert.Equal(t, v.Expected, nameFromRef(spec.MustCreateRef(v.Source))) - } -} - -func TestDefinitionName(t *testing.T) { - values := []struct { - Source, Expected string - Definitions spec.Definitions - }{ - {"#/definitions/errorModel", "errorModel", map[string]spec.Schema(nil)}, - {"http://somewhere.com/definitions/errorModel", "errorModel", map[string]spec.Schema(nil)}, - {"#/definitions/errorModel", "errorModel", map[string]spec.Schema{"apples": *spec.StringProperty()}}, - {"#/definitions/errorModel", "errorModelOAIGen", map[string]spec.Schema{"errorModel": *spec.StringProperty()}}, - {"#/definitions/errorModel", "errorModelOAIGen1", map[string]spec.Schema{"errorModel": *spec.StringProperty(), "errorModelOAIGen": *spec.StringProperty()}}, - {"#", "oaiGen", nil}, - } - - for _, v := range values { - assert.Equal(t, v.Expected, uniqifyName(v.Definitions, nameFromRef(spec.MustCreateRef(v.Source)))) - } -} - -func TestUpdateRef(t *testing.T) { - bp := filepath.Join("fixtures", "external_definitions.yml") - sp, err := loadSpec(bp) - if assert.NoError(t, err) { - - values := []struct { - Key string - Ref spec.Ref - }{ - {"#/parameters/someParam/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/paths/~1some~1where~1{id}/parameters/1/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/paths/~1some~1where~1{id}/get/parameters/2/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/responses/someResponse/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/paths/~1some~1where~1{id}/get/responses/default/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/paths/~1some~1where~1{id}/get/responses/200/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/definitions/namedAgain", spec.MustCreateRef("#/definitions/named")}, - {"#/definitions/datedTag/allOf/1", spec.MustCreateRef("#/definitions/tag")}, - {"#/definitions/datedRecords/items/1", spec.MustCreateRef("#/definitions/record")}, - {"#/definitions/datedTaggedRecords/items/1", spec.MustCreateRef("#/definitions/record")}, - {"#/definitions/datedTaggedRecords/additionalItems", spec.MustCreateRef("#/definitions/tag")}, - {"#/definitions/otherRecords/items", spec.MustCreateRef("#/definitions/record")}, - {"#/definitions/tags/additionalProperties", spec.MustCreateRef("#/definitions/tag")}, - {"#/definitions/namedThing/properties/name", spec.MustCreateRef("#/definitions/named")}, - } - - for _, v := range values { - err := updateRef(sp, v.Key, v.Ref) - if assert.NoError(t, err) { - ptr, err := jsonpointer.New(v.Key[1:]) - if assert.NoError(t, err) { - vv, _, err := ptr.Get(sp) - - if assert.NoError(t, err) { - switch tv := vv.(type) { - case *spec.Schema: - assert.Equal(t, v.Ref.String(), tv.Ref.String()) - case spec.Schema: - assert.Equal(t, v.Ref.String(), tv.Ref.String()) - case *spec.SchemaOrBool: - assert.Equal(t, v.Ref.String(), tv.Schema.Ref.String()) - case *spec.SchemaOrArray: - assert.Equal(t, v.Ref.String(), tv.Schema.Ref.String()) - default: - assert.Fail(t, "unknown type", "got %T", vv) - } - } - } - } - } - } -} - -func TestImportExternalReferences(t *testing.T) { - bp := filepath.Join(".", "fixtures", "external_definitions.yml") - sp, err := loadSpec(bp) - if assert.NoError(t, err) { - - values := []struct { - Key string - Ref spec.Ref - }{ - {"#/parameters/someParam/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/paths/~1some~1where~1{id}/parameters/1/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/paths/~1some~1where~1{id}/get/parameters/2/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/responses/someResponse/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/paths/~1some~1where~1{id}/get/responses/default/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/paths/~1some~1where~1{id}/get/responses/200/schema", spec.MustCreateRef("#/definitions/tag")}, - {"#/definitions/namedAgain", spec.MustCreateRef("#/definitions/named")}, - {"#/definitions/datedTag/allOf/1", spec.MustCreateRef("#/definitions/tag")}, - {"#/definitions/datedRecords/items/1", spec.MustCreateRef("#/definitions/record")}, - {"#/definitions/datedTaggedRecords/items/1", spec.MustCreateRef("#/definitions/record")}, - {"#/definitions/datedTaggedRecords/additionalItems", spec.MustCreateRef("#/definitions/tag")}, - {"#/definitions/otherRecords/items", spec.MustCreateRef("#/definitions/record")}, - {"#/definitions/tags/additionalProperties", spec.MustCreateRef("#/definitions/tag")}, - {"#/definitions/namedThing/properties/name", spec.MustCreateRef("#/definitions/named")}, - } - for _, v := range values { - // technically not necessary to run for each value, but if things go right - // this is idempotent, so having it repeat shouldn't matter - // this validates that behavior - err := importExternalReferences(&FlattenOpts{ - Spec: New(sp), - BasePath: bp, - }) - - if assert.NoError(t, err) { - - ptr, err := jsonpointer.New(v.Key[1:]) - if assert.NoError(t, err) { - vv, _, err := ptr.Get(sp) - - if assert.NoError(t, err) { - switch tv := vv.(type) { - case *spec.Schema: - assert.Equal(t, v.Ref.String(), tv.Ref.String(), "for %s", v.Key) - case spec.Schema: - assert.Equal(t, v.Ref.String(), tv.Ref.String(), "for %s", v.Key) - case *spec.SchemaOrBool: - assert.Equal(t, v.Ref.String(), tv.Schema.Ref.String(), "for %s", v.Key) - case *spec.SchemaOrArray: - assert.Equal(t, v.Ref.String(), tv.Schema.Ref.String(), "for %s", v.Key) - default: - assert.Fail(t, "unknown type", "got %T", vv) - } - } - } - } - } - assert.Len(t, sp.Definitions, 11) - assert.Contains(t, sp.Definitions, "tag") - assert.Contains(t, sp.Definitions, "named") - assert.Contains(t, sp.Definitions, "record") - } -} - -func TestRewriteSchemaRef(t *testing.T) { - bp := filepath.Join("fixtures", "inline_schemas.yml") - sp, err := loadSpec(bp) - if assert.NoError(t, err) { - - values := []struct { - Key string - Ref spec.Ref - }{ - {"#/parameters/someParam/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/paths/~1some~1where~1{id}/parameters/1/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/paths/~1some~1where~1{id}/get/parameters/2/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/responses/someResponse/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/paths/~1some~1where~1{id}/get/responses/default/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/paths/~1some~1where~1{id}/get/responses/200/schema", spec.MustCreateRef("#/definitions/record")}, - {"#/definitions/namedAgain", spec.MustCreateRef("#/definitions/named")}, - {"#/definitions/datedTag/allOf/1", spec.MustCreateRef("#/definitions/tag")}, - {"#/definitions/datedRecords/items/1", spec.MustCreateRef("#/definitions/record")}, - {"#/definitions/datedTaggedRecords/items/1", spec.MustCreateRef("#/definitions/record")}, - {"#/definitions/datedTaggedRecords/additionalItems", spec.MustCreateRef("#/definitions/tag")}, - {"#/definitions/otherRecords/items", spec.MustCreateRef("#/definitions/record")}, - {"#/definitions/tags/additionalProperties", spec.MustCreateRef("#/definitions/tag")}, - {"#/definitions/namedThing/properties/name", spec.MustCreateRef("#/definitions/named")}, - } - - for i, v := range values { - err := rewriteSchemaToRef(sp, v.Key, v.Ref) - if assert.NoError(t, err) { - ptr, err := jsonpointer.New(v.Key[1:]) - if assert.NoError(t, err) { - vv, _, err := ptr.Get(sp) - - if assert.NoError(t, err) { - switch tv := vv.(type) { - case *spec.Schema: - assert.Equal(t, v.Ref.String(), tv.Ref.String(), "at %d for %s", i, v.Key) - case spec.Schema: - assert.Equal(t, v.Ref.String(), tv.Ref.String(), "at %d for %s", i, v.Key) - case *spec.SchemaOrBool: - assert.Equal(t, v.Ref.String(), tv.Schema.Ref.String(), "at %d for %s", i, v.Key) - case *spec.SchemaOrArray: - assert.Equal(t, v.Ref.String(), tv.Schema.Ref.String(), "at %d for %s", i, v.Key) - default: - assert.Fail(t, "unknown type", "got %T", vv) - } - } - } - } - } - } -} - -func TestSplitKey(t *testing.T) { - - type KeyFlag uint64 - - const ( - isOperation KeyFlag = 1 << iota - isDefinition - isSharedOperationParam - isOperationParam - isOperationResponse - isDefaultResponse - isStatusCodeResponse - ) - - values := []struct { - Key string - Flags KeyFlag - PathItemRef spec.Ref - PathRef spec.Ref - Name string - }{ - { - "#/paths/~1some~1where~1{id}/parameters/1/schema", - isOperation | isSharedOperationParam, - spec.Ref{}, - spec.MustCreateRef("#/paths/~1some~1where~1{id}"), - "", - }, - { - "#/paths/~1some~1where~1{id}/get/parameters/2/schema", - isOperation | isOperationParam, - spec.MustCreateRef("#/paths/~1some~1where~1{id}/GET"), - spec.MustCreateRef("#/paths/~1some~1where~1{id}"), - "", - }, - { - "#/paths/~1some~1where~1{id}/get/responses/default/schema", - isOperation | isOperationResponse | isDefaultResponse, - spec.MustCreateRef("#/paths/~1some~1where~1{id}/GET"), - spec.MustCreateRef("#/paths/~1some~1where~1{id}"), - "Default", - }, - { - "#/paths/~1some~1where~1{id}/get/responses/200/schema", - isOperation | isOperationResponse | isStatusCodeResponse, - spec.MustCreateRef("#/paths/~1some~1where~1{id}/GET"), - spec.MustCreateRef("#/paths/~1some~1where~1{id}"), - "OK", - }, - { - "#/definitions/namedAgain", - isDefinition, - spec.Ref{}, - spec.Ref{}, - "namedAgain", - }, - { - "#/definitions/datedRecords/items/1", - isDefinition, - spec.Ref{}, - spec.Ref{}, - "datedRecords", - }, - { - "#/definitions/datedRecords/items/1", - isDefinition, - spec.Ref{}, - spec.Ref{}, - "datedRecords", - }, - { - "#/definitions/datedTaggedRecords/items/1", - isDefinition, - spec.Ref{}, - spec.Ref{}, - "datedTaggedRecords", - }, - { - "#/definitions/datedTaggedRecords/additionalItems", - isDefinition, - spec.Ref{}, - spec.Ref{}, - "datedTaggedRecords", - }, - { - "#/definitions/otherRecords/items", - isDefinition, - spec.Ref{}, - spec.Ref{}, - "otherRecords", - }, - { - "#/definitions/tags/additionalProperties", - isDefinition, - spec.Ref{}, - spec.Ref{}, - "tags", - }, - { - "#/definitions/namedThing/properties/name", - isDefinition, - spec.Ref{}, - spec.Ref{}, - "namedThing", - }, - } - - for i, v := range values { - parts := keyParts(v.Key) - pref := parts.PathRef() - piref := parts.PathItemRef() - assert.Equal(t, v.PathRef.String(), pref.String(), "pathRef: %s at %d", v.Key, i) - assert.Equal(t, v.PathItemRef.String(), piref.String(), "pathItemRef: %s at %d", v.Key, i) - - if v.Flags&isOperation != 0 { - assert.True(t, parts.IsOperation(), "isOperation: %s at %d", v.Key, i) - } else { - assert.False(t, parts.IsOperation(), "isOperation: %s at %d", v.Key, i) - } - if v.Flags&isDefinition != 0 { - assert.True(t, parts.IsDefinition(), "isDefinition: %s at %d", v.Key, i) - assert.Equal(t, v.Name, parts.DefinitionName(), "definition name: %s at %d", v.Key, i) - } else { - assert.False(t, parts.IsDefinition(), "isDefinition: %s at %d", v.Key, i) - if v.Name != "" { - assert.Equal(t, v.Name, parts.ResponseName(), "response name: %s at %d", v.Key, i) - } - } - if v.Flags&isOperationParam != 0 { - assert.True(t, parts.IsOperationParam(), "isOperationParam: %s at %d", v.Key, i) - } else { - assert.False(t, parts.IsOperationParam(), "isOperationParam: %s at %d", v.Key, i) - } - if v.Flags&isSharedOperationParam != 0 { - assert.True(t, parts.IsSharedOperationParam(), "isSharedOperationParam: %s at %d", v.Key, i) - } else { - assert.False(t, parts.IsSharedOperationParam(), "isSharedOperationParam: %s at %d", v.Key, i) - } - if v.Flags&isOperationResponse != 0 { - assert.True(t, parts.IsOperationResponse(), "isOperationResponse: %s at %d", v.Key, i) - } else { - assert.False(t, parts.IsOperationResponse(), "isOperationResponse: %s at %d", v.Key, i) - } - if v.Flags&isDefaultResponse != 0 { - assert.True(t, parts.IsDefaultResponse(), "isDefaultResponse: %s at %d", v.Key, i) - } else { - assert.False(t, parts.IsDefaultResponse(), "isDefaultResponse: %s at %d", v.Key, i) - } - if v.Flags&isStatusCodeResponse != 0 { - assert.True(t, parts.IsStatusCodeResponse(), "isStatusCodeResponse: %s at %d", v.Key, i) - } else { - assert.False(t, parts.IsStatusCodeResponse(), "isStatusCodeResponse: %s at %d", v.Key, i) - } - } -} - -func definitionPtr(key string) string { - if !strings.HasPrefix(key, "#/definitions") { - return key - } - return strings.Join(strings.Split(key, "/")[:3], "/") -} - -func TestNamesFromKey(t *testing.T) { - bp := filepath.Join("fixtures", "inline_schemas.yml") - sp, err := loadSpec(bp) - if assert.NoError(t, err) { - - values := []struct { - Key string - Names []string - }{ - {"#/paths/~1some~1where~1{id}/parameters/1/schema", []string{"GetSomeWhereID params body", "PostSomeWhereID params body"}}, - {"#/paths/~1some~1where~1{id}/get/parameters/2/schema", []string{"GetSomeWhereID params body"}}, - {"#/paths/~1some~1where~1{id}/get/responses/default/schema", []string{"GetSomeWhereID Default body"}}, - {"#/paths/~1some~1where~1{id}/get/responses/200/schema", []string{"GetSomeWhereID OK body"}}, - {"#/definitions/namedAgain", []string{"namedAgain"}}, - {"#/definitions/datedTag/allOf/1", []string{"datedTag allOf 1"}}, - {"#/definitions/datedRecords/items/1", []string{"datedRecords tuple 1"}}, - {"#/definitions/datedTaggedRecords/items/1", []string{"datedTaggedRecords tuple 1"}}, - {"#/definitions/datedTaggedRecords/additionalItems", []string{"datedTaggedRecords tuple additionalItems"}}, - {"#/definitions/otherRecords/items", []string{"otherRecords items"}}, - {"#/definitions/tags/additionalProperties", []string{"tags additionalProperties"}}, - {"#/definitions/namedThing/properties/name", []string{"namedThing name"}}, - } - - for i, v := range values { - ptr, err := jsonpointer.New(definitionPtr(v.Key)[1:]) - if assert.NoError(t, err) { - vv, _, err := ptr.Get(sp) - if assert.NoError(t, err) { - switch tv := vv.(type) { - case *spec.Schema: - aschema, err := Schema(SchemaOpts{Schema: tv, Root: sp, BasePath: bp}) - if assert.NoError(t, err) { - names := namesFromKey(keyParts(v.Key), aschema, opRefsByRef(gatherOperations(New(sp), nil))) - assert.Equal(t, v.Names, names, "for %s at %d", v.Key, i) - } - case spec.Schema: - aschema, err := Schema(SchemaOpts{Schema: &tv, Root: sp, BasePath: bp}) - if assert.NoError(t, err) { - names := namesFromKey(keyParts(v.Key), aschema, opRefsByRef(gatherOperations(New(sp), nil))) - assert.Equal(t, v.Names, names, "for %s at %d", v.Key, i) - } - default: - assert.Fail(t, "unknown type", "got %T", vv) - } - } - } - } - } -} - -func TestDepthFirstSort(t *testing.T) { - bp := filepath.Join("fixtures", "inline_schemas.yml") - sp, err := loadSpec(bp) - values := []string{ - "#/paths/~1some~1where~1{id}/parameters/1/schema/properties/createdAt", - "#/paths/~1some~1where~1{id}/parameters/1/schema", - "#/paths/~1some~1where~1{id}/get/parameters/2/schema/properties/createdAt", - "#/paths/~1some~1where~1{id}/get/parameters/2/schema", - "#/paths/~1some~1where~1{id}/get/responses/200/schema/properties/id", - "#/paths/~1some~1where~1{id}/get/responses/200/schema/properties/value", - "#/paths/~1some~1where~1{id}/get/responses/200/schema", - "#/paths/~1some~1where~1{id}/get/responses/404/schema", - "#/paths/~1some~1where~1{id}/get/responses/default/schema/properties/createdAt", - "#/paths/~1some~1where~1{id}/get/responses/default/schema", - "#/definitions/datedRecords/items/1/properties/createdAt", - "#/definitions/datedTaggedRecords/items/1/properties/createdAt", - "#/definitions/namedThing/properties/name/properties/id", - "#/definitions/records/items/0/properties/createdAt", - "#/definitions/datedTaggedRecords/additionalItems/properties/id", - "#/definitions/datedTaggedRecords/additionalItems/properties/value", - "#/definitions/otherRecords/items/properties/createdAt", - "#/definitions/tags/additionalProperties/properties/id", - "#/definitions/tags/additionalProperties/properties/value", - "#/definitions/datedRecords/items/0", - "#/definitions/datedRecords/items/1", - "#/definitions/datedTag/allOf/0", - "#/definitions/datedTag/allOf/1", - "#/definitions/datedTag/properties/id", - "#/definitions/datedTag/properties/value", - "#/definitions/datedTaggedRecords/items/0", - "#/definitions/datedTaggedRecords/items/1", - "#/definitions/namedAgain/properties/id", - "#/definitions/namedThing/properties/name", - "#/definitions/pneumonoultramicroscopicsilicovolcanoconiosisAntidisestablishmentarianism/properties/floccinaucinihilipilificationCreatedAt", - "#/definitions/records/items/0", - "#/definitions/datedTaggedRecords/additionalItems", - "#/definitions/otherRecords/items", - "#/definitions/tags/additionalProperties", - "#/definitions/datedRecords", - "#/definitions/datedTag", - "#/definitions/datedTaggedRecords", - "#/definitions/namedAgain", - "#/definitions/namedThing", - "#/definitions/otherRecords", - "#/definitions/pneumonoultramicroscopicsilicovolcanoconiosisAntidisestablishmentarianism", - "#/definitions/records", - "#/definitions/tags", - } - if assert.NoError(t, err) { - a := New(sp) - result := sortDepthFirst(a.allSchemas) - assert.Equal(t, values, result) - } -} - -func TestBuildNameWithReservedKeyWord(t *testing.T) { - s := splitKey([]string{"definitions", "fullview", "properties", "properties"}) - startIdx := 2 - segments := []string{"fullview"} - newName := s.BuildName(segments, startIdx, nil) - assert.Equal(t, "fullview properties", newName) - s = splitKey([]string{"definitions", "fullview", "properties", "properties", "properties", "properties", "properties", "properties"}) - newName = s.BuildName(segments, startIdx, nil) - assert.Equal(t, "fullview properties properties properties", newName) -} - -func TestNameInlinedSchemas(t *testing.T) { - cwd, _ := os.Getwd() - bp := filepath.Join(cwd, "fixtures", "nested_inline_schemas.yml") - sp, err := loadSpec(bp) - err = spec.ExpandSpec(sp, &spec.ExpandOptions{ - RelativeBase: bp, - SkipSchemas: true, - }) - assert.NoError(t, err) - values := []struct { - Key string - Location string - Ref spec.Ref - }{ - {"#/paths/~1some~1where~1{id}/get/parameters/2/schema/properties/record/items/2/properties/name", "#/definitions/getSomeWhereIdParamsBodyRecordItems2/properties/name", spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyRecordItems2Name")}, - {"#/paths/~1some~1where~1{id}/get/parameters/2/schema/properties/record/items/1", "#/definitions/getSomeWhereIdParamsBodyRecord/items/1", spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyRecordItems1")}, - {"#/paths/~1some~1where~1{id}/get/parameters/2/schema/properties/record/items/2", "#/definitions/getSomeWhereIdParamsBodyRecord/items/2", spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyRecordItems2")}, - {"#/paths/~1some~1where~1{id}/get/responses/200/schema/properties/record/items/2/properties/name", "#/definitions/getSomeWhereIdOKBodyRecordItems2/properties/name", spec.MustCreateRef("#/definitions/getSomeWhereIdOKBodyRecordItems2Name")}, - {"#/paths/~1some~1where~1{id}/get/responses/200/schema/properties/record/items/1", "#/definitions/getSomeWhereIdOKBodyRecord/items/1", spec.MustCreateRef("#/definitions/getSomeWhereIdOKBodyRecordItems1")}, - {"#/paths/~1some~1where~1{id}/get/responses/200/schema/properties/record/items/2", "#/definitions/getSomeWhereIdOKBodyRecord/items/2", spec.MustCreateRef("#/definitions/getSomeWhereIdOKBodyRecordItems2")}, - {"#/paths/~1some~1where~1{id}/get/responses/200/schema/properties/record", "#/definitions/getSomeWhereIdOKBody/properties/record", spec.MustCreateRef("#/definitions/getSomeWhereIdOKBodyRecord")}, - {"#/paths/~1some~1where~1{id}/get/responses/200/schema", "#/paths/~1some~1where~1{id}/get/responses/200/schema", spec.MustCreateRef("#/definitions/getSomeWhereIdOKBody")}, - {"#/paths/~1some~1where~1{id}/get/responses/default/schema/properties/record/items/2/properties/name", "#/definitions/getSomeWhereIdDefaultBodyRecordItems2/properties/name", spec.MustCreateRef("#/definitions/getSomeWhereIdDefaultBodyRecordItems2Name")}, - {"#/paths/~1some~1where~1{id}/get/responses/default/schema/properties/record/items/1", "#/definitions/getSomeWhereIdDefaultBodyRecord/items/1", spec.MustCreateRef("#/definitions/getSomeWhereIdDefaultBodyRecordItems1")}, - {"#/paths/~1some~1where~1{id}/get/responses/default/schema/properties/record/items/2", "#/definitions/getSomeWhereIdDefaultBodyRecord/items/2", spec.MustCreateRef("#/definitions/getSomeWhereIdDefaultBodyRecordItems2")}, - {"#/paths/~1some~1where~1{id}/get/responses/default/schema/properties/record", "#/definitions/getSomeWhereIdDefaultBody/properties/record", spec.MustCreateRef("#/definitions/getSomeWhereIdDefaultBodyRecord")}, - {"#/paths/~1some~1where~1{id}/get/responses/default/schema", "#/paths/~1some~1where~1{id}/get/responses/default/schema", spec.MustCreateRef("#/definitions/getSomeWhereIdDefaultBody")}, - {"#/definitions/nestedThing/properties/record/items/2/allOf/1/additionalProperties", "#/definitions/nestedThingRecordItems2AllOf1/additionalProperties", spec.MustCreateRef("#/definitions/nestedThingRecordItems2AllOf1AdditionalProperties")}, - {"#/definitions/nestedThing/properties/record/items/2/allOf/1", "#/definitions/nestedThingRecordItems2/allOf/1", spec.MustCreateRef("#/definitions/nestedThingRecordItems2AllOf1")}, - {"#/definitions/nestedThing/properties/record/items/2/properties/name", "#/definitions/nestedThingRecordItems2/properties/name", spec.MustCreateRef("#/definitions/nestedThingRecordItems2Name")}, - {"#/definitions/nestedThing/properties/record/items/1", "#/definitions/nestedThingRecord/items/1", spec.MustCreateRef("#/definitions/nestedThingRecordItems1")}, - {"#/definitions/nestedThing/properties/record/items/2", "#/definitions/nestedThingRecord/items/2", spec.MustCreateRef("#/definitions/nestedThingRecordItems2")}, - {"#/definitions/datedRecords/items/1", "#/definitions/datedRecords/items/1", spec.MustCreateRef("#/definitions/datedRecordsItems1")}, - {"#/definitions/datedTaggedRecords/items/1", "#/definitions/datedTaggedRecords/items/1", spec.MustCreateRef("#/definitions/datedTaggedRecordsItems1")}, - {"#/definitions/namedThing/properties/name", "#/definitions/namedThing/properties/name", spec.MustCreateRef("#/definitions/namedThingName")}, - {"#/definitions/nestedThing/properties/record", "#/definitions/nestedThing/properties/record", spec.MustCreateRef("#/definitions/nestedThingRecord")}, - {"#/definitions/records/items/0", "#/definitions/records/items/0", spec.MustCreateRef("#/definitions/recordsItems0")}, - {"#/definitions/datedTaggedRecords/additionalItems", "#/definitions/datedTaggedRecords/additionalItems", spec.MustCreateRef("#/definitions/datedTaggedRecordsItemsAdditionalItems")}, - {"#/definitions/otherRecords/items", "#/definitions/otherRecords/items", spec.MustCreateRef("#/definitions/otherRecordsItems")}, - {"#/definitions/tags/additionalProperties", "#/definitions/tags/additionalProperties", spec.MustCreateRef("#/definitions/tagsAdditionalProperties")}, - } - if assert.NoError(t, err) { - err := nameInlinedSchemas(&FlattenOpts{ - Spec: New(sp), - BasePath: bp, - }) - - if assert.NoError(t, err) { - for i, v := range values { - ptr, err := jsonpointer.New(v.Location[1:]) - if assert.NoError(t, err, "at %d for %s", i, v.Key) { - vv, _, err := ptr.Get(sp) - - if assert.NoError(t, err, "at %d for %s", i, v.Key) { - switch tv := vv.(type) { - case *spec.Schema: - assert.Equal(t, v.Ref.String(), tv.Ref.String(), "at %d for %s", i, v.Key) - case spec.Schema: - assert.Equal(t, v.Ref.String(), tv.Ref.String(), "at %d for %s", i, v.Key) - case *spec.SchemaOrBool: - var sRef spec.Ref - if tv != nil && tv.Schema != nil { - sRef = tv.Schema.Ref - } - assert.Equal(t, v.Ref.String(), sRef.String(), "at %d for %s", i, v.Key) - case *spec.SchemaOrArray: - var sRef spec.Ref - if tv != nil && tv.Schema != nil { - sRef = tv.Schema.Ref - } - assert.Equal(t, v.Ref.String(), sRef.String(), "at %d for %s", i, v.Key) - default: - assert.Fail(t, "unknown type", "got %T", vv) - } - } - } - } - } - - for k, rr := range New(sp).allSchemas { - if !strings.HasPrefix(k, "#/responses") && !strings.HasPrefix(k, "#/parameters") { - if rr.Schema != nil && rr.Schema.Ref.String() == "" && !rr.TopLevel { - asch, err := Schema(SchemaOpts{Schema: rr.Schema, Root: sp, BasePath: bp}) - if assert.NoError(t, err, "for key: %s", k) { - if !asch.IsSimpleSchema && !asch.IsArray { - assert.Fail(t, "not a top level schema", "for key: %s", k) - } - } - } - } - } - } -} - -func TestFlatten(t *testing.T) { - cwd, _ := os.Getwd() - bp := filepath.Join(cwd, "fixtures", "flatten.yml") - sp, err := loadSpec(bp) - values := []struct { - Key string - Location string - Ref spec.Ref - Expected interface{} - }{ - { - "#/responses/notFound/schema", - "#/responses/notFound/schema", - spec.MustCreateRef("#/definitions/error"), - nil, - }, - { - "#/paths/~1some~1where~1{id}/parameters/0", - "#/paths/~1some~1where~1{id}/parameters/0/name", - spec.Ref{}, - "id", - }, - { - "#/paths/~1other~1place", - "#/paths/~1other~1place/get/operationId", - spec.Ref{}, - "modelOp", - }, - { - "#/paths/~1some~1where~1{id}/get/parameters/0", - "#/paths/~1some~1where~1{id}/get/parameters/0/name", - spec.Ref{}, - "limit", - }, - { - "#/paths/~1some~1where~1{id}/get/parameters/1", - "#/paths/~1some~1where~1{id}/get/parameters/1/name", - spec.Ref{}, - "some", - }, - { - "#/paths/~1some~1where~1{id}/get/parameters/2", - "#/paths/~1some~1where~1{id}/get/parameters/2/name", - spec.Ref{}, - "other", - }, - { - "#/paths/~1some~1where~1{id}/get/parameters/3", - "#/paths/~1some~1where~1{id}/get/parameters/3/schema", - spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBody"), - "", - }, - { - "#/paths/~1some~1where~1{id}/get/responses/200", - "#/paths/~1some~1where~1{id}/get/responses/200/schema", - spec.MustCreateRef("#/definitions/getSomeWhereIdOKBody"), - "", - }, - { - "#/definitions/namedAgain", - "", - spec.MustCreateRef("#/definitions/named"), - "", - }, - { - "#/definitions/namedThing/properties/name", - "", - spec.MustCreateRef("#/definitions/named"), - "", - }, - { - "#/definitions/namedThing/properties/namedAgain", - "", - spec.MustCreateRef("#/definitions/namedAgain"), - "", - }, - { - "#/definitions/datedRecords/items/1", - "", - spec.MustCreateRef("#/definitions/record"), - "", - }, - { - "#/definitions/otherRecords/items", - "", - spec.MustCreateRef("#/definitions/record"), - "", - }, - { - "#/definitions/tags/additionalProperties", - "", - spec.MustCreateRef("#/definitions/tag"), - "", - }, - { - "#/definitions/datedTag/allOf/1", - "", - spec.MustCreateRef("#/definitions/tag"), - "", - }, - { - "#/definitions/nestedThingRecordItems2/allOf/1", - "", - spec.MustCreateRef("#/definitions/nestedThingRecordItems2AllOf1"), - "", - }, - { - "#/definitions/nestedThingRecord/items/1", - "", - spec.MustCreateRef("#/definitions/nestedThingRecordItems1"), - "", - }, - { - "#/definitions/nestedThingRecord/items/2", - "", - spec.MustCreateRef("#/definitions/nestedThingRecordItems2"), - "", - }, - { - "#/definitions/nestedThing/properties/record", - "", - spec.MustCreateRef("#/definitions/nestedThingRecord"), - "", - }, - { - "#/definitions/named", - "#/definitions/named/type", - spec.Ref{}, - spec.StringOrArray{"string"}, - }, - { - "#/definitions/error", - "#/definitions/error/properties/id/type", - spec.Ref{}, - spec.StringOrArray{"integer"}, - }, - { - "#/definitions/record", - "#/definitions/record/properties/createdAt/format", - spec.Ref{}, - "date-time", - }, - { - "#/definitions/getSomeWhereIdOKBody", - "#/definitions/getSomeWhereIdOKBody/properties/record", - spec.MustCreateRef("#/definitions/nestedThing"), - nil, - }, - { - "#/definitions/getSomeWhereIdParamsBody", - "#/definitions/getSomeWhereIdParamsBody/properties/record", - spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyRecord"), - nil, - }, - { - "#/definitions/getSomeWhereIdParamsBodyRecord", - "#/definitions/getSomeWhereIdParamsBodyRecord/items/1", - spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyRecordItems1"), - nil, - }, - { - "#/definitions/getSomeWhereIdParamsBodyRecord", - "#/definitions/getSomeWhereIdParamsBodyRecord/items/2", - spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyRecordItems2"), - nil, - }, - { - "#/definitions/getSomeWhereIdParamsBodyRecordItems2", - "#/definitions/getSomeWhereIdParamsBodyRecordItems2/allOf/0/format", - spec.Ref{}, - "date", - }, - { - "#/definitions/getSomeWhereIdParamsBodyRecordItems2Name", - "#/definitions/getSomeWhereIdParamsBodyRecordItems2Name/properties/createdAt/format", - spec.Ref{}, - "date-time", - }, - { - "#/definitions/getSomeWhereIdParamsBodyRecordItems2", - "#/definitions/getSomeWhereIdParamsBodyRecordItems2/properties/name", - spec.MustCreateRef("#/definitions/getSomeWhereIdParamsBodyRecordItems2Name"), - "date", - }, - } - if assert.NoError(t, err) { - err := Flatten(FlattenOpts{Spec: New(sp), BasePath: bp}) - //b, _ := sp.MarshalJSON() - //panic(string(b)) - if assert.NoError(t, err) { - for i, v := range values { - pk := v.Key[1:] - if v.Location != "" { - pk = v.Location[1:] - } - ptr, err := jsonpointer.New(pk) - if assert.NoError(t, err, "at %d for %s", i, v.Key) { - d, _, err := ptr.Get(sp) - if assert.NoError(t, err) { - if v.Ref.String() != "" { - switch s := d.(type) { - case *spec.Schema: - assert.Equal(t, v.Ref.String(), s.Ref.String(), "at %d for %s", i, v.Key) - case spec.Schema: - assert.Equal(t, v.Ref.String(), s.Ref.String(), "at %d for %s", i, v.Key) - case *spec.SchemaOrArray: - var sRef spec.Ref - if s != nil && s.Schema != nil { - sRef = s.Schema.Ref - } - assert.Equal(t, v.Ref.String(), sRef.String(), "at %d for %s", i, v.Key) - case *spec.SchemaOrBool: - var sRef spec.Ref - if s != nil && s.Schema != nil { - sRef = s.Schema.Ref - } - assert.Equal(t, v.Ref.String(), sRef.String(), "at %d for %s", i, v.Key) - default: - assert.Fail(t, "unknown type", "got %T at %d for %s", d, i, v.Key) - } - } else { - assert.Equal(t, v.Expected, d) - } - } - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/analysis/mixin.go b/vendor/github.com/go-openapi/analysis/mixin.go deleted file mode 100644 index a547433ba..000000000 --- a/vendor/github.com/go-openapi/analysis/mixin.go +++ /dev/null @@ -1,199 +0,0 @@ -package analysis - -import ( - "fmt" - - "github.com/go-openapi/spec" -) - -// Mixin modifies the primary swagger spec by adding the paths and -// definitions from the mixin specs. Top level parameters and -// responses from the mixins are also carried over. Operation id -// collisions are avoided by appending "Mixin" but only if -// needed. No other parts of primary are modified. Consider calling -// FixEmptyResponseDescriptions() on the modified primary if you read -// them from storage and they are valid to start with. -// -// Entries in "paths", "definitions", "parameters" and "responses" are -// added to the primary in the order of the given mixins. If the entry -// already exists in primary it is skipped with a warning message. -// -// The count of skipped entries (from collisions) is returned so any -// deviation from the number expected can flag warning in your build -// scripts. Carefully review the collisions before accepting them; -// consider renaming things if possible. -// -// No normalization of any keys takes place (paths, type defs, -// etc). Ensure they are canonical if your downstream tools do -// key normalization of any form. -func Mixin(primary *spec.Swagger, mixins ...*spec.Swagger) []string { - var skipped []string - opIds := getOpIds(primary) - if primary.Paths == nil { - primary.Paths = &spec.Paths{Paths: make(map[string]spec.PathItem)} - } - if primary.Paths.Paths == nil { - primary.Paths.Paths = make(map[string]spec.PathItem) - } - if primary.Definitions == nil { - primary.Definitions = make(spec.Definitions) - } - if primary.Parameters == nil { - primary.Parameters = make(map[string]spec.Parameter) - } - if primary.Responses == nil { - primary.Responses = make(map[string]spec.Response) - } - - for i, m := range mixins { - for k, v := range m.Definitions { - // assume name collisions represent IDENTICAL type. careful. - if _, exists := primary.Definitions[k]; exists { - warn := fmt.Sprintf("definitions entry '%v' already exists in primary or higher priority mixin, skipping\n", k) - skipped = append(skipped, warn) - continue - } - primary.Definitions[k] = v - } - if m.Paths != nil { - for k, v := range m.Paths.Paths { - if _, exists := primary.Paths.Paths[k]; exists { - warn := fmt.Sprintf("paths entry '%v' already exists in primary or higher priority mixin, skipping\n", k) - skipped = append(skipped, warn) - continue - } - - // Swagger requires that operationIds be - // unique within a spec. If we find a - // collision we append "Mixin0" to the - // operatoinId we are adding, where 0 is mixin - // index. We assume that operationIds with - // all the proivded specs are already unique. - piops := pathItemOps(v) - for _, piop := range piops { - if opIds[piop.ID] { - piop.ID = fmt.Sprintf("%v%v%v", piop.ID, "Mixin", i) - } - opIds[piop.ID] = true - } - primary.Paths.Paths[k] = v - } - } - for k, v := range m.Parameters { - // could try to rename on conflict but would - // have to fix $refs in the mixin. Complain - // for now - if _, exists := primary.Parameters[k]; exists { - warn := fmt.Sprintf("top level parameters entry '%v' already exists in primary or higher priority mixin, skipping\n", k) - skipped = append(skipped, warn) - continue - } - primary.Parameters[k] = v - } - for k, v := range m.Responses { - // could try to rename on conflict but would - // have to fix $refs in the mixin. Complain - // for now - if _, exists := primary.Responses[k]; exists { - warn := fmt.Sprintf("top level responses entry '%v' already exists in primary or higher priority mixin, skipping\n", k) - skipped = append(skipped, warn) - continue - } - primary.Responses[k] = v - } - } - return skipped -} - -// FixEmptyResponseDescriptions replaces empty ("") response -// descriptions in the input with "(empty)" to ensure that the -// resulting Swagger is stays valid. The problem appears to arise -// from reading in valid specs that have a explicit response -// description of "" (valid, response.description is required), but -// due to zero values being omitted upon re-serializing (omitempty) we -// lose them unless we stick some chars in there. -func FixEmptyResponseDescriptions(s *spec.Swagger) { - if s.Paths != nil { - for _, v := range s.Paths.Paths { - if v.Get != nil { - FixEmptyDescs(v.Get.Responses) - } - if v.Put != nil { - FixEmptyDescs(v.Put.Responses) - } - if v.Post != nil { - FixEmptyDescs(v.Post.Responses) - } - if v.Delete != nil { - FixEmptyDescs(v.Delete.Responses) - } - if v.Options != nil { - FixEmptyDescs(v.Options.Responses) - } - if v.Head != nil { - FixEmptyDescs(v.Head.Responses) - } - if v.Patch != nil { - FixEmptyDescs(v.Patch.Responses) - } - } - } - for k, v := range s.Responses { - FixEmptyDesc(&v) - s.Responses[k] = v - } -} - -// FixEmptyDescs adds "(empty)" as the description for any Response in -// the given Responses object that doesn't already have one. -func FixEmptyDescs(rs *spec.Responses) { - FixEmptyDesc(rs.Default) - for k, v := range rs.StatusCodeResponses { - FixEmptyDesc(&v) - rs.StatusCodeResponses[k] = v - } -} - -// FixEmptyDesc adds "(empty)" as the description to the given -// Response object if it doesn't already have one and isn't a -// ref. No-op on nil input. -func FixEmptyDesc(rs *spec.Response) { - if rs == nil || rs.Description != "" || rs.Ref.Ref.GetURL() != nil { - return - } - rs.Description = "(empty)" -} - -// getOpIds extracts all the paths..operationIds from the given -// spec and returns them as the keys in a map with 'true' values. -func getOpIds(s *spec.Swagger) map[string]bool { - rv := make(map[string]bool) - if s.Paths == nil { - return rv - } - for _, v := range s.Paths.Paths { - piops := pathItemOps(v) - for _, op := range piops { - rv[op.ID] = true - } - } - return rv -} - -func pathItemOps(p spec.PathItem) []*spec.Operation { - var rv []*spec.Operation - rv = appendOp(rv, p.Get) - rv = appendOp(rv, p.Put) - rv = appendOp(rv, p.Post) - rv = appendOp(rv, p.Delete) - rv = appendOp(rv, p.Head) - rv = appendOp(rv, p.Patch) - return rv -} - -func appendOp(ops []*spec.Operation, op *spec.Operation) []*spec.Operation { - if op == nil { - return ops - } - return append(ops, op) -} diff --git a/vendor/github.com/go-openapi/analysis/mixin_test.go b/vendor/github.com/go-openapi/analysis/mixin_test.go deleted file mode 100644 index 1d8028217..000000000 --- a/vendor/github.com/go-openapi/analysis/mixin_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package analysis - -import "testing" - -const ( - widgetFile = "fixtures/widget-crud.yml" - fooFile = "fixtures/foo-crud.yml" - barFile = "fixtures/bar-crud.yml" - noPathsFile = "fixtures/no-paths.yml" - emptyPathsFile = "fixtures/empty-paths.json" -) - -func TestMixin(t *testing.T) { - - primary, err := loadSpec(widgetFile) - if err != nil { - t.Fatalf("Could not load '%v': %v\n", widgetFile, err) - } - mixin1, err := loadSpec(fooFile) - if err != nil { - t.Fatalf("Could not load '%v': %v\n", fooFile, err) - } - mixin2, err := loadSpec(barFile) - if err != nil { - t.Fatalf("Could not load '%v': %v\n", barFile, err) - } - mixin3, err := loadSpec(noPathsFile) - if err != nil { - t.Fatalf("Could not load '%v': %v\n", noPathsFile, err) - } - - collisions := Mixin(primary, mixin1, mixin2, mixin3) - if len(collisions) != 16 { - t.Errorf("TestMixin: Expected 16 collisions, got %v\n%v", len(collisions), collisions) - } - - if len(primary.Paths.Paths) != 7 { - t.Errorf("TestMixin: Expected 7 paths in merged, got %v\n", len(primary.Paths.Paths)) - } - - if len(primary.Definitions) != 8 { - t.Errorf("TestMixin: Expected 8 definitions in merged, got %v\n", len(primary.Definitions)) - } - - if len(primary.Parameters) != 4 { - t.Errorf("TestMixin: Expected 4 top level parameters in merged, got %v\n", len(primary.Parameters)) - } - - if len(primary.Responses) != 2 { - t.Errorf("TestMixin: Expected 2 top level responses in merged, got %v\n", len(primary.Responses)) - } - - // test that adding paths to a primary with no paths works (was NPE) - emptyPaths, err := loadSpec(emptyPathsFile) - if err != nil { - t.Fatalf("Could not load '%v': %v\n", emptyPathsFile, err) - } - - collisions = Mixin(emptyPaths, primary) - if len(collisions) != 0 { - t.Errorf("TestMixin: Expected 0 collisions, got %v\n%v", len(collisions), collisions) - } - -} diff --git a/vendor/github.com/go-openapi/analysis/schema.go b/vendor/github.com/go-openapi/analysis/schema.go deleted file mode 100644 index 3ef64d753..000000000 --- a/vendor/github.com/go-openapi/analysis/schema.go +++ /dev/null @@ -1,234 +0,0 @@ -package analysis - -import ( - "github.com/go-openapi/spec" - "github.com/go-openapi/strfmt" -) - -// SchemaOpts configures the schema analyzer -type SchemaOpts struct { - Schema *spec.Schema - Root interface{} - BasePath string - _ struct{} -} - -// Schema analysis, will classify the schema according to known -// patterns. -func Schema(opts SchemaOpts) (*AnalyzedSchema, error) { - a := &AnalyzedSchema{ - schema: opts.Schema, - root: opts.Root, - basePath: opts.BasePath, - } - - a.initializeFlags() - a.inferKnownType() - a.inferEnum() - a.inferBaseType() - - if err := a.inferMap(); err != nil { - return nil, err - } - if err := a.inferArray(); err != nil { - return nil, err - } - - if err := a.inferTuple(); err != nil { - return nil, err - } - - if err := a.inferFromRef(); err != nil { - return nil, err - } - - a.inferSimpleSchema() - return a, nil -} - -// AnalyzedSchema indicates what the schema represents -type AnalyzedSchema struct { - schema *spec.Schema - root interface{} - basePath string - - hasProps bool - hasAllOf bool - hasItems bool - hasAdditionalProps bool - hasAdditionalItems bool - hasRef bool - - IsKnownType bool - IsSimpleSchema bool - IsArray bool - IsSimpleArray bool - IsMap bool - IsSimpleMap bool - IsExtendedObject bool - IsTuple bool - IsTupleWithExtra bool - IsBaseType bool - IsEnum bool -} - -// Inherits copies value fields from other onto this schema -func (a *AnalyzedSchema) inherits(other *AnalyzedSchema) { - if other == nil { - return - } - a.hasProps = other.hasProps - a.hasAllOf = other.hasAllOf - a.hasItems = other.hasItems - a.hasAdditionalItems = other.hasAdditionalItems - a.hasAdditionalProps = other.hasAdditionalProps - a.hasRef = other.hasRef - - a.IsKnownType = other.IsKnownType - a.IsSimpleSchema = other.IsSimpleSchema - a.IsArray = other.IsArray - a.IsSimpleArray = other.IsSimpleArray - a.IsMap = other.IsMap - a.IsSimpleMap = other.IsSimpleMap - a.IsExtendedObject = other.IsExtendedObject - a.IsTuple = other.IsTuple - a.IsTupleWithExtra = other.IsTupleWithExtra - a.IsBaseType = other.IsBaseType - a.IsEnum = other.IsEnum -} - -func (a *AnalyzedSchema) inferFromRef() error { - if a.hasRef { - sch := new(spec.Schema) - sch.Ref = a.schema.Ref - err := spec.ExpandSchema(sch, a.root, nil) - if err != nil { - return err - } - if sch != nil { - rsch, err := Schema(SchemaOpts{ - Schema: sch, - Root: a.root, - BasePath: a.basePath, - }) - if err != nil { - return err - } - a.inherits(rsch) - } - } - return nil -} - -func (a *AnalyzedSchema) inferSimpleSchema() { - a.IsSimpleSchema = a.IsKnownType || a.IsSimpleArray || a.IsSimpleMap -} - -func (a *AnalyzedSchema) inferKnownType() { - tpe := a.schema.Type - format := a.schema.Format - a.IsKnownType = tpe.Contains("boolean") || - tpe.Contains("integer") || - tpe.Contains("number") || - tpe.Contains("string") || - (format != "" && strfmt.Default.ContainsName(format)) || - (a.isObjectType() && !a.hasProps && !a.hasAllOf && !a.hasAdditionalProps && !a.hasAdditionalItems) -} - -func (a *AnalyzedSchema) inferMap() error { - if a.isObjectType() { - hasExtra := a.hasProps || a.hasAllOf - a.IsMap = a.hasAdditionalProps && !hasExtra - a.IsExtendedObject = a.hasAdditionalProps && hasExtra - if a.IsMap { - if a.schema.AdditionalProperties.Schema != nil { - msch, err := Schema(SchemaOpts{ - Schema: a.schema.AdditionalProperties.Schema, - Root: a.root, - BasePath: a.basePath, - }) - if err != nil { - return err - } - a.IsSimpleMap = msch.IsSimpleSchema - } else if a.schema.AdditionalProperties.Allows { - a.IsSimpleMap = true - } - } - } - return nil -} - -func (a *AnalyzedSchema) inferArray() error { - fromValid := a.isArrayType() && (a.schema.Items == nil || a.schema.Items.Len() < 2) - a.IsArray = fromValid || (a.hasItems && a.schema.Items.Len() < 2) - if a.IsArray && a.hasItems { - if a.schema.Items.Schema != nil { - itsch, err := Schema(SchemaOpts{ - Schema: a.schema.Items.Schema, - Root: a.root, - BasePath: a.basePath, - }) - if err != nil { - return err - } - a.IsSimpleArray = itsch.IsSimpleSchema - } - if len(a.schema.Items.Schemas) > 0 { - itsch, err := Schema(SchemaOpts{ - Schema: &a.schema.Items.Schemas[0], - Root: a.root, - BasePath: a.basePath, - }) - if err != nil { - return err - } - a.IsSimpleArray = itsch.IsSimpleSchema - } - } - if a.IsArray && !a.hasItems { - a.IsSimpleArray = true - } - return nil -} - -func (a *AnalyzedSchema) inferTuple() error { - tuple := a.hasItems && a.schema.Items.Len() > 1 - a.IsTuple = tuple && !a.hasAdditionalItems - a.IsTupleWithExtra = tuple && a.hasAdditionalItems - return nil -} - -func (a *AnalyzedSchema) inferBaseType() { - if a.isObjectType() { - a.IsBaseType = a.schema.Discriminator != "" - } -} - -func (a *AnalyzedSchema) inferEnum() { - a.IsEnum = len(a.schema.Enum) > 0 -} - -func (a *AnalyzedSchema) initializeFlags() { - a.hasProps = len(a.schema.Properties) > 0 - a.hasAllOf = len(a.schema.AllOf) > 0 - a.hasRef = a.schema.Ref.String() != "" - - a.hasItems = a.schema.Items != nil && - (a.schema.Items.Schema != nil || len(a.schema.Items.Schemas) > 0) - - a.hasAdditionalProps = a.schema.AdditionalProperties != nil && - (a.schema.AdditionalProperties != nil || a.schema.AdditionalProperties.Allows) - - a.hasAdditionalItems = a.schema.AdditionalItems != nil && - (a.schema.AdditionalItems.Schema != nil || a.schema.AdditionalItems.Allows) - -} - -func (a *AnalyzedSchema) isObjectType() bool { - return !a.hasRef && (a.schema.Type == nil || a.schema.Type.Contains("") || a.schema.Type.Contains("object")) -} - -func (a *AnalyzedSchema) isArrayType() bool { - return !a.hasRef && (a.schema.Type != nil && a.schema.Type.Contains("array")) -} diff --git a/vendor/github.com/go-openapi/analysis/schema_test.go b/vendor/github.com/go-openapi/analysis/schema_test.go deleted file mode 100644 index 0c386b2a4..000000000 --- a/vendor/github.com/go-openapi/analysis/schema_test.go +++ /dev/null @@ -1,266 +0,0 @@ -package analysis - -import ( - "encoding/json" - "fmt" - "path" - "testing" - - "net/http" - "net/http/httptest" - - "github.com/go-openapi/spec" - "github.com/stretchr/testify/assert" -) - -var knownSchemas = []*spec.Schema{ - spec.BoolProperty(), // 0 - spec.StringProperty(), // 1 - spec.Int8Property(), // 2 - spec.Int16Property(), // 3 - spec.Int32Property(), // 4 - spec.Int64Property(), // 5 - spec.Float32Property(), // 6 - spec.Float64Property(), // 7 - spec.DateProperty(), // 8 - spec.DateTimeProperty(), // 9 - (&spec.Schema{}), // 10 - (&spec.Schema{}).Typed("object", ""), // 11 - (&spec.Schema{}).Typed("", ""), // 12 - (&spec.Schema{}).Typed("", "uuid"), // 13 -} - -func newCObj() *spec.Schema { - return (&spec.Schema{}).Typed("object", "").SetProperty("id", *spec.Int64Property()) -} - -var complexObject = newCObj() - -var complexSchemas = []*spec.Schema{ - complexObject, - spec.ArrayProperty(complexObject), - spec.MapProperty(complexObject), -} - -func knownRefs(base string) []spec.Ref { - urls := []string{"bool", "string", "integer", "float", "date", "object", "format"} - - var result []spec.Ref - for _, u := range urls { - result = append(result, spec.MustCreateRef(fmt.Sprintf("%s/%s", base, path.Join("known", u)))) - } - return result -} - -func complexRefs(base string) []spec.Ref { - urls := []string{"object", "array", "map"} - - var result []spec.Ref - for _, u := range urls { - result = append(result, spec.MustCreateRef(fmt.Sprintf("%s/%s", base, path.Join("complex", u)))) - } - return result -} - -func refServer() *httptest.Server { - mux := http.NewServeMux() - mux.Handle("/known/bool", schemaHandler(knownSchemas[0])) - mux.Handle("/known/string", schemaHandler(knownSchemas[1])) - mux.Handle("/known/integer", schemaHandler(knownSchemas[5])) - mux.Handle("/known/float", schemaHandler(knownSchemas[6])) - mux.Handle("/known/date", schemaHandler(knownSchemas[8])) - mux.Handle("/known/object", schemaHandler(knownSchemas[11])) - mux.Handle("/known/format", schemaHandler(knownSchemas[13])) - - mux.Handle("/complex/object", schemaHandler(complexSchemas[0])) - mux.Handle("/complex/array", schemaHandler(complexSchemas[1])) - mux.Handle("/complex/map", schemaHandler(complexSchemas[2])) - - return httptest.NewServer(mux) -} - -func refSchema(ref spec.Ref) *spec.Schema { - return &spec.Schema{SchemaProps: spec.SchemaProps{Ref: ref}} -} - -func schemaHandler(schema *spec.Schema) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - writeJSON(w, schema) - }) -} - -func writeJSON(w http.ResponseWriter, data interface{}) { - w.Header().Add("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - enc := json.NewEncoder(w) - if err := enc.Encode(data); err != nil { - panic(err) - } -} - -func TestSchemaAnalysis_KnownTypes(t *testing.T) { - for i, v := range knownSchemas { - sch, err := Schema(SchemaOpts{Schema: v}) - if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) { - assert.True(t, sch.IsKnownType, "item at %d should be a known type", i) - } - } - for i, v := range complexSchemas { - sch, err := Schema(SchemaOpts{Schema: v}) - if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) { - assert.False(t, sch.IsKnownType, "item at %d should not be a known type", i) - } - } - - serv := refServer() - defer serv.Close() - - for i, ref := range knownRefs(serv.URL) { - sch, err := Schema(SchemaOpts{Schema: refSchema(ref)}) - if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) { - assert.True(t, sch.IsKnownType, "item at %d should be a known type", i) - } - } - for i, ref := range complexRefs(serv.URL) { - sch, err := Schema(SchemaOpts{Schema: refSchema(ref)}) - if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) { - assert.False(t, sch.IsKnownType, "item at %d should not be a known type", i) - } - } -} - -func TestSchemaAnalysis_Array(t *testing.T) { - for i, v := range append(knownSchemas, (&spec.Schema{}).Typed("array", "")) { - sch, err := Schema(SchemaOpts{Schema: spec.ArrayProperty(v)}) - if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) { - assert.True(t, sch.IsArray, "item at %d should be an array type", i) - assert.True(t, sch.IsSimpleArray, "item at %d should be a simple array type", i) - } - } - - for i, v := range complexSchemas { - sch, err := Schema(SchemaOpts{Schema: spec.ArrayProperty(v)}) - if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) { - assert.True(t, sch.IsArray, "item at %d should be an array type", i) - assert.False(t, sch.IsSimpleArray, "item at %d should not be a simple array type", i) - } - } - - serv := refServer() - defer serv.Close() - - for i, ref := range knownRefs(serv.URL) { - sch, err := Schema(SchemaOpts{Schema: spec.ArrayProperty(refSchema(ref))}) - if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) { - assert.True(t, sch.IsArray, "item at %d should be an array type", i) - assert.True(t, sch.IsSimpleArray, "item at %d should be a simple array type", i) - } - } - for i, ref := range complexRefs(serv.URL) { - sch, err := Schema(SchemaOpts{Schema: spec.ArrayProperty(refSchema(ref))}) - if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) { - assert.False(t, sch.IsKnownType, "item at %d should not be a known type", i) - assert.True(t, sch.IsArray, "item at %d should be an array type", i) - assert.False(t, sch.IsSimpleArray, "item at %d should not be a simple array type", i) - } - } - -} - -func TestSchemaAnalysis_Map(t *testing.T) { - for i, v := range append(knownSchemas, spec.MapProperty(nil)) { - sch, err := Schema(SchemaOpts{Schema: spec.MapProperty(v)}) - if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) { - assert.True(t, sch.IsMap, "item at %d should be a map type", i) - assert.True(t, sch.IsSimpleMap, "item at %d should be a simple map type", i) - } - } - - for i, v := range complexSchemas { - sch, err := Schema(SchemaOpts{Schema: spec.MapProperty(v)}) - if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) { - assert.True(t, sch.IsMap, "item at %d should be a map type", i) - assert.False(t, sch.IsSimpleMap, "item at %d should not be a simple map type", i) - } - } -} - -func TestSchemaAnalysis_ExtendedObject(t *testing.T) { - for i, v := range knownSchemas { - wex := spec.MapProperty(v).SetProperty("name", *spec.StringProperty()) - sch, err := Schema(SchemaOpts{Schema: wex}) - if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) { - assert.True(t, sch.IsExtendedObject, "item at %d should be an extended map object type", i) - assert.False(t, sch.IsMap, "item at %d should not be a map type", i) - assert.False(t, sch.IsSimpleMap, "item at %d should not be a simple map type", i) - } - } -} - -func TestSchemaAnalysis_Tuple(t *testing.T) { - at := spec.ArrayProperty(nil) - at.Items = &spec.SchemaOrArray{} - at.Items.Schemas = append(at.Items.Schemas, *spec.StringProperty(), *spec.Int64Property()) - - sch, err := Schema(SchemaOpts{Schema: at}) - if assert.NoError(t, err) { - assert.True(t, sch.IsTuple) - assert.False(t, sch.IsTupleWithExtra) - assert.False(t, sch.IsKnownType) - assert.False(t, sch.IsSimpleSchema) - } -} - -func TestSchemaAnalysis_TupleWithExtra(t *testing.T) { - at := spec.ArrayProperty(nil) - at.Items = &spec.SchemaOrArray{} - at.Items.Schemas = append(at.Items.Schemas, *spec.StringProperty(), *spec.Int64Property()) - at.AdditionalItems = &spec.SchemaOrBool{Allows: true} - at.AdditionalItems.Schema = spec.Int32Property() - - sch, err := Schema(SchemaOpts{Schema: at}) - if assert.NoError(t, err) { - assert.False(t, sch.IsTuple) - assert.True(t, sch.IsTupleWithExtra) - assert.False(t, sch.IsKnownType) - assert.False(t, sch.IsSimpleSchema) - } -} - -func TestSchemaAnalysis_BaseType(t *testing.T) { - cl := (&spec.Schema{}).Typed("object", "").SetProperty("type", *spec.StringProperty()).WithDiscriminator("type") - - sch, err := Schema(SchemaOpts{Schema: cl}) - if assert.NoError(t, err) { - assert.True(t, sch.IsBaseType) - assert.False(t, sch.IsKnownType) - assert.False(t, sch.IsSimpleSchema) - } -} - -func TestSchemaAnalysis_SimpleSchema(t *testing.T) { - for i, v := range append(knownSchemas, spec.ArrayProperty(nil), spec.MapProperty(nil)) { - sch, err := Schema(SchemaOpts{Schema: v}) - if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) { - assert.True(t, sch.IsSimpleSchema, "item at %d should be a simple schema", i) - } - - asch, err := Schema(SchemaOpts{Schema: spec.ArrayProperty(v)}) - if assert.NoError(t, err, "failed to analyze array schema at %d: %v", i, err) { - assert.True(t, asch.IsSimpleSchema, "array item at %d should be a simple schema", i) - } - - msch, err := Schema(SchemaOpts{Schema: spec.MapProperty(v)}) - if assert.NoError(t, err, "failed to analyze map schema at %d: %v", i, err) { - assert.True(t, msch.IsSimpleSchema, "map item at %d should be a simple schema", i) - } - } - - for i, v := range complexSchemas { - sch, err := Schema(SchemaOpts{Schema: v}) - if assert.NoError(t, err, "failed to analyze schema at %d: %v", i, err) { - assert.False(t, sch.IsSimpleSchema, "item at %d should not be a simple schema", i) - } - } - -} diff --git a/vendor/github.com/go-openapi/errors/.github/CONTRIBUTING.md b/vendor/github.com/go-openapi/errors/.github/CONTRIBUTING.md deleted file mode 100644 index 7dea4240d..000000000 --- a/vendor/github.com/go-openapi/errors/.github/CONTRIBUTING.md +++ /dev/null @@ -1,117 +0,0 @@ -## Contribution Guidelines - -### Pull requests are always welcome - -We are always thrilled to receive pull requests, and do our best to -process them as fast as possible. Not sure if that typo is worth a pull -request? Do it! We will appreciate it. - -If your pull request is not accepted on the first try, don't be -discouraged! If there's a problem with the implementation, hopefully you -received feedback on what to improve. - -We're trying very hard to keep go-swagger lean and focused. We don't want it -to do everything for everybody. This means that we might decide against -incorporating a new feature. However, there might be a way to implement -that feature *on top of* go-swagger. - - -### Conventions - -Fork the repo and make changes on your fork in a feature branch: - -- If it's a bugfix branch, name it XXX-something where XXX is the number of the - issue -- If it's a feature branch, create an enhancement issue to announce your - intentions, and name it XXX-something where XXX is the number of the issue. - -Submit unit tests for your changes. Go has a great test framework built in; use -it! Take a look at existing tests for inspiration. Run the full test suite on -your branch before submitting a pull request. - -Update the documentation when creating or modifying features. Test -your documentation changes for clarity, concision, and correctness, as -well as a clean documentation build. See ``docs/README.md`` for more -information on building the docs and how docs get released. - -Write clean code. Universally formatted code promotes ease of writing, reading, -and maintenance. Always run `gofmt -s -w file.go` on each changed file before -committing your changes. Most editors have plugins that do this automatically. - -Pull requests descriptions should be as clear as possible and include a -reference to all the issues that they address. - -Pull requests must not contain commits from other users or branches. - -Commit messages must start with a capitalized and short summary (max. 50 -chars) written in the imperative, followed by an optional, more detailed -explanatory text which is separated from the summary by an empty line. - -Code review comments may be added to your pull request. Discuss, then make the -suggested modifications and push additional commits to your feature branch. Be -sure to post a comment after pushing. The new commits will show up in the pull -request automatically, but the reviewers will not be notified unless you -comment. - -Before the pull request is merged, make sure that you squash your commits into -logical units of work using `git rebase -i` and `git push -f`. After every -commit the test suite should be passing. Include documentation changes in the -same commit so that a revert would remove all traces of the feature or fix. - -Commits that fix or close an issue should include a reference like `Closes #XXX` -or `Fixes #XXX`, which will automatically close the issue when merged. - -### Sign your work - -The sign-off is a simple line at the end of the explanation for the -patch, which certifies that you wrote it or otherwise have the right to -pass it on as an open-source patch. The rules are pretty simple: if you -can certify the below (from -[developercertificate.org](http://developercertificate.org/)): - -``` -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` - -then you just add a line to every git commit message: - - Signed-off-by: Joe Smith - -using your real name (sorry, no pseudonyms or anonymous contributions.) - -You can add the sign off when creating the git commit via `git commit -s`. diff --git a/vendor/github.com/go-openapi/errors/.gitignore b/vendor/github.com/go-openapi/errors/.gitignore deleted file mode 100644 index dd91ed6a0..000000000 --- a/vendor/github.com/go-openapi/errors/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -secrets.yml -coverage.out diff --git a/vendor/github.com/go-openapi/errors/.travis.yml b/vendor/github.com/go-openapi/errors/.travis.yml deleted file mode 100644 index 8d22a34a9..000000000 --- a/vendor/github.com/go-openapi/errors/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go -go: -- 1.7 -install: -- go get -u github.com/stretchr/testify/assert -script: -- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./... -after_success: -- bash <(curl -s https://codecov.io/bash) -notifications: - slack: - secure: gZGp9NaHxi7zawlXJXKY92BGeDR1x0tbIcTyU5nMKLq0fhIaiEBJEeALwZ4VgqsSv3DytSSF5mLH8fevAM3ixE6hxjKQ+lQuf7V/w3btCN1CSWgoua5LOh1kTnqZQtJuRvO4pzoJcT3bJWBsVZ07VGNVzzJEy/zAKCHFqBUCXShw7QemlLBcYWFNqveTlvDIfCzvouoLnPoXwxEpkjxe9uz/ZKZgAnup/fXjC8RFctmgCnkCyvJTk0Y/fZCsufixJrJhshBWTnlrFCzRmgNkz2d+i1Ls3+MJ5EJJ2Tx/A5S63dL49J1f9Kr0AKHADmulSy8JNzIckKwbyFMYUecrsW+Lsu9DhnVMy1jj5pKsJDLRi2iIU3fXTMWbcyQbXjbbnBO2mPdP3Tzme75y4D9fc8hUPeyqVv2BU26NEbQ7EF2pKJ93OXvci7HlwRBgdJa8j6mP2LEDClcPQW00g7N/OZe0cTOMa8L5AwiBlbArwqt9wv6YLJoTG0wpDhzWsFvbCg5bJxe28Yn3fIDD0Lk1I7iSnBbp/5gzF19jmxqvcT8tHRkDL4xfjbENFTZjA5uB4Z4pj4WSyWQILLV/Jwhe3fi9uQwdviFHfj5pnVrmNUiGSOQL672K5wl2c3E9mGwejvsu2dfEz28n7Y/FUnOpY3/cBS0n27JJaerS0zMKNLE= diff --git a/vendor/github.com/go-openapi/errors/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/errors/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e..000000000 --- a/vendor/github.com/go-openapi/errors/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/errors/LICENSE b/vendor/github.com/go-openapi/errors/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/go-openapi/errors/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/go-openapi/errors/README.md b/vendor/github.com/go-openapi/errors/README.md deleted file mode 100644 index 48c49fb2d..000000000 --- a/vendor/github.com/go-openapi/errors/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# OpenAPI errors [![Build Status](https://travis-ci.org/go-openapi/errors.svg?branch=master)](https://travis-ci.org/go-openapi/errors) [![codecov](https://codecov.io/gh/go-openapi/errors/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/errors) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/errors/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/errors?status.svg)](http://godoc.org/github.com/go-openapi/errors) - -Shared errors used throughout the various libraries for the go-openapi toolkit \ No newline at end of file diff --git a/vendor/github.com/go-openapi/errors/api.go b/vendor/github.com/go-openapi/errors/api.go deleted file mode 100644 index 64e0e7300..000000000 --- a/vendor/github.com/go-openapi/errors/api.go +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package errors - -import ( - "encoding/json" - "fmt" - "net/http" - "strings" -) - -// Error represents a error interface all swagger framework errors implement -type Error interface { - error - Code() int32 -} - -type apiError struct { - code int32 - message string -} - -func (a *apiError) Error() string { - return a.message -} - -func (a *apiError) Code() int32 { - return a.code -} - -// New creates a new API error with a code and a message -func New(code int32, message string, args ...interface{}) Error { - if len(args) > 0 { - return &apiError{code, fmt.Sprintf(message, args...)} - } - return &apiError{code, message} -} - -// NotFound creates a new not found error -func NotFound(message string, args ...interface{}) Error { - if message == "" { - message = "Not found" - } - return New(http.StatusNotFound, fmt.Sprintf(message, args...)) -} - -// NotImplemented creates a new not implemented error -func NotImplemented(message string) Error { - return New(http.StatusNotImplemented, message) -} - -// MethodNotAllowedError represents an error for when the path matches but the method doesn't -type MethodNotAllowedError struct { - code int32 - Allowed []string - message string -} - -func (m *MethodNotAllowedError) Error() string { - return m.message -} - -// Code the error code -func (m *MethodNotAllowedError) Code() int32 { - return m.code -} - -func errorAsJSON(err Error) []byte { - b, _ := json.Marshal(struct { - Code int32 `json:"code"` - Message string `json:"message"` - }{err.Code(), err.Error()}) - return b -} - -func flattenComposite(errs *CompositeError) *CompositeError { - var res []error - for _, er := range errs.Errors { - switch e := er.(type) { - case *CompositeError: - if len(e.Errors) > 0 { - flat := flattenComposite(e) - if len(flat.Errors) > 0 { - res = append(res, flat.Errors...) - } - } - default: - if e != nil { - res = append(res, e) - } - } - } - return CompositeValidationError(res...) -} - -// MethodNotAllowed creates a new method not allowed error -func MethodNotAllowed(requested string, allow []string) Error { - msg := fmt.Sprintf("method %s is not allowed, but [%s] are", requested, strings.Join(allow, ",")) - return &MethodNotAllowedError{code: http.StatusMethodNotAllowed, Allowed: allow, message: msg} -} - -// ServeError the error handler interface implemenation -func ServeError(rw http.ResponseWriter, r *http.Request, err error) { - rw.Header().Set("Content-Type", "application/json") - switch e := err.(type) { - case *CompositeError: - er := flattenComposite(e) - ServeError(rw, r, er.Errors[0]) - case *MethodNotAllowedError: - rw.Header().Add("Allow", strings.Join(err.(*MethodNotAllowedError).Allowed, ",")) - rw.WriteHeader(asHTTPCode(int(e.Code()))) - if r == nil || r.Method != "HEAD" { - rw.Write(errorAsJSON(e)) - } - case Error: - if e == nil { - rw.WriteHeader(http.StatusInternalServerError) - rw.Write(errorAsJSON(New(http.StatusInternalServerError, "Unknown error"))) - return - } - rw.WriteHeader(asHTTPCode(int(e.Code()))) - if r == nil || r.Method != "HEAD" { - rw.Write(errorAsJSON(e)) - } - default: - rw.WriteHeader(http.StatusInternalServerError) - if r == nil || r.Method != "HEAD" { - rw.Write(errorAsJSON(New(http.StatusInternalServerError, err.Error()))) - } - } -} - -func asHTTPCode(input int) int { - if input >= 600 { - return 422 - } - return input -} diff --git a/vendor/github.com/go-openapi/errors/api_test.go b/vendor/github.com/go-openapi/errors/api_test.go deleted file mode 100644 index 4c928172d..000000000 --- a/vendor/github.com/go-openapi/errors/api_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package errors - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestServeError(t *testing.T) { - // method not allowed wins - var err error - err = MethodNotAllowed("GET", []string{"POST", "PUT"}) - recorder := httptest.NewRecorder() - ServeError(recorder, nil, err) - assert.Equal(t, http.StatusMethodNotAllowed, recorder.Code) - assert.Equal(t, "POST,PUT", recorder.Header().Get("Allow")) - // assert.Equal(t, "application/json", recorder.Header().Get("content-type")) - assert.Equal(t, `{"code":405,"message":"method GET is not allowed, but [POST,PUT] are"}`, recorder.Body.String()) - - // renders status code from error when present - err = NotFound("") - recorder = httptest.NewRecorder() - ServeError(recorder, nil, err) - assert.Equal(t, http.StatusNotFound, recorder.Code) - // assert.Equal(t, "application/json", recorder.Header().Get("content-type")) - assert.Equal(t, `{"code":404,"message":"Not found"}`, recorder.Body.String()) - - // renders mapped status code from error when present - err = InvalidTypeName("someType") - recorder = httptest.NewRecorder() - ServeError(recorder, nil, err) - assert.Equal(t, http.StatusUnprocessableEntity, recorder.Code) - // assert.Equal(t, "application/json", recorder.Header().Get("content-type")) - assert.Equal(t, `{"code":601,"message":"someType is an invalid type name"}`, recorder.Body.String()) - - // defaults to internal server error - err = fmt.Errorf("some error") - recorder = httptest.NewRecorder() - ServeError(recorder, nil, err) - assert.Equal(t, http.StatusInternalServerError, recorder.Code) - // assert.Equal(t, "application/json", recorder.Header().Get("content-type")) - assert.Equal(t, `{"code":500,"message":"some error"}`, recorder.Body.String()) -} - -func TestAPIErrors(t *testing.T) { - err := New(402, "this failed %s", "yada") - assert.Error(t, err) - assert.EqualValues(t, 402, err.Code()) - assert.EqualValues(t, "this failed yada", err.Error()) - - err = NotFound("this failed %d", 1) - assert.Error(t, err) - assert.EqualValues(t, http.StatusNotFound, err.Code()) - assert.EqualValues(t, "this failed 1", err.Error()) - - err = NotFound("") - assert.Error(t, err) - assert.EqualValues(t, http.StatusNotFound, err.Code()) - assert.EqualValues(t, "Not found", err.Error()) - - err = NotImplemented("not implemented") - assert.Error(t, err) - assert.EqualValues(t, http.StatusNotImplemented, err.Code()) - assert.EqualValues(t, "not implemented", err.Error()) - - err = MethodNotAllowed("GET", []string{"POST", "PUT"}) - assert.Error(t, err) - assert.EqualValues(t, http.StatusMethodNotAllowed, err.Code()) - assert.EqualValues(t, "method GET is not allowed, but [POST,PUT] are", err.Error()) - - err = InvalidContentType("application/saml", []string{"application/json", "application/x-yaml"}) - assert.Error(t, err) - assert.EqualValues(t, http.StatusUnsupportedMediaType, err.Code()) - assert.EqualValues(t, "unsupported media type \"application/saml\", only [application/json application/x-yaml] are allowed", err.Error()) - - err = InvalidResponseFormat("application/saml", []string{"application/json", "application/x-yaml"}) - assert.Error(t, err) - assert.EqualValues(t, http.StatusNotAcceptable, err.Code()) - assert.EqualValues(t, "unsupported media type requested, only [application/json application/x-yaml] are available", err.Error()) -} diff --git a/vendor/github.com/go-openapi/errors/auth.go b/vendor/github.com/go-openapi/errors/auth.go deleted file mode 100644 index 70eb960b1..000000000 --- a/vendor/github.com/go-openapi/errors/auth.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package errors - -// Unauthenticated returns an unauthenticated error -func Unauthenticated(scheme string) Error { - return New(401, "unauthenticated for %s", scheme) -} diff --git a/vendor/github.com/go-openapi/errors/auth_test.go b/vendor/github.com/go-openapi/errors/auth_test.go deleted file mode 100644 index eee7a5c7e..000000000 --- a/vendor/github.com/go-openapi/errors/auth_test.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package errors - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestUnauthenticated(t *testing.T) { - err := Unauthenticated("basic") - assert.EqualValues(t, 401, err.Code()) - assert.Equal(t, "unauthenticated for basic", err.Error()) -} diff --git a/vendor/github.com/go-openapi/errors/headers.go b/vendor/github.com/go-openapi/errors/headers.go deleted file mode 100644 index 66a1f4bc8..000000000 --- a/vendor/github.com/go-openapi/errors/headers.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package errors - -import ( - "fmt" - "net/http" -) - -// Validation represents a failure of a precondition -type Validation struct { - code int32 - Name string - In string - Value interface{} - message string - Values []interface{} -} - -func (e *Validation) Error() string { - return e.message -} - -// Code the error code -func (e *Validation) Code() int32 { - return e.code -} - -const ( - contentTypeFail = `unsupported media type %q, only %v are allowed` - responseFormatFail = `unsupported media type requested, only %v are available` -) - -// InvalidContentType error for an invalid content type -func InvalidContentType(value string, allowed []string) *Validation { - var values []interface{} - for _, v := range allowed { - values = append(values, v) - } - return &Validation{ - code: http.StatusUnsupportedMediaType, - Name: "Content-Type", - In: "header", - Value: value, - Values: values, - message: fmt.Sprintf(contentTypeFail, value, allowed), - } -} - -// InvalidResponseFormat error for an unacceptable response format request -func InvalidResponseFormat(value string, allowed []string) *Validation { - var values []interface{} - for _, v := range allowed { - values = append(values, v) - } - return &Validation{ - code: http.StatusNotAcceptable, - Name: "Accept", - In: "header", - Value: value, - Values: values, - message: fmt.Sprintf(responseFormatFail, allowed), - } -} - -// Validate error message name for aliased property -func (e *Validation) ValidateName(name string) *Validation { - if e.Name == "" && name != "" { - e.Name = name - e.message = name+e.message - } - return e -} diff --git a/vendor/github.com/go-openapi/errors/middleware.go b/vendor/github.com/go-openapi/errors/middleware.go deleted file mode 100644 index 6390d4636..000000000 --- a/vendor/github.com/go-openapi/errors/middleware.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package errors - -import ( - "bytes" - "fmt" - "strings" -) - -// APIVerificationFailed is an error that contains all the missing info for a mismatched section -// between the api registrations and the api spec -type APIVerificationFailed struct { - Section string - MissingSpecification []string - MissingRegistration []string -} - -// -func (v *APIVerificationFailed) Error() string { - buf := bytes.NewBuffer(nil) - - hasRegMissing := len(v.MissingRegistration) > 0 - hasSpecMissing := len(v.MissingSpecification) > 0 - - if hasRegMissing { - buf.WriteString(fmt.Sprintf("missing [%s] %s registrations", strings.Join(v.MissingRegistration, ", "), v.Section)) - } - - if hasRegMissing && hasSpecMissing { - buf.WriteString("\n") - } - - if hasSpecMissing { - buf.WriteString(fmt.Sprintf("missing from spec file [%s] %s", strings.Join(v.MissingSpecification, ", "), v.Section)) - } - - return buf.String() -} diff --git a/vendor/github.com/go-openapi/errors/middleware_test.go b/vendor/github.com/go-openapi/errors/middleware_test.go deleted file mode 100644 index feff2074d..000000000 --- a/vendor/github.com/go-openapi/errors/middleware_test.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package errors - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestAPIVerificationFailed(t *testing.T) { - err := &APIVerificationFailed{ - Section: "consumer", - MissingSpecification: []string{"application/json", "application/x-yaml"}, - MissingRegistration: []string{"text/html", "application/xml"}, - } - - expected := `missing [text/html, application/xml] consumer registrations -missing from spec file [application/json, application/x-yaml] consumer` - assert.Equal(t, expected, err.Error()) -} diff --git a/vendor/github.com/go-openapi/errors/parsing.go b/vendor/github.com/go-openapi/errors/parsing.go deleted file mode 100644 index 1bae87302..000000000 --- a/vendor/github.com/go-openapi/errors/parsing.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package errors - -import "fmt" - -// ParseError respresents a parsing error -type ParseError struct { - code int32 - Name string - In string - Value string - Reason error - message string -} - -func (e *ParseError) Error() string { - return e.message -} - -// Code returns the http status code for this error -func (e *ParseError) Code() int32 { - return e.code -} - -const ( - parseErrorTemplContent = `parsing %s %s from %q failed, because %s` - parseErrorTemplContentNoIn = `parsing %s from %q failed, because %s` -) - -// NewParseError creates a new parse error -func NewParseError(name, in, value string, reason error) *ParseError { - var msg string - if in == "" { - msg = fmt.Sprintf(parseErrorTemplContentNoIn, name, value, reason) - } else { - msg = fmt.Sprintf(parseErrorTemplContent, name, in, value, reason) - } - return &ParseError{ - code: 400, - Name: name, - In: in, - Value: value, - Reason: reason, - message: msg, - } -} diff --git a/vendor/github.com/go-openapi/errors/parsing_test.go b/vendor/github.com/go-openapi/errors/parsing_test.go deleted file mode 100644 index a51f773c9..000000000 --- a/vendor/github.com/go-openapi/errors/parsing_test.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package errors - -import ( - "errors" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestParseError(t *testing.T) { - err := NewParseError("Content-Type", "header", "application(", errors.New("unable to parse")) - assert.EqualValues(t, 400, err.Code()) - assert.Equal(t, "parsing Content-Type header from \"application(\" failed, because unable to parse", err.Error()) - - err = NewParseError("Content-Type", "", "application(", errors.New("unable to parse")) - assert.EqualValues(t, 400, err.Code()) - assert.Equal(t, "parsing Content-Type from \"application(\" failed, because unable to parse", err.Error()) -} diff --git a/vendor/github.com/go-openapi/errors/schema.go b/vendor/github.com/go-openapi/errors/schema.go deleted file mode 100644 index 14fb2c5f1..000000000 --- a/vendor/github.com/go-openapi/errors/schema.go +++ /dev/null @@ -1,562 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package errors - -import ( - "fmt" - "strings" -) - -const ( - invalidType = "%s is an invalid type name" - typeFail = "%s in %s must be of type %s" - typeFailWithData = "%s in %s must be of type %s: %q" - typeFailWithError = "%s in %s must be of type %s, because: %s" - requiredFail = "%s in %s is required" - tooLongMessage = "%s in %s should be at most %d chars long" - tooShortMessage = "%s in %s should be at least %d chars long" - patternFail = "%s in %s should match '%s'" - enumFail = "%s in %s should be one of %v" - multipleOfFail = "%s in %s should be a multiple of %v" - maxIncFail = "%s in %s should be less than or equal to %v" - maxExcFail = "%s in %s should be less than %v" - minIncFail = "%s in %s should be greater than or equal to %v" - minExcFail = "%s in %s should be greater than %v" - uniqueFail = "%s in %s shouldn't contain duplicates" - maxItemsFail = "%s in %s should have at most %d items" - minItemsFail = "%s in %s should have at least %d items" - typeFailNoIn = "%s must be of type %s" - typeFailWithDataNoIn = "%s must be of type %s: %q" - typeFailWithErrorNoIn = "%s must be of type %s, because: %s" - requiredFailNoIn = "%s is required" - tooLongMessageNoIn = "%s should be at most %d chars long" - tooShortMessageNoIn = "%s should be at least %d chars long" - patternFailNoIn = "%s should match '%s'" - enumFailNoIn = "%s should be one of %v" - multipleOfFailNoIn = "%s should be a multiple of %v" - maxIncFailNoIn = "%s should be less than or equal to %v" - maxExcFailNoIn = "%s should be less than %v" - minIncFailNoIn = "%s should be greater than or equal to %v" - minExcFailNoIn = "%s should be greater than %v" - uniqueFailNoIn = "%s shouldn't contain duplicates" - maxItemsFailNoIn = "%s should have at most %d items" - minItemsFailNoIn = "%s should have at least %d items" - noAdditionalItems = "%s in %s can't have additional items" - noAdditionalItemsNoIn = "%s can't have additional items" - tooFewProperties = "%s in %s should have at least %d properties" - tooFewPropertiesNoIn = "%s should have at least %d properties" - tooManyProperties = "%s in %s should have at most %d properties" - tooManyPropertiesNoIn = "%s should have at most %d properties" - unallowedProperty = "%s.%s in %s is a forbidden property" - unallowedPropertyNoIn = "%s.%s is a forbidden property" - failedAllPatternProps = "%s.%s in %s failed all pattern properties" - failedAllPatternPropsNoIn = "%s.%s failed all pattern properties" - multipleOfMustBePositive = "factor MultipleOf declared for %s must be positive: %v" -) - -// All code responses can be used to differentiate errors for different handling -// by the consuming program -const ( - // CompositeErrorCode remains 422 for backwards-compatibility - // and to separate it from validation errors with cause - CompositeErrorCode = 422 - // InvalidTypeCode is used for any subclass of invalid types - InvalidTypeCode = 600 + iota - RequiredFailCode - TooLongFailCode - TooShortFailCode - PatternFailCode - EnumFailCode - MultipleOfFailCode - MaxFailCode - MinFailCode - UniqueFailCode - MaxItemsFailCode - MinItemsFailCode - NoAdditionalItemsCode - TooFewPropertiesCode - TooManyPropertiesCode - UnallowedPropertyCode - FailedAllPatternPropsCode - MultipleOfMustBePositiveCode -) - -// CompositeError is an error that groups several errors together -type CompositeError struct { - Errors []error - code int32 - message string -} - -// Code for this error -func (c *CompositeError) Code() int32 { - return c.code -} - -func (c *CompositeError) Error() string { - if len(c.Errors) > 0 { - msgs := []string{c.message + ":"} - for _, e := range c.Errors { - msgs = append(msgs, e.Error()) - } - return strings.Join(msgs, "\n") - } - return c.message -} - -// CompositeValidationError an error to wrap a bunch of other errors -func CompositeValidationError(errors ...error) *CompositeError { - return &CompositeError{ - code: CompositeErrorCode, - Errors: append([]error{}, errors...), - message: "validation failure list", - } -} - -// FailedAllPatternProperties an error for when the property doesn't match a pattern -func FailedAllPatternProperties(name, in, key string) *Validation { - msg := fmt.Sprintf(failedAllPatternProps, name, key, in) - if in == "" { - msg = fmt.Sprintf(failedAllPatternPropsNoIn, name, key) - } - return &Validation{ - code: FailedAllPatternPropsCode, - Name: name, - In: in, - Value: key, - message: msg, - } -} - -// PropertyNotAllowed an error for when the property doesn't match a pattern -func PropertyNotAllowed(name, in, key string) *Validation { - msg := fmt.Sprintf(unallowedProperty, name, key, in) - if in == "" { - msg = fmt.Sprintf(unallowedPropertyNoIn, name, key) - } - return &Validation{ - code: UnallowedPropertyCode, - Name: name, - In: in, - Value: key, - message: msg, - } -} - -// TooFewProperties an error for an object with too few properties -func TooFewProperties(name, in string, n int64) *Validation { - msg := fmt.Sprintf(tooFewProperties, name, in, n) - if in == "" { - msg = fmt.Sprintf(tooFewPropertiesNoIn, name, n) - } - return &Validation{ - code: TooFewPropertiesCode, - Name: name, - In: in, - Value: n, - message: msg, - } -} - -// TooManyProperties an error for an object with too many properties -func TooManyProperties(name, in string, n int64) *Validation { - msg := fmt.Sprintf(tooManyProperties, name, in, n) - if in == "" { - msg = fmt.Sprintf(tooManyPropertiesNoIn, name, n) - } - return &Validation{ - code: TooManyPropertiesCode, - Name: name, - In: in, - Value: n, - message: msg, - } -} - -// AdditionalItemsNotAllowed an error for invalid additional items -func AdditionalItemsNotAllowed(name, in string) *Validation { - msg := fmt.Sprintf(noAdditionalItems, name, in) - if in == "" { - msg = fmt.Sprintf(noAdditionalItemsNoIn, name) - } - return &Validation{ - code: NoAdditionalItemsCode, - Name: name, - In: in, - message: msg, - } -} - -// InvalidCollectionFormat another flavor of invalid type error -func InvalidCollectionFormat(name, in, format string) *Validation { - return &Validation{ - code: InvalidTypeCode, - Name: name, - In: in, - Value: format, - message: fmt.Sprintf("the collection format %q is not supported for the %s param %q", format, in, name), - } -} - -// InvalidTypeName an error for when the type is invalid -func InvalidTypeName(typeName string) *Validation { - return &Validation{ - code: InvalidTypeCode, - Value: typeName, - message: fmt.Sprintf(invalidType, typeName), - } -} - -// InvalidType creates an error for when the type is invalid -func InvalidType(name, in, typeName string, value interface{}) *Validation { - var message string - - if in != "" { - switch value.(type) { - case string: - message = fmt.Sprintf(typeFailWithData, name, in, typeName, value) - case error: - message = fmt.Sprintf(typeFailWithError, name, in, typeName, value) - default: - message = fmt.Sprintf(typeFail, name, in, typeName) - } - } else { - switch value.(type) { - case string: - message = fmt.Sprintf(typeFailWithDataNoIn, name, typeName, value) - case error: - message = fmt.Sprintf(typeFailWithErrorNoIn, name, typeName, value) - default: - message = fmt.Sprintf(typeFailNoIn, name, typeName) - } - } - - return &Validation{ - code: InvalidTypeCode, - Name: name, - In: in, - Value: value, - message: message, - } - -} - -// DuplicateItems error for when an array contains duplicates -func DuplicateItems(name, in string) *Validation { - msg := fmt.Sprintf(uniqueFail, name, in) - if in == "" { - msg = fmt.Sprintf(uniqueFailNoIn, name) - } - return &Validation{ - code: UniqueFailCode, - Name: name, - In: in, - message: msg, - } -} - -// TooManyItems error for when an array contains too many items -func TooManyItems(name, in string, max int64) *Validation { - msg := fmt.Sprintf(maxItemsFail, name, in, max) - if in == "" { - msg = fmt.Sprintf(maxItemsFailNoIn, name, max) - } - - return &Validation{ - code: MaxItemsFailCode, - Name: name, - In: in, - message: msg, - } -} - -// TooFewItems error for when an array contains too few items -func TooFewItems(name, in string, min int64) *Validation { - msg := fmt.Sprintf(minItemsFail, name, in, min) - if in == "" { - msg = fmt.Sprintf(minItemsFailNoIn, name, min) - } - return &Validation{ - code: MinItemsFailCode, - Name: name, - In: in, - message: msg, - } -} - -// ExceedsMaximumInt error for when maxinum validation fails -func ExceedsMaximumInt(name, in string, max int64, exclusive bool) *Validation { - var message string - if in == "" { - m := maxIncFailNoIn - if exclusive { - m = maxExcFailNoIn - } - message = fmt.Sprintf(m, name, max) - } else { - m := maxIncFail - if exclusive { - m = maxExcFail - } - message = fmt.Sprintf(m, name, in, max) - } - return &Validation{ - code: MaxFailCode, - Name: name, - In: in, - Value: max, - message: message, - } -} - -// ExceedsMaximumUint error for when maxinum validation fails -func ExceedsMaximumUint(name, in string, max uint64, exclusive bool) *Validation { - var message string - if in == "" { - m := maxIncFailNoIn - if exclusive { - m = maxExcFailNoIn - } - message = fmt.Sprintf(m, name, max) - } else { - m := maxIncFail - if exclusive { - m = maxExcFail - } - message = fmt.Sprintf(m, name, in, max) - } - return &Validation{ - code: MaxFailCode, - Name: name, - In: in, - Value: max, - message: message, - } -} - -// ExceedsMaximum error for when maxinum validation fails -func ExceedsMaximum(name, in string, max float64, exclusive bool) *Validation { - var message string - if in == "" { - m := maxIncFailNoIn - if exclusive { - m = maxExcFailNoIn - } - message = fmt.Sprintf(m, name, max) - } else { - m := maxIncFail - if exclusive { - m = maxExcFail - } - message = fmt.Sprintf(m, name, in, max) - } - return &Validation{ - code: MaxFailCode, - Name: name, - In: in, - Value: max, - message: message, - } -} - -// ExceedsMinimumInt error for when maxinum validation fails -func ExceedsMinimumInt(name, in string, min int64, exclusive bool) *Validation { - var message string - if in == "" { - m := minIncFailNoIn - if exclusive { - m = minExcFailNoIn - } - message = fmt.Sprintf(m, name, min) - } else { - m := minIncFail - if exclusive { - m = minExcFail - } - message = fmt.Sprintf(m, name, in, min) - } - return &Validation{ - code: MinFailCode, - Name: name, - In: in, - Value: min, - message: message, - } -} - -// ExceedsMinimumUint error for when maxinum validation fails -func ExceedsMinimumUint(name, in string, min uint64, exclusive bool) *Validation { - var message string - if in == "" { - m := minIncFailNoIn - if exclusive { - m = minExcFailNoIn - } - message = fmt.Sprintf(m, name, min) - } else { - m := minIncFail - if exclusive { - m = minExcFail - } - message = fmt.Sprintf(m, name, in, min) - } - return &Validation{ - code: MinFailCode, - Name: name, - In: in, - Value: min, - message: message, - } -} - -// ExceedsMinimum error for when maxinum validation fails -func ExceedsMinimum(name, in string, min float64, exclusive bool) *Validation { - var message string - if in == "" { - m := minIncFailNoIn - if exclusive { - m = minExcFailNoIn - } - message = fmt.Sprintf(m, name, min) - } else { - m := minIncFail - if exclusive { - m = minExcFail - } - message = fmt.Sprintf(m, name, in, min) - } - return &Validation{ - code: MinFailCode, - Name: name, - In: in, - Value: min, - message: message, - } -} - -// NotMultipleOf error for when multiple of validation fails -func NotMultipleOf(name, in string, multiple interface{}) *Validation { - var msg string - if in == "" { - msg = fmt.Sprintf(multipleOfFailNoIn, name, multiple) - } else { - msg = fmt.Sprintf(multipleOfFail, name, in, multiple) - } - return &Validation{ - code: MultipleOfFailCode, - Name: name, - In: in, - Value: multiple, - message: msg, - } -} - -// EnumFail error for when an enum validation fails -func EnumFail(name, in string, value interface{}, values []interface{}) *Validation { - var msg string - if in == "" { - msg = fmt.Sprintf(enumFailNoIn, name, values) - } else { - msg = fmt.Sprintf(enumFail, name, in, values) - } - - return &Validation{ - code: EnumFailCode, - Name: name, - In: in, - Value: value, - Values: values, - message: msg, - } -} - -// Required error for when a value is missing -func Required(name, in string) *Validation { - var msg string - if in == "" { - msg = fmt.Sprintf(requiredFailNoIn, name) - } else { - msg = fmt.Sprintf(requiredFail, name, in) - } - return &Validation{ - code: RequiredFailCode, - Name: name, - In: in, - message: msg, - } -} - -// TooLong error for when a string is too long -func TooLong(name, in string, max int64) *Validation { - var msg string - if in == "" { - msg = fmt.Sprintf(tooLongMessageNoIn, name, max) - } else { - msg = fmt.Sprintf(tooLongMessage, name, in, max) - } - return &Validation{ - code: TooLongFailCode, - Name: name, - In: in, - message: msg, - } -} - -// TooShort error for when a string is too short -func TooShort(name, in string, min int64) *Validation { - var msg string - if in == "" { - msg = fmt.Sprintf(tooShortMessageNoIn, name, min) - } else { - msg = fmt.Sprintf(tooShortMessage, name, in, min) - } - - return &Validation{ - code: TooShortFailCode, - Name: name, - In: in, - message: msg, - } -} - -// FailedPattern error for when a string fails a regex pattern match -// the pattern that is returned is the ECMA syntax version of the pattern not the golang version. -func FailedPattern(name, in, pattern string) *Validation { - var msg string - if in == "" { - msg = fmt.Sprintf(patternFailNoIn, name, pattern) - } else { - msg = fmt.Sprintf(patternFail, name, in, pattern) - } - - return &Validation{ - code: PatternFailCode, - Name: name, - In: in, - message: msg, - } -} - -// MultipleOfMustBePositive error for when a -// multipleOf factor is negative -func MultipleOfMustBePositive(name, in string, factor interface{}) *Validation { - return &Validation{ - code: MultipleOfMustBePositiveCode, - Name: name, - In: in, - Value: factor, - message: fmt.Sprintf(multipleOfMustBePositive, name, factor), - } -} diff --git a/vendor/github.com/go-openapi/errors/schema_test.go b/vendor/github.com/go-openapi/errors/schema_test.go deleted file mode 100644 index 53093f0c0..000000000 --- a/vendor/github.com/go-openapi/errors/schema_test.go +++ /dev/null @@ -1,364 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package errors - -import ( - "errors" - "fmt" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestSchemaErrors(t *testing.T) { - err := InvalidType("confirmed", "query", "boolean", nil) - assert.Error(t, err) - assert.EqualValues(t, InvalidTypeCode, err.Code()) - assert.Equal(t, "confirmed in query must be of type boolean", err.Error()) - - err = InvalidType("confirmed", "", "boolean", nil) - assert.Error(t, err) - assert.EqualValues(t, InvalidTypeCode, err.Code()) - assert.Equal(t, "confirmed must be of type boolean", err.Error()) - - err = InvalidType("confirmed", "query", "boolean", "hello") - assert.Error(t, err) - assert.EqualValues(t, InvalidTypeCode, err.Code()) - assert.Equal(t, "confirmed in query must be of type boolean: \"hello\"", err.Error()) - - err = InvalidType("confirmed", "query", "boolean", errors.New("hello")) - assert.Error(t, err) - assert.EqualValues(t, InvalidTypeCode, err.Code()) - assert.Equal(t, "confirmed in query must be of type boolean, because: hello", err.Error()) - - err = InvalidType("confirmed", "", "boolean", "hello") - assert.Error(t, err) - assert.EqualValues(t, InvalidTypeCode, err.Code()) - assert.Equal(t, "confirmed must be of type boolean: \"hello\"", err.Error()) - - err = InvalidType("confirmed", "", "boolean", errors.New("hello")) - assert.Error(t, err) - assert.EqualValues(t, InvalidTypeCode, err.Code()) - assert.Equal(t, "confirmed must be of type boolean, because: hello", err.Error()) - - err = DuplicateItems("uniques", "query") - assert.Error(t, err) - assert.EqualValues(t, UniqueFailCode, err.Code()) - assert.Equal(t, "uniques in query shouldn't contain duplicates", err.Error()) - - err = DuplicateItems("uniques", "") - assert.Error(t, err) - assert.EqualValues(t, UniqueFailCode, err.Code()) - assert.Equal(t, "uniques shouldn't contain duplicates", err.Error()) - - err = TooManyItems("something", "query", 5) - assert.Error(t, err) - assert.EqualValues(t, MaxItemsFailCode, err.Code()) - assert.Equal(t, "something in query should have at most 5 items", err.Error()) - - err = TooManyItems("something", "", 5) - assert.Error(t, err) - assert.EqualValues(t, MaxItemsFailCode, err.Code()) - assert.Equal(t, "something should have at most 5 items", err.Error()) - - err = TooFewItems("something", "", 5) - assert.Error(t, err) - assert.EqualValues(t, MinItemsFailCode, err.Code()) - assert.Equal(t, "something should have at least 5 items", err.Error()) - - err = ExceedsMaximumInt("something", "query", 5, false) - assert.Error(t, err) - assert.EqualValues(t, MaxFailCode, err.Code()) - assert.Equal(t, "something in query should be less than or equal to 5", err.Error()) - - err = ExceedsMaximumInt("something", "", 5, false) - assert.Error(t, err) - assert.EqualValues(t, MaxFailCode, err.Code()) - assert.Equal(t, "something should be less than or equal to 5", err.Error()) - - err = ExceedsMaximumInt("something", "query", 5, true) - assert.Error(t, err) - assert.EqualValues(t, MaxFailCode, err.Code()) - assert.Equal(t, "something in query should be less than 5", err.Error()) - - err = ExceedsMaximumInt("something", "", 5, true) - assert.Error(t, err) - assert.EqualValues(t, MaxFailCode, err.Code()) - assert.Equal(t, "something should be less than 5", err.Error()) - - err = ExceedsMaximumUint("something", "query", 5, false) - assert.Error(t, err) - assert.EqualValues(t, MaxFailCode, err.Code()) - assert.Equal(t, "something in query should be less than or equal to 5", err.Error()) - - err = ExceedsMaximumUint("something", "", 5, false) - assert.Error(t, err) - assert.EqualValues(t, MaxFailCode, err.Code()) - assert.Equal(t, "something should be less than or equal to 5", err.Error()) - - err = ExceedsMaximumUint("something", "query", 5, true) - assert.Error(t, err) - assert.EqualValues(t, MaxFailCode, err.Code()) - assert.Equal(t, "something in query should be less than 5", err.Error()) - - err = ExceedsMaximumUint("something", "", 5, true) - assert.Error(t, err) - assert.EqualValues(t, MaxFailCode, err.Code()) - assert.Equal(t, "something should be less than 5", err.Error()) - - err = ExceedsMaximum("something", "query", 5, false) - assert.Error(t, err) - assert.EqualValues(t, MaxFailCode, err.Code()) - assert.Equal(t, "something in query should be less than or equal to 5", err.Error()) - - err = ExceedsMaximum("something", "", 5, false) - assert.Error(t, err) - assert.EqualValues(t, MaxFailCode, err.Code()) - assert.Equal(t, "something should be less than or equal to 5", err.Error()) - - err = ExceedsMaximum("something", "query", 5, true) - assert.Error(t, err) - assert.EqualValues(t, MaxFailCode, err.Code()) - assert.Equal(t, "something in query should be less than 5", err.Error()) - - err = ExceedsMaximum("something", "", 5, true) - assert.Error(t, err) - assert.EqualValues(t, MaxFailCode, err.Code()) - assert.Equal(t, "something should be less than 5", err.Error()) - - err = ExceedsMinimumInt("something", "query", 5, false) - assert.Error(t, err) - assert.EqualValues(t, MinFailCode, err.Code()) - assert.Equal(t, "something in query should be greater than or equal to 5", err.Error()) - - err = ExceedsMinimumInt("something", "", 5, false) - assert.Error(t, err) - assert.EqualValues(t, MinFailCode, err.Code()) - assert.Equal(t, "something should be greater than or equal to 5", err.Error()) - - err = ExceedsMinimumInt("something", "query", 5, true) - assert.Error(t, err) - assert.EqualValues(t, MinFailCode, err.Code()) - assert.Equal(t, "something in query should be greater than 5", err.Error()) - - err = ExceedsMinimumInt("something", "", 5, true) - assert.Error(t, err) - assert.EqualValues(t, MinFailCode, err.Code()) - assert.Equal(t, "something should be greater than 5", err.Error()) - - err = ExceedsMinimumUint("something", "query", 5, false) - assert.Error(t, err) - assert.EqualValues(t, MinFailCode, err.Code()) - assert.Equal(t, "something in query should be greater than or equal to 5", err.Error()) - - err = ExceedsMinimumUint("something", "", 5, false) - assert.Error(t, err) - assert.EqualValues(t, MinFailCode, err.Code()) - assert.Equal(t, "something should be greater than or equal to 5", err.Error()) - - err = ExceedsMinimumUint("something", "query", 5, true) - assert.Error(t, err) - assert.EqualValues(t, MinFailCode, err.Code()) - assert.Equal(t, "something in query should be greater than 5", err.Error()) - - err = ExceedsMinimumUint("something", "", 5, true) - assert.Error(t, err) - assert.EqualValues(t, MinFailCode, err.Code()) - assert.Equal(t, "something should be greater than 5", err.Error()) - - err = ExceedsMinimum("something", "query", 5, false) - assert.Error(t, err) - assert.EqualValues(t, MinFailCode, err.Code()) - assert.Equal(t, "something in query should be greater than or equal to 5", err.Error()) - - err = ExceedsMinimum("something", "", 5, false) - assert.Error(t, err) - assert.EqualValues(t, MinFailCode, err.Code()) - assert.Equal(t, "something should be greater than or equal to 5", err.Error()) - - err = ExceedsMinimum("something", "query", 5, true) - assert.Error(t, err) - assert.EqualValues(t, MinFailCode, err.Code()) - assert.Equal(t, "something in query should be greater than 5", err.Error()) - - err = ExceedsMinimum("something", "", 5, true) - assert.Error(t, err) - assert.EqualValues(t, MinFailCode, err.Code()) - assert.Equal(t, "something should be greater than 5", err.Error()) - - err = NotMultipleOf("something", "query", 5) - assert.Error(t, err) - assert.EqualValues(t, MultipleOfFailCode, err.Code()) - assert.Equal(t, "something in query should be a multiple of 5", err.Error()) - - err = NotMultipleOf("something", "query", float64(5)) - assert.Error(t, err) - assert.EqualValues(t, MultipleOfFailCode, err.Code()) - assert.Equal(t, "something in query should be a multiple of 5", err.Error()) - - err = NotMultipleOf("something", "query", uint64(5)) - assert.Error(t, err) - assert.EqualValues(t, MultipleOfFailCode, err.Code()) - assert.Equal(t, "something in query should be a multiple of 5", err.Error()) - - err = NotMultipleOf("something", "", 5) - assert.Error(t, err) - assert.EqualValues(t, MultipleOfFailCode, err.Code()) - assert.Equal(t, "something should be a multiple of 5", err.Error()) - - err = EnumFail("something", "query", "yada", []interface{}{"hello", "world"}) - assert.Error(t, err) - assert.EqualValues(t, EnumFailCode, err.Code()) - assert.Equal(t, "something in query should be one of [hello world]", err.Error()) - - err = EnumFail("something", "", "yada", []interface{}{"hello", "world"}) - assert.Error(t, err) - assert.EqualValues(t, EnumFailCode, err.Code()) - assert.Equal(t, "something should be one of [hello world]", err.Error()) - - err = Required("something", "query") - assert.Error(t, err) - assert.EqualValues(t, RequiredFailCode, err.Code()) - assert.Equal(t, "something in query is required", err.Error()) - - err = Required("something", "") - assert.Error(t, err) - assert.EqualValues(t, RequiredFailCode, err.Code()) - assert.Equal(t, "something is required", err.Error()) - - err = TooLong("something", "query", 5) - assert.Error(t, err) - assert.EqualValues(t, TooLongFailCode, err.Code()) - assert.Equal(t, "something in query should be at most 5 chars long", err.Error()) - - err = TooLong("something", "", 5) - assert.Error(t, err) - assert.EqualValues(t, TooLongFailCode, err.Code()) - assert.Equal(t, "something should be at most 5 chars long", err.Error()) - - err = TooShort("something", "query", 5) - assert.Error(t, err) - assert.EqualValues(t, TooShortFailCode, err.Code()) - assert.Equal(t, "something in query should be at least 5 chars long", err.Error()) - - err = TooShort("something", "", 5) - assert.Error(t, err) - assert.EqualValues(t, TooShortFailCode, err.Code()) - assert.Equal(t, "something should be at least 5 chars long", err.Error()) - - err = FailedPattern("something", "query", "\\d+") - assert.Error(t, err) - assert.EqualValues(t, PatternFailCode, err.Code()) - assert.Equal(t, "something in query should match '\\d+'", err.Error()) - - err = FailedPattern("something", "", "\\d+") - assert.Error(t, err) - assert.EqualValues(t, PatternFailCode, err.Code()) - assert.Equal(t, "something should match '\\d+'", err.Error()) - - err = InvalidTypeName("something") - assert.Error(t, err) - assert.EqualValues(t, InvalidTypeCode, err.Code()) - assert.Equal(t, "something is an invalid type name", err.Error()) - - err = AdditionalItemsNotAllowed("something", "query") - assert.Error(t, err) - assert.EqualValues(t, NoAdditionalItemsCode, err.Code()) - assert.Equal(t, "something in query can't have additional items", err.Error()) - - err = AdditionalItemsNotAllowed("something", "") - assert.Error(t, err) - assert.EqualValues(t, NoAdditionalItemsCode, err.Code()) - assert.Equal(t, "something can't have additional items", err.Error()) - - err = InvalidCollectionFormat("something", "query", "yada") - assert.Error(t, err) - assert.EqualValues(t, InvalidTypeCode, err.Code()) - assert.Equal(t, "the collection format \"yada\" is not supported for the query param \"something\"", err.Error()) - - err2 := CompositeValidationError() - assert.Error(t, err2) - assert.EqualValues(t, CompositeErrorCode, err2.Code()) - assert.Equal(t, "validation failure list", err2.Error()) - - err2 = CompositeValidationError(fmt.Errorf("First error"), fmt.Errorf("Second error")) - assert.Error(t, err2) - assert.EqualValues(t, CompositeErrorCode, err2.Code()) - assert.Equal(t, "validation failure list:\nFirst error\nSecond error", err2.Error()) - - //func MultipleOfMustBePositive(name, in string, factor interface{}) *Validation { - err = MultipleOfMustBePositive("path", "body", float64(-10)) - assert.Error(t, err) - assert.EqualValues(t, MultipleOfMustBePositiveCode, err.Code()) - assert.Equal(t, `factor MultipleOf declared for path must be positive: -10`, err.Error()) - - err = MultipleOfMustBePositive("path", "body", int64(-10)) - assert.Error(t, err) - assert.EqualValues(t, MultipleOfMustBePositiveCode, err.Code()) - assert.Equal(t, `factor MultipleOf declared for path must be positive: -10`, err.Error()) - - // func PropertyNotAllowed(name, in, key string) *Validation { - err = PropertyNotAllowed("path", "body", "key") - assert.Error(t, err) - assert.EqualValues(t, UnallowedPropertyCode, err.Code()) - //unallowedProperty = "%s.%s in %s is a forbidden property" - assert.Equal(t, "path.key in body is a forbidden property", err.Error()) - - err = PropertyNotAllowed("path", "", "key") - assert.Error(t, err) - assert.EqualValues(t, UnallowedPropertyCode, err.Code()) - //unallowedPropertyNoIn = "%s.%s is a forbidden property" - assert.Equal(t, "path.key is a forbidden property", err.Error()) - - //func TooManyProperties(name, in string, n int64) *Validation { - err = TooManyProperties("path", "body", 10) - assert.Error(t, err) - assert.EqualValues(t, TooManyPropertiesCode, err.Code()) - //tooManyProperties = "%s in %s should have at most %d properties" - assert.Equal(t, "path in body should have at most 10 properties", err.Error()) - - err = TooManyProperties("path", "", 10) - assert.Error(t, err) - assert.EqualValues(t, TooManyPropertiesCode, err.Code()) - //tooManyPropertiesNoIn = "%s should have at most %d properties" - assert.Equal(t, "path should have at most 10 properties", err.Error()) - - err = TooFewProperties("path", "body", 10) - // func TooFewProperties(name, in string, n int64) *Validation { - assert.Error(t, err) - assert.EqualValues(t, TooFewPropertiesCode, err.Code()) - //tooFewProperties = "%s in %s should have at least %d properties" - assert.Equal(t, "path in body should have at least 10 properties", err.Error()) - - err = TooFewProperties("path", "", 10) - // func TooFewProperties(name, in string, n int64) *Validation { - assert.Error(t, err) - assert.EqualValues(t, TooFewPropertiesCode, err.Code()) - //tooFewPropertiesNoIn = "%s should have at least %d properties" - assert.Equal(t, "path should have at least 10 properties", err.Error()) - - //func FailedAllPatternProperties(name, in, key string) *Validation { - err = FailedAllPatternProperties("path", "body", "key") - assert.Error(t, err) - assert.EqualValues(t, FailedAllPatternPropsCode, err.Code()) - //failedAllPatternProps = "%s.%s in %s failed all pattern properties" - assert.Equal(t, "path.key in body failed all pattern properties", err.Error()) - - err = FailedAllPatternProperties("path", "", "key") - assert.Error(t, err) - assert.EqualValues(t, FailedAllPatternPropsCode, err.Code()) - //failedAllPatternPropsNoIn = "%s.%s failed all pattern properties" - assert.Equal(t, "path.key failed all pattern properties", err.Error()) -} diff --git a/vendor/github.com/go-openapi/jsonpointer/.editorconfig b/vendor/github.com/go-openapi/jsonpointer/.editorconfig deleted file mode 100644 index 3152da69a..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/.editorconfig +++ /dev/null @@ -1,26 +0,0 @@ -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -end_of_line = lf -insert_final_newline = true -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true - -# Set default charset -[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] -charset = utf-8 - -# Tab indentation (no size specified) -[*.go] -indent_style = tab - -[*.md] -trim_trailing_whitespace = false - -# Matches the exact files either package.json or .travis.yml -[{package.json,.travis.yml}] -indent_style = space -indent_size = 2 diff --git a/vendor/github.com/go-openapi/jsonpointer/.github/CONTRIBUTING.md b/vendor/github.com/go-openapi/jsonpointer/.github/CONTRIBUTING.md deleted file mode 100644 index 7dea4240d..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/.github/CONTRIBUTING.md +++ /dev/null @@ -1,117 +0,0 @@ -## Contribution Guidelines - -### Pull requests are always welcome - -We are always thrilled to receive pull requests, and do our best to -process them as fast as possible. Not sure if that typo is worth a pull -request? Do it! We will appreciate it. - -If your pull request is not accepted on the first try, don't be -discouraged! If there's a problem with the implementation, hopefully you -received feedback on what to improve. - -We're trying very hard to keep go-swagger lean and focused. We don't want it -to do everything for everybody. This means that we might decide against -incorporating a new feature. However, there might be a way to implement -that feature *on top of* go-swagger. - - -### Conventions - -Fork the repo and make changes on your fork in a feature branch: - -- If it's a bugfix branch, name it XXX-something where XXX is the number of the - issue -- If it's a feature branch, create an enhancement issue to announce your - intentions, and name it XXX-something where XXX is the number of the issue. - -Submit unit tests for your changes. Go has a great test framework built in; use -it! Take a look at existing tests for inspiration. Run the full test suite on -your branch before submitting a pull request. - -Update the documentation when creating or modifying features. Test -your documentation changes for clarity, concision, and correctness, as -well as a clean documentation build. See ``docs/README.md`` for more -information on building the docs and how docs get released. - -Write clean code. Universally formatted code promotes ease of writing, reading, -and maintenance. Always run `gofmt -s -w file.go` on each changed file before -committing your changes. Most editors have plugins that do this automatically. - -Pull requests descriptions should be as clear as possible and include a -reference to all the issues that they address. - -Pull requests must not contain commits from other users or branches. - -Commit messages must start with a capitalized and short summary (max. 50 -chars) written in the imperative, followed by an optional, more detailed -explanatory text which is separated from the summary by an empty line. - -Code review comments may be added to your pull request. Discuss, then make the -suggested modifications and push additional commits to your feature branch. Be -sure to post a comment after pushing. The new commits will show up in the pull -request automatically, but the reviewers will not be notified unless you -comment. - -Before the pull request is merged, make sure that you squash your commits into -logical units of work using `git rebase -i` and `git push -f`. After every -commit the test suite should be passing. Include documentation changes in the -same commit so that a revert would remove all traces of the feature or fix. - -Commits that fix or close an issue should include a reference like `Closes #XXX` -or `Fixes #XXX`, which will automatically close the issue when merged. - -### Sign your work - -The sign-off is a simple line at the end of the explanation for the -patch, which certifies that you wrote it or otherwise have the right to -pass it on as an open-source patch. The rules are pretty simple: if you -can certify the below (from -[developercertificate.org](http://developercertificate.org/)): - -``` -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` - -then you just add a line to every git commit message: - - Signed-off-by: Joe Smith - -using your real name (sorry, no pseudonyms or anonymous contributions.) - -You can add the sign off when creating the git commit via `git commit -s`. diff --git a/vendor/github.com/go-openapi/jsonpointer/.gitignore b/vendor/github.com/go-openapi/jsonpointer/.gitignore deleted file mode 100644 index 769c24400..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/.gitignore +++ /dev/null @@ -1 +0,0 @@ -secrets.yml diff --git a/vendor/github.com/go-openapi/jsonpointer/.travis.yml b/vendor/github.com/go-openapi/jsonpointer/.travis.yml deleted file mode 100644 index 2ee3ab975..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -language: go -go: -- "1.8" -- "1.9" -- "1.10" -install: -- go get -u github.com/stretchr/testify/assert -- go get -u github.com/go-openapi/swag -script: -- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./... -after_success: -- bash <(curl -s https://codecov.io/bash) -notifications: - slack: - secure: a5VgoiwB1G/AZqzmephPZIhEB9avMlsWSlVnM1dSAtYAwdrQHGTQxAmpOxYIoSPDhWNN5bfZmjd29++UlTwLcHSR+e0kJhH6IfDlsHj/HplNCJ9tyI0zYc7XchtdKgeMxMzBKCzgwFXGSbQGydXTliDNBo0HOzmY3cou/daMFTP60K+offcjS+3LRAYb1EroSRXZqrk1nuF/xDL3792DZUdPMiFR/L/Df6y74D6/QP4sTkTDFQitz4Wy/7jbsfj8dG6qK2zivgV6/l+w4OVjFkxVpPXogDWY10vVXNVynqxfJ7to2d1I9lNCHE2ilBCkWMIPdyJF7hjF8pKW+82yP4EzRh0vu8Xn0HT5MZpQxdRY/YMxNrWaG7SxsoEaO4q5uhgdzAqLYY3TRa7MjIK+7Ur+aqOeTXn6OKwVi0CjvZ6mIU3WUKSwiwkFZMbjRAkSb5CYwMEfGFO/z964xz83qGt6WAtBXNotqCQpTIiKtDHQeLOMfksHImCg6JLhQcWBVxamVgu0G3Pdh8Y6DyPnxraXY95+QDavbjqv7TeYT9T/FNnrkXaTTK0s4iWE5H4ACU0Qvz0wUYgfQrZv0/Hp7V17+rabUwnzYySHCy9SWX/7OV9Cfh31iMp9ZIffr76xmmThtOEqs8TrTtU6BWI3rWwvA9cXQipZTVtL0oswrGw= diff --git a/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/jsonpointer/LICENSE b/vendor/github.com/go-openapi/jsonpointer/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/go-openapi/jsonpointer/README.md b/vendor/github.com/go-openapi/jsonpointer/README.md deleted file mode 100644 index 813788aff..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# gojsonpointer [![Build Status](https://travis-ci.org/go-openapi/jsonpointer.svg?branch=master)](https://travis-ci.org/go-openapi/jsonpointer) [![codecov](https://codecov.io/gh/go-openapi/jsonpointer/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonpointer) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/jsonpointer/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/jsonpointer?status.svg)](http://godoc.org/github.com/go-openapi/jsonpointer) -An implementation of JSON Pointer - Go language - -## Status -Completed YES - -Tested YES - -## References -http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 - -### Note -The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, the reference token MUST contain either...' is not implemented. diff --git a/vendor/github.com/go-openapi/jsonpointer/pointer.go b/vendor/github.com/go-openapi/jsonpointer/pointer.go deleted file mode 100644 index fe2d6ee57..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/pointer.go +++ /dev/null @@ -1,390 +0,0 @@ -// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) -// -// 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. - -// author sigu-399 -// author-github https://github.com/sigu-399 -// author-mail sigu.399@gmail.com -// -// repository-name jsonpointer -// repository-desc An implementation of JSON Pointer - Go language -// -// description Main and unique file. -// -// created 25-02-2013 - -package jsonpointer - -import ( - "errors" - "fmt" - "reflect" - "strconv" - "strings" - - "github.com/go-openapi/swag" -) - -const ( - emptyPointer = `` - pointerSeparator = `/` - - invalidStart = `JSON pointer must be empty or start with a "` + pointerSeparator -) - -var jsonPointableType = reflect.TypeOf(new(JSONPointable)).Elem() -var jsonSetableType = reflect.TypeOf(new(JSONSetable)).Elem() - -// JSONPointable is an interface for structs to implement when they need to customize the -// json pointer process -type JSONPointable interface { - JSONLookup(string) (interface{}, error) -} - -// JSONSetable is an interface for structs to implement when they need to customize the -// json pointer process -type JSONSetable interface { - JSONSet(string, interface{}) error -} - -// New creates a new json pointer for the given string -func New(jsonPointerString string) (Pointer, error) { - - var p Pointer - err := p.parse(jsonPointerString) - return p, err - -} - -// Pointer the json pointer reprsentation -type Pointer struct { - referenceTokens []string -} - -// "Constructor", parses the given string JSON pointer -func (p *Pointer) parse(jsonPointerString string) error { - - var err error - - if jsonPointerString != emptyPointer { - if !strings.HasPrefix(jsonPointerString, pointerSeparator) { - err = errors.New(invalidStart) - } else { - referenceTokens := strings.Split(jsonPointerString, pointerSeparator) - for _, referenceToken := range referenceTokens[1:] { - p.referenceTokens = append(p.referenceTokens, referenceToken) - } - } - } - - return err -} - -// Get uses the pointer to retrieve a value from a JSON document -func (p *Pointer) Get(document interface{}) (interface{}, reflect.Kind, error) { - return p.get(document, swag.DefaultJSONNameProvider) -} - -// Set uses the pointer to set a value from a JSON document -func (p *Pointer) Set(document interface{}, value interface{}) (interface{}, error) { - return document, p.set(document, value, swag.DefaultJSONNameProvider) -} - -// GetForToken gets a value for a json pointer token 1 level deep -func GetForToken(document interface{}, decodedToken string) (interface{}, reflect.Kind, error) { - return getSingleImpl(document, decodedToken, swag.DefaultJSONNameProvider) -} - -// SetForToken gets a value for a json pointer token 1 level deep -func SetForToken(document interface{}, decodedToken string, value interface{}) (interface{}, error) { - return document, setSingleImpl(document, value, decodedToken, swag.DefaultJSONNameProvider) -} - -func getSingleImpl(node interface{}, decodedToken string, nameProvider *swag.NameProvider) (interface{}, reflect.Kind, error) { - rValue := reflect.Indirect(reflect.ValueOf(node)) - kind := rValue.Kind() - - switch kind { - - case reflect.Struct: - if rValue.Type().Implements(jsonPointableType) { - r, err := node.(JSONPointable).JSONLookup(decodedToken) - if err != nil { - return nil, kind, err - } - return r, kind, nil - } - nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) - if !ok { - return nil, kind, fmt.Errorf("object has no field %q", decodedToken) - } - fld := rValue.FieldByName(nm) - return fld.Interface(), kind, nil - - case reflect.Map: - kv := reflect.ValueOf(decodedToken) - mv := rValue.MapIndex(kv) - - if mv.IsValid() && !swag.IsZero(mv) { - return mv.Interface(), kind, nil - } - return nil, kind, fmt.Errorf("object has no key %q", decodedToken) - - case reflect.Slice: - tokenIndex, err := strconv.Atoi(decodedToken) - if err != nil { - return nil, kind, err - } - sLength := rValue.Len() - if tokenIndex < 0 || tokenIndex >= sLength { - return nil, kind, fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength-1, tokenIndex) - } - - elem := rValue.Index(tokenIndex) - return elem.Interface(), kind, nil - - default: - return nil, kind, fmt.Errorf("invalid token reference %q", decodedToken) - } - -} - -func setSingleImpl(node, data interface{}, decodedToken string, nameProvider *swag.NameProvider) error { - rValue := reflect.Indirect(reflect.ValueOf(node)) - switch rValue.Kind() { - - case reflect.Struct: - if ns, ok := node.(JSONSetable); ok { // pointer impl - return ns.JSONSet(decodedToken, data) - } - - if rValue.Type().Implements(jsonSetableType) { - return node.(JSONSetable).JSONSet(decodedToken, data) - } - - nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) - if !ok { - return fmt.Errorf("object has no field %q", decodedToken) - } - fld := rValue.FieldByName(nm) - if fld.IsValid() { - fld.Set(reflect.ValueOf(data)) - } - return nil - - case reflect.Map: - kv := reflect.ValueOf(decodedToken) - rValue.SetMapIndex(kv, reflect.ValueOf(data)) - return nil - - case reflect.Slice: - tokenIndex, err := strconv.Atoi(decodedToken) - if err != nil { - return err - } - sLength := rValue.Len() - if tokenIndex < 0 || tokenIndex >= sLength { - return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex) - } - - elem := rValue.Index(tokenIndex) - if !elem.CanSet() { - return fmt.Errorf("can't set slice index %s to %v", decodedToken, data) - } - elem.Set(reflect.ValueOf(data)) - return nil - - default: - return fmt.Errorf("invalid token reference %q", decodedToken) - } - -} - -func (p *Pointer) get(node interface{}, nameProvider *swag.NameProvider) (interface{}, reflect.Kind, error) { - - if nameProvider == nil { - nameProvider = swag.DefaultJSONNameProvider - } - - kind := reflect.Invalid - - // Full document when empty - if len(p.referenceTokens) == 0 { - return node, kind, nil - } - - for _, token := range p.referenceTokens { - - decodedToken := Unescape(token) - - r, knd, err := getSingleImpl(node, decodedToken, nameProvider) - if err != nil { - return nil, knd, err - } - node, kind = r, knd - - } - - rValue := reflect.ValueOf(node) - kind = rValue.Kind() - - return node, kind, nil -} - -func (p *Pointer) set(node, data interface{}, nameProvider *swag.NameProvider) error { - knd := reflect.ValueOf(node).Kind() - - if knd != reflect.Ptr && knd != reflect.Struct && knd != reflect.Map && knd != reflect.Slice && knd != reflect.Array { - return fmt.Errorf("only structs, pointers, maps and slices are supported for setting values") - } - - if nameProvider == nil { - nameProvider = swag.DefaultJSONNameProvider - } - - // Full document when empty - if len(p.referenceTokens) == 0 { - return nil - } - - lastI := len(p.referenceTokens) - 1 - for i, token := range p.referenceTokens { - isLastToken := i == lastI - decodedToken := Unescape(token) - - if isLastToken { - - return setSingleImpl(node, data, decodedToken, nameProvider) - } - - rValue := reflect.Indirect(reflect.ValueOf(node)) - kind := rValue.Kind() - - switch kind { - - case reflect.Struct: - if rValue.Type().Implements(jsonPointableType) { - r, err := node.(JSONPointable).JSONLookup(decodedToken) - if err != nil { - return err - } - fld := reflect.ValueOf(r) - if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { - node = fld.Addr().Interface() - continue - } - node = r - continue - } - nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) - if !ok { - return fmt.Errorf("object has no field %q", decodedToken) - } - fld := rValue.FieldByName(nm) - if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { - node = fld.Addr().Interface() - continue - } - node = fld.Interface() - - case reflect.Map: - kv := reflect.ValueOf(decodedToken) - mv := rValue.MapIndex(kv) - - if !mv.IsValid() { - return fmt.Errorf("object has no key %q", decodedToken) - } - if mv.CanAddr() && mv.Kind() != reflect.Interface && mv.Kind() != reflect.Map && mv.Kind() != reflect.Slice && mv.Kind() != reflect.Ptr { - node = mv.Addr().Interface() - continue - } - node = mv.Interface() - - case reflect.Slice: - tokenIndex, err := strconv.Atoi(decodedToken) - if err != nil { - return err - } - sLength := rValue.Len() - if tokenIndex < 0 || tokenIndex >= sLength { - return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex) - } - - elem := rValue.Index(tokenIndex) - if elem.CanAddr() && elem.Kind() != reflect.Interface && elem.Kind() != reflect.Map && elem.Kind() != reflect.Slice && elem.Kind() != reflect.Ptr { - node = elem.Addr().Interface() - continue - } - node = elem.Interface() - - default: - return fmt.Errorf("invalid token reference %q", decodedToken) - } - - } - - return nil -} - -// DecodedTokens returns the decoded tokens -func (p *Pointer) DecodedTokens() []string { - result := make([]string, 0, len(p.referenceTokens)) - for _, t := range p.referenceTokens { - result = append(result, Unescape(t)) - } - return result -} - -// IsEmpty returns true if this is an empty json pointer -// this indicates that it points to the root document -func (p *Pointer) IsEmpty() bool { - return len(p.referenceTokens) == 0 -} - -// Pointer to string representation function -func (p *Pointer) String() string { - - if len(p.referenceTokens) == 0 { - return emptyPointer - } - - pointerString := pointerSeparator + strings.Join(p.referenceTokens, pointerSeparator) - - return pointerString -} - -// Specific JSON pointer encoding here -// ~0 => ~ -// ~1 => / -// ... and vice versa - -const ( - encRefTok0 = `~0` - encRefTok1 = `~1` - decRefTok0 = `~` - decRefTok1 = `/` -) - -// Unescape unescapes a json pointer reference token string to the original representation -func Unescape(token string) string { - step1 := strings.Replace(token, encRefTok1, decRefTok1, -1) - step2 := strings.Replace(step1, encRefTok0, decRefTok0, -1) - return step2 -} - -// Escape escapes a pointer reference token string -func Escape(token string) string { - step1 := strings.Replace(token, decRefTok0, encRefTok0, -1) - step2 := strings.Replace(step1, decRefTok1, encRefTok1, -1) - return step2 -} diff --git a/vendor/github.com/go-openapi/jsonpointer/pointer_test.go b/vendor/github.com/go-openapi/jsonpointer/pointer_test.go deleted file mode 100644 index eabd58603..000000000 --- a/vendor/github.com/go-openapi/jsonpointer/pointer_test.go +++ /dev/null @@ -1,573 +0,0 @@ -// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) -// -// 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. - -// author sigu-399 -// author-github https://github.com/sigu-399 -// author-mail sigu.399@gmail.com -// -// repository-name jsonpointer -// repository-desc An implementation of JSON Pointer - Go language -// -// description Automated tests on package. -// -// created 03-03-2013 - -package jsonpointer - -import ( - "encoding/json" - "fmt" - "strconv" - "testing" - - "github.com/stretchr/testify/assert" -) - -const ( - TestDocumentNBItems = 11 - TestNodeObjNBItems = 4 - TestDocumentString = `{ -"foo": ["bar", "baz"], -"obj": { "a":1, "b":2, "c":[3,4], "d":[ {"e":9}, {"f":[50,51]} ] }, -"": 0, -"a/b": 1, -"c%d": 2, -"e^f": 3, -"g|h": 4, -"i\\j": 5, -"k\"l": 6, -" ": 7, -"m~n": 8 -}` -) - -var testDocumentJSON interface{} - -type testStructJSON struct { - Foo []string `json:"foo"` - Obj struct { - A int `json:"a"` - B int `json:"b"` - C []int `json:"c"` - D []struct { - E int `json:"e"` - F []int `json:"f"` - } `json:"d"` - } `json:"obj"` -} - -type aliasedMap map[string]interface{} - -var testStructJSONDoc testStructJSON -var testStructJSONPtr *testStructJSON - -func init() { - json.Unmarshal([]byte(TestDocumentString), &testDocumentJSON) - json.Unmarshal([]byte(TestDocumentString), &testStructJSONDoc) - testStructJSONPtr = &testStructJSONDoc -} - -func TestEscaping(t *testing.T) { - - ins := []string{`/`, `/`, `/a~1b`, `/a~1b`, `/c%d`, `/e^f`, `/g|h`, `/i\j`, `/k"l`, `/ `, `/m~0n`} - outs := []float64{0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8} - - for i := range ins { - p, err := New(ins[i]) - if assert.NoError(t, err, "input: %v", ins[i]) { - result, _, err := p.Get(testDocumentJSON) - if assert.NoError(t, err, "input: %v", ins[i]) { - assert.Equal(t, outs[i], result, "input: %v", ins[i]) - } - } - } - -} - -func TestFullDocument(t *testing.T) { - - in := `` - - p, err := New(in) - if err != nil { - t.Errorf("New(%v) error %v", in, err.Error()) - } - - result, _, err := p.Get(testDocumentJSON) - if err != nil { - t.Errorf("Get(%v) error %v", in, err.Error()) - } - - if len(result.(map[string]interface{})) != TestDocumentNBItems { - t.Errorf("Get(%v) = %v, expect full document", in, result) - } - - result, _, err = p.get(testDocumentJSON, nil) - if err != nil { - t.Errorf("Get(%v) error %v", in, err.Error()) - } - - if len(result.(map[string]interface{})) != TestDocumentNBItems { - t.Errorf("Get(%v) = %v, expect full document", in, result) - } -} - -func TestDecodedTokens(t *testing.T) { - p, err := New("/obj/a~1b") - assert.NoError(t, err) - assert.Equal(t, []string{"obj", "a/b"}, p.DecodedTokens()) -} - -func TestIsEmpty(t *testing.T) { - p, err := New("") - assert.NoError(t, err) - assert.True(t, p.IsEmpty()) - p, err = New("/obj") - assert.NoError(t, err) - assert.False(t, p.IsEmpty()) -} - -func TestGetSingle(t *testing.T) { - in := `/obj` - - _, err := New(in) - assert.NoError(t, err) - result, _, err := GetForToken(testDocumentJSON, "obj") - assert.NoError(t, err) - assert.Len(t, result, TestNodeObjNBItems) - - result, _, err = GetForToken(testStructJSONDoc, "Obj") - assert.Error(t, err) - assert.Nil(t, result) - - result, _, err = GetForToken(testStructJSONDoc, "Obj2") - assert.Error(t, err) - assert.Nil(t, result) -} - -type pointableImpl struct { - a string -} - -func (p pointableImpl) JSONLookup(token string) (interface{}, error) { - if token == "some" { - return p.a, nil - } - return nil, fmt.Errorf("object has no field %q", token) -} - -func TestPointableInterface(t *testing.T) { - p := &pointableImpl{"hello"} - - result, _, err := GetForToken(p, "some") - assert.NoError(t, err) - assert.Equal(t, p.a, result) - - result, _, err = GetForToken(p, "something") - assert.Error(t, err) - assert.Nil(t, result) -} - -func TestGetNode(t *testing.T) { - - in := `/obj` - - p, err := New(in) - assert.NoError(t, err) - result, _, err := p.Get(testDocumentJSON) - assert.NoError(t, err) - assert.Len(t, result, TestNodeObjNBItems) - - result, _, err = p.Get(aliasedMap(testDocumentJSON.(map[string]interface{}))) - assert.NoError(t, err) - assert.Len(t, result, TestNodeObjNBItems) - - result, _, err = p.Get(testStructJSONDoc) - assert.NoError(t, err) - assert.Equal(t, testStructJSONDoc.Obj, result) - - result, _, err = p.Get(testStructJSONPtr) - assert.NoError(t, err) - assert.Equal(t, testStructJSONDoc.Obj, result) -} - -func TestArray(t *testing.T) { - - ins := []string{`/foo/0`, `/foo/0`, `/foo/1`} - outs := []string{"bar", "bar", "baz"} - - for i := range ins { - p, err := New(ins[i]) - assert.NoError(t, err) - - result, _, err := p.Get(testStructJSONDoc) - assert.NoError(t, err) - assert.Equal(t, outs[i], result) - - result, _, err = p.Get(testStructJSONPtr) - assert.NoError(t, err) - assert.Equal(t, outs[i], result) - - result, _, err = p.Get(testDocumentJSON) - assert.NoError(t, err) - assert.Equal(t, outs[i], result) - } -} - -func TestOtherThings(t *testing.T) { - _, err := New("abc") - assert.Error(t, err) - - p, err := New("") - assert.NoError(t, err) - assert.Equal(t, "", p.String()) - - p, err = New("/obj/a") - assert.Equal(t, "/obj/a", p.String()) - - s := Escape("m~n") - assert.Equal(t, "m~0n", s) - s = Escape("m/n") - assert.Equal(t, "m~1n", s) - - p, err = New("/foo/3") - assert.NoError(t, err) - _, _, err = p.Get(testDocumentJSON) - assert.Error(t, err) - - p, err = New("/foo/a") - assert.NoError(t, err) - _, _, err = p.Get(testDocumentJSON) - assert.Error(t, err) - - p, err = New("/notthere") - assert.NoError(t, err) - _, _, err = p.Get(testDocumentJSON) - assert.Error(t, err) - - p, err = New("/invalid") - assert.NoError(t, err) - _, _, err = p.Get(1234) - assert.Error(t, err) - - p, err = New("/foo/1") - assert.NoError(t, err) - expected := "hello" - bbb := testDocumentJSON.(map[string]interface{})["foo"] - bbb.([]interface{})[1] = "hello" - - v, _, err := p.Get(testDocumentJSON) - assert.NoError(t, err) - assert.Equal(t, expected, v) - - esc := Escape("a/") - assert.Equal(t, "a~1", esc) - unesc := Unescape(esc) - assert.Equal(t, "a/", unesc) - - unesc = Unescape("~01") - assert.Equal(t, "~1", unesc) - assert.Equal(t, "~0~1", Escape("~/")) - assert.Equal(t, "~/", Unescape("~0~1")) -} - -func TestObject(t *testing.T) { - - ins := []string{`/obj/a`, `/obj/b`, `/obj/c/0`, `/obj/c/1`, `/obj/c/1`, `/obj/d/1/f/0`} - outs := []float64{1, 2, 3, 4, 4, 50} - - for i := range ins { - - p, err := New(ins[i]) - assert.NoError(t, err) - - result, _, err := p.Get(testDocumentJSON) - assert.NoError(t, err) - assert.Equal(t, outs[i], result) - - result, _, err = p.Get(testStructJSONDoc) - assert.NoError(t, err) - assert.EqualValues(t, outs[i], result) - - result, _, err = p.Get(testStructJSONPtr) - assert.NoError(t, err) - assert.EqualValues(t, outs[i], result) - } -} - -type setJsonDocEle struct { - B int `json:"b"` - C int `json:"c"` -} -type setJsonDoc struct { - A []struct { - B int `json:"b"` - C int `json:"c"` - } `json:"a"` - D int `json:"d"` -} - -type settableDoc struct { - Coll settableColl - Int settableInt -} - -func (s settableDoc) MarshalJSON() ([]byte, error) { - var res struct { - A settableColl `json:"a"` - D settableInt `json:"d"` - } - res.A = s.Coll - res.D = s.Int - return json.Marshal(res) -} -func (s *settableDoc) UnmarshalJSON(data []byte) error { - var res struct { - A settableColl `json:"a"` - D settableInt `json:"d"` - } - - if err := json.Unmarshal(data, &res); err != nil { - return err - } - s.Coll = res.A - s.Int = res.D - return nil -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s settableDoc) JSONLookup(token string) (interface{}, error) { - switch token { - case "a": - return &s.Coll, nil - case "d": - return &s.Int, nil - default: - return nil, fmt.Errorf("%s is not a known field", token) - } -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s *settableDoc) JSONSet(token string, data interface{}) error { - switch token { - case "a": - switch dt := data.(type) { - case settableColl: - s.Coll = dt - return nil - case *settableColl: - if dt != nil { - s.Coll = *dt - } else { - s.Coll = settableColl{} - } - return nil - case []settableCollItem: - s.Coll.Items = dt - return nil - } - case "d": - switch dt := data.(type) { - case settableInt: - s.Int = dt - return nil - case int: - s.Int.Value = dt - return nil - case int8: - s.Int.Value = int(dt) - return nil - case int16: - s.Int.Value = int(dt) - return nil - case int32: - s.Int.Value = int(dt) - return nil - case int64: - s.Int.Value = int(dt) - return nil - default: - return fmt.Errorf("invalid type %T for %s", data, token) - } - } - return fmt.Errorf("%s is not a known field", token) -} - -type settableColl struct { - Items []settableCollItem -} - -func (s settableColl) MarshalJSON() ([]byte, error) { - return json.Marshal(s.Items) -} -func (s *settableColl) UnmarshalJSON(data []byte) error { - return json.Unmarshal(data, &s.Items) -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s settableColl) JSONLookup(token string) (interface{}, error) { - if tok, err := strconv.Atoi(token); err == nil { - return &s.Items[tok], nil - } - return nil, fmt.Errorf("%s is not a valid index", token) -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s *settableColl) JSONSet(token string, data interface{}) error { - if _, err := strconv.Atoi(token); err == nil { - _, err := SetForToken(s.Items, token, data) - return err - } - return fmt.Errorf("%s is not a valid index", token) -} - -type settableCollItem struct { - B int `json:"b"` - C int `json:"c"` -} - -type settableInt struct { - Value int -} - -func (s settableInt) MarshalJSON() ([]byte, error) { - return json.Marshal(s.Value) -} -func (s *settableInt) UnmarshalJSON(data []byte) error { - return json.Unmarshal(data, &s.Value) -} - -func TestSetNode(t *testing.T) { - - jsonText := `{"a":[{"b": 1, "c": 2}], "d": 3}` - - var jsonDocument interface{} - if assert.NoError(t, json.Unmarshal([]byte(jsonText), &jsonDocument)) { - in := "/a/0/c" - p, err := New(in) - if assert.NoError(t, err) { - - _, err = p.Set(jsonDocument, 999) - assert.NoError(t, err) - - firstNode := jsonDocument.(map[string]interface{}) - assert.Len(t, firstNode, 2) - - sliceNode := firstNode["a"].([]interface{}) - assert.Len(t, sliceNode, 1) - - changedNode := sliceNode[0].(map[string]interface{}) - chNodeVI := changedNode["c"] - if assert.IsType(t, 0, chNodeVI) { - changedNodeValue := chNodeVI.(int) - if assert.Equal(t, 999, changedNodeValue) { - assert.Len(t, sliceNode, 1) - } - } - } - - v, err := New("/a/0") - if assert.NoError(t, err) { - _, err = v.Set(jsonDocument, map[string]interface{}{"b": 3, "c": 8}) - if assert.NoError(t, err) { - firstNode := jsonDocument.(map[string]interface{}) - assert.Len(t, firstNode, 2) - - sliceNode := firstNode["a"].([]interface{}) - assert.Len(t, sliceNode, 1) - changedNode := sliceNode[0].(map[string]interface{}) - assert.Equal(t, 3, changedNode["b"]) - assert.Equal(t, 8, changedNode["c"]) - } - } - } - - var structDoc setJsonDoc - if assert.NoError(t, json.Unmarshal([]byte(jsonText), &structDoc)) { - g, err := New("/a") - if assert.NoError(t, err) { - _, err = g.Set(&structDoc, []struct { - B int `json:"b"` - C int `json:"c"` - }{{B: 4, C: 7}}) - - if assert.NoError(t, err) { - assert.Len(t, structDoc.A, 1) - changedNode := structDoc.A[0] - assert.Equal(t, 4, changedNode.B) - assert.Equal(t, 7, changedNode.C) - } - } - - v, err := New("/a/0") - if assert.NoError(t, err) { - _, err = v.Set(structDoc, struct { - B int `json:"b"` - C int `json:"c"` - }{B: 3, C: 8}) - - if assert.NoError(t, err) { - assert.Len(t, structDoc.A, 1) - changedNode := structDoc.A[0] - assert.Equal(t, 3, changedNode.B) - assert.Equal(t, 8, changedNode.C) - } - } - - p, err := New("/a/0/c") - if assert.NoError(t, err) { - _, err = p.Set(&structDoc, 999) - assert.NoError(t, err) - if assert.Len(t, structDoc.A, 1) { - assert.Equal(t, 999, structDoc.A[0].C) - } - } - } - - var setDoc settableDoc - if assert.NoError(t, json.Unmarshal([]byte(jsonText), &setDoc)) { - g, err := New("/a") - if assert.NoError(t, err) { - _, err = g.Set(&setDoc, []settableCollItem{{B: 4, C: 7}}) - - if assert.NoError(t, err) { - assert.Len(t, setDoc.Coll.Items, 1) - changedNode := setDoc.Coll.Items[0] - assert.Equal(t, 4, changedNode.B) - assert.Equal(t, 7, changedNode.C) - } - } - - v, err := New("/a/0") - if assert.NoError(t, err) { - _, err = v.Set(setDoc, settableCollItem{B: 3, C: 8}) - - if assert.NoError(t, err) { - assert.Len(t, setDoc.Coll.Items, 1) - changedNode := setDoc.Coll.Items[0] - assert.Equal(t, 3, changedNode.B) - assert.Equal(t, 8, changedNode.C) - } - } - - p, err := New("/a/0/c") - if assert.NoError(t, err) { - _, err = p.Set(setDoc, 999) - assert.NoError(t, err) - if assert.Len(t, setDoc.Coll.Items, 1) { - assert.Equal(t, 999, setDoc.Coll.Items[0].C) - } - } - } -} diff --git a/vendor/github.com/go-openapi/jsonreference/.github/CONTRIBUTING.md b/vendor/github.com/go-openapi/jsonreference/.github/CONTRIBUTING.md deleted file mode 100644 index 7dea4240d..000000000 --- a/vendor/github.com/go-openapi/jsonreference/.github/CONTRIBUTING.md +++ /dev/null @@ -1,117 +0,0 @@ -## Contribution Guidelines - -### Pull requests are always welcome - -We are always thrilled to receive pull requests, and do our best to -process them as fast as possible. Not sure if that typo is worth a pull -request? Do it! We will appreciate it. - -If your pull request is not accepted on the first try, don't be -discouraged! If there's a problem with the implementation, hopefully you -received feedback on what to improve. - -We're trying very hard to keep go-swagger lean and focused. We don't want it -to do everything for everybody. This means that we might decide against -incorporating a new feature. However, there might be a way to implement -that feature *on top of* go-swagger. - - -### Conventions - -Fork the repo and make changes on your fork in a feature branch: - -- If it's a bugfix branch, name it XXX-something where XXX is the number of the - issue -- If it's a feature branch, create an enhancement issue to announce your - intentions, and name it XXX-something where XXX is the number of the issue. - -Submit unit tests for your changes. Go has a great test framework built in; use -it! Take a look at existing tests for inspiration. Run the full test suite on -your branch before submitting a pull request. - -Update the documentation when creating or modifying features. Test -your documentation changes for clarity, concision, and correctness, as -well as a clean documentation build. See ``docs/README.md`` for more -information on building the docs and how docs get released. - -Write clean code. Universally formatted code promotes ease of writing, reading, -and maintenance. Always run `gofmt -s -w file.go` on each changed file before -committing your changes. Most editors have plugins that do this automatically. - -Pull requests descriptions should be as clear as possible and include a -reference to all the issues that they address. - -Pull requests must not contain commits from other users or branches. - -Commit messages must start with a capitalized and short summary (max. 50 -chars) written in the imperative, followed by an optional, more detailed -explanatory text which is separated from the summary by an empty line. - -Code review comments may be added to your pull request. Discuss, then make the -suggested modifications and push additional commits to your feature branch. Be -sure to post a comment after pushing. The new commits will show up in the pull -request automatically, but the reviewers will not be notified unless you -comment. - -Before the pull request is merged, make sure that you squash your commits into -logical units of work using `git rebase -i` and `git push -f`. After every -commit the test suite should be passing. Include documentation changes in the -same commit so that a revert would remove all traces of the feature or fix. - -Commits that fix or close an issue should include a reference like `Closes #XXX` -or `Fixes #XXX`, which will automatically close the issue when merged. - -### Sign your work - -The sign-off is a simple line at the end of the explanation for the -patch, which certifies that you wrote it or otherwise have the right to -pass it on as an open-source patch. The rules are pretty simple: if you -can certify the below (from -[developercertificate.org](http://developercertificate.org/)): - -``` -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` - -then you just add a line to every git commit message: - - Signed-off-by: Joe Smith - -using your real name (sorry, no pseudonyms or anonymous contributions.) - -You can add the sign off when creating the git commit via `git commit -s`. diff --git a/vendor/github.com/go-openapi/jsonreference/.gitignore b/vendor/github.com/go-openapi/jsonreference/.gitignore deleted file mode 100644 index 769c24400..000000000 --- a/vendor/github.com/go-openapi/jsonreference/.gitignore +++ /dev/null @@ -1 +0,0 @@ -secrets.yml diff --git a/vendor/github.com/go-openapi/jsonreference/.travis.yml b/vendor/github.com/go-openapi/jsonreference/.travis.yml deleted file mode 100644 index 7a261a651..000000000 --- a/vendor/github.com/go-openapi/jsonreference/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -language: go -go: -- "1.8" -- "1.9" -- "1.10" -install: -- go get -u github.com/stretchr/testify/assert -- go get -u github.com/PuerkitoBio/purell -- go get -u github.com/go-openapi/jsonpointer -script: -- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./... -after_success: -- bash <(curl -s https://codecov.io/bash) -notifications: - slack: - secure: OpQG/36F7DSF00HLm9WZMhyqFCYYyYTsVDObW226cWiR8PWYiNfLZiSEvIzT1Gx4dDjhigKTIqcLhG34CkL5iNXDjm9Yyo2RYhQPlK8NErNqUEXuBqn4RqYHW48VGhEhOyDd4Ei0E2FN5ZbgpvHgtpkdZ6XDi64r3Ac89isP9aPHXQTuv2Jog6b4/OKKiUTftLcTIst0p4Cp3gqOJWf1wnoj+IadWiECNVQT6zb47IYjtyw6+uV8iUjTzdKcRB6Zc6b4Dq7JAg1Zd7Jfxkql3hlKp4PNlRf9Cy7y5iA3G7MLyg3FcPX5z2kmcyPt2jOTRMBWUJ5zIQpOxizAcN8WsT3WWBL5KbuYK6k0PzujrIDLqdxGpNmjkkMfDBT9cKmZpm2FdW+oZgPFJP+oKmAo4u4KJz/vjiPTXgQlN5bmrLuRMCp+AwC5wkIohTqWZVPE2TK6ZSnMYcg/W39s+RP/9mJoyryAvPSpBOLTI+biCgaUCTOAZxNTWpMFc3tPYntc41WWkdKcooZ9JA5DwfcaVFyTGQ3YXz+HvX6G1z/gW0Q/A4dBi9mj2iE1xm7tRTT+4VQ2AXFvSEI1HJpfPgYnwAtwOD1v3Qm2EUHk9sCdtEDR4wVGEPIVn44GnwFMnGKx9JWppMPYwFu3SVDdHt+E+LOlhZUply11Aa+IVrT2KUQ= diff --git a/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e..000000000 --- a/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/jsonreference/LICENSE b/vendor/github.com/go-openapi/jsonreference/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/go-openapi/jsonreference/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/go-openapi/jsonreference/README.md b/vendor/github.com/go-openapi/jsonreference/README.md deleted file mode 100644 index 66345f4c6..000000000 --- a/vendor/github.com/go-openapi/jsonreference/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# gojsonreference [![Build Status](https://travis-ci.org/go-openapi/jsonreference.svg?branch=master)](https://travis-ci.org/go-openapi/jsonreference) [![codecov](https://codecov.io/gh/go-openapi/jsonreference/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonreference) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/jsonreference/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/jsonreference?status.svg)](http://godoc.org/github.com/go-openapi/jsonreference) -An implementation of JSON Reference - Go language - -## Status -Work in progress ( 90% done ) - -## Dependencies -https://github.com/go-openapi/jsonpointer - -## References -http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 - -http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 diff --git a/vendor/github.com/go-openapi/jsonreference/reference.go b/vendor/github.com/go-openapi/jsonreference/reference.go deleted file mode 100644 index 3bc0a6e26..000000000 --- a/vendor/github.com/go-openapi/jsonreference/reference.go +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) -// -// 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. - -// author sigu-399 -// author-github https://github.com/sigu-399 -// author-mail sigu.399@gmail.com -// -// repository-name jsonreference -// repository-desc An implementation of JSON Reference - Go language -// -// description Main and unique file. -// -// created 26-02-2013 - -package jsonreference - -import ( - "errors" - "net/url" - "strings" - - "github.com/PuerkitoBio/purell" - "github.com/go-openapi/jsonpointer" -) - -const ( - fragmentRune = `#` -) - -// New creates a new reference for the given string -func New(jsonReferenceString string) (Ref, error) { - - var r Ref - err := r.parse(jsonReferenceString) - return r, err - -} - -// MustCreateRef parses the ref string and panics when it's invalid. -// Use the New method for a version that returns an error -func MustCreateRef(ref string) Ref { - r, err := New(ref) - if err != nil { - panic(err) - } - return r -} - -// Ref represents a json reference object -type Ref struct { - referenceURL *url.URL - referencePointer jsonpointer.Pointer - - HasFullURL bool - HasURLPathOnly bool - HasFragmentOnly bool - HasFileScheme bool - HasFullFilePath bool -} - -// GetURL gets the URL for this reference -func (r *Ref) GetURL() *url.URL { - return r.referenceURL -} - -// GetPointer gets the json pointer for this reference -func (r *Ref) GetPointer() *jsonpointer.Pointer { - return &r.referencePointer -} - -// String returns the best version of the url for this reference -func (r *Ref) String() string { - - if r.referenceURL != nil { - return r.referenceURL.String() - } - - if r.HasFragmentOnly { - return fragmentRune + r.referencePointer.String() - } - - return r.referencePointer.String() -} - -// IsRoot returns true if this reference is a root document -func (r *Ref) IsRoot() bool { - return r.referenceURL != nil && - !r.IsCanonical() && - !r.HasURLPathOnly && - r.referenceURL.Fragment == "" -} - -// IsCanonical returns true when this pointer starts with http(s):// or file:// -func (r *Ref) IsCanonical() bool { - return (r.HasFileScheme && r.HasFullFilePath) || (!r.HasFileScheme && r.HasFullURL) -} - -// "Constructor", parses the given string JSON reference -func (r *Ref) parse(jsonReferenceString string) error { - - parsed, err := url.Parse(jsonReferenceString) - if err != nil { - return err - } - - r.referenceURL, _ = url.Parse(purell.NormalizeURL(parsed, purell.FlagsSafe|purell.FlagRemoveDuplicateSlashes)) - refURL := r.referenceURL - - if refURL.Scheme != "" && refURL.Host != "" { - r.HasFullURL = true - } else { - if refURL.Path != "" { - r.HasURLPathOnly = true - } else if refURL.RawQuery == "" && refURL.Fragment != "" { - r.HasFragmentOnly = true - } - } - - r.HasFileScheme = refURL.Scheme == "file" - r.HasFullFilePath = strings.HasPrefix(refURL.Path, "/") - - // invalid json-pointer error means url has no json-pointer fragment. simply ignore error - r.referencePointer, _ = jsonpointer.New(refURL.Fragment) - - return nil -} - -// Inherits creates a new reference from a parent and a child -// If the child cannot inherit from the parent, an error is returned -func (r *Ref) Inherits(child Ref) (*Ref, error) { - childURL := child.GetURL() - parentURL := r.GetURL() - if childURL == nil { - return nil, errors.New("child url is nil") - } - if parentURL == nil { - return &child, nil - } - - ref, err := New(parentURL.ResolveReference(childURL).String()) - if err != nil { - return nil, err - } - return &ref, nil -} diff --git a/vendor/github.com/go-openapi/jsonreference/reference_test.go b/vendor/github.com/go-openapi/jsonreference/reference_test.go deleted file mode 100644 index 2bfadcede..000000000 --- a/vendor/github.com/go-openapi/jsonreference/reference_test.go +++ /dev/null @@ -1,420 +0,0 @@ -// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) -// -// 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. - -// author sigu-399 -// author-github https://github.com/sigu-399 -// author-mail sigu.399@gmail.com -// -// repository-name jsonreference -// repository-desc An implementation of JSON Reference - Go language -// -// description Automated tests on package. -// -// created 03-03-2013 - -package jsonreference - -import ( - "testing" - - "github.com/go-openapi/jsonpointer" - "github.com/stretchr/testify/assert" -) - -func TestIsRoot(t *testing.T) { - in := "#" - r1, err := New(in) - assert.NoError(t, err) - assert.True(t, r1.IsRoot()) - - in = "#/ok" - r1 = MustCreateRef(in) - assert.False(t, r1.IsRoot()) - - assert.Panics(t, assert.PanicTestFunc(func() { - MustCreateRef("%2") - })) -} - -func TestFull(t *testing.T) { - - in := "http://host/path/a/b/c#/f/a/b" - - r1, err := New(in) - if err != nil { - t.Errorf("New(%v) error %s", in, err.Error()) - } - - if in != r1.String() { - t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) - } - - if r1.HasFragmentOnly != false { - t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) - } - - if r1.HasFullURL != true { - t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, true) - } - - if r1.HasURLPathOnly != false { - t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, false) - } - - if r1.HasFileScheme != false { - t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) - } - - if r1.GetPointer().String() != "/f/a/b" { - t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "/f/a/b") - } -} - -func TestFullURL(t *testing.T) { - - in := "http://host/path/a/b/c" - - r1, err := New(in) - if err != nil { - t.Errorf("New(%v) error %s", in, err.Error()) - } - - if in != r1.String() { - t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) - } - - if r1.HasFragmentOnly != false { - t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) - } - - if r1.HasFullURL != true { - t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, true) - } - - if r1.HasURLPathOnly != false { - t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, false) - } - - if r1.HasFileScheme != false { - t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) - } - - if r1.GetPointer().String() != "" { - t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "") - } -} - -func TestFragmentOnly(t *testing.T) { - - in := "#/fragment/only" - - r1, err := New(in) - if err != nil { - t.Errorf("New(%v) error %s", in, err.Error()) - } - - if in != r1.String() { - t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) - } - - if r1.HasFragmentOnly != true { - t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, true) - } - - if r1.HasFullURL != false { - t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, false) - } - - if r1.HasURLPathOnly != false { - t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, false) - } - - if r1.HasFileScheme != false { - t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) - } - - if r1.GetPointer().String() != "/fragment/only" { - t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "/fragment/only") - } - - p, _ := jsonpointer.New(r1.referenceURL.Fragment) - r2 := Ref{referencePointer: p, HasFragmentOnly: true} - assert.Equal(t, r2.String(), in) - - r3 := Ref{referencePointer: p, HasFragmentOnly: false} - assert.Equal(t, r3.String(), in[1:]) -} - -func TestURLPathOnly(t *testing.T) { - - in := "/documents/document.json" - - r1, err := New(in) - if err != nil { - t.Errorf("New(%v) error %s", in, err.Error()) - } - - if in != r1.String() { - t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) - } - - if r1.HasFragmentOnly != false { - t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) - } - - if r1.HasFullURL != false { - t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, false) - } - - if r1.HasURLPathOnly != true { - t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, true) - } - - if r1.HasFileScheme != false { - t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) - } - - if r1.GetPointer().String() != "" { - t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "") - } -} - -func TestURLRelativePathOnly(t *testing.T) { - - in := "document.json" - - r1, err := New(in) - if err != nil { - t.Errorf("New(%v) error %s", in, err.Error()) - } - - if in != r1.String() { - t.Errorf("New(%v) = %v, expect %v", in, r1.String(), in) - } - - if r1.HasFragmentOnly != false { - t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in, r1.HasFragmentOnly, false) - } - - if r1.HasFullURL != false { - t.Errorf("New(%v)::HasFullURL %v expect %v", in, r1.HasFullURL, false) - } - - if r1.HasURLPathOnly != true { - t.Errorf("New(%v)::HasURLPathOnly %v expect %v", in, r1.HasURLPathOnly, true) - } - - if r1.HasFileScheme != false { - t.Errorf("New(%v)::HasFileScheme %v expect %v", in, r1.HasFileScheme, false) - } - - if r1.GetPointer().String() != "" { - t.Errorf("New(%v)::GetPointer() %v expect %v", in, r1.GetPointer().String(), "") - } -} - -func TestInheritsInValid(t *testing.T) { - in1 := "http://www.test.com/doc.json" - in2 := "#/a/b" - - r1, _ := New(in1) - r2 := Ref{} - result, err := r1.Inherits(r2) - assert.Error(t, err) - assert.Nil(t, result) - - r1 = Ref{} - r2, _ = New(in2) - result, err = r1.Inherits(r2) - assert.NoError(t, err) - assert.Equal(t, r2, *result) -} - -func TestInheritsValid(t *testing.T) { - - in1 := "http://www.test.com/doc.json" - in2 := "#/a/b" - out := in1 + in2 - - r1, _ := New(in1) - r2, _ := New(in2) - - result, err := r1.Inherits(r2) - if err != nil { - t.Errorf("Inherits(%s,%s) error %s", r1.String(), r2.String(), err.Error()) - } - - if result.String() != out { - t.Errorf("Inherits(%s,%s) = %s, expect %s", r1.String(), r2.String(), result.String(), out) - } - - if result.GetPointer().String() != "/a/b" { - t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "/a/b") - } -} - -func TestInheritsDifferentHost(t *testing.T) { - - in1 := "http://www.test.com/doc.json" - in2 := "http://www.test2.com/doc.json#bla" - - r1, _ := New(in1) - r2, _ := New(in2) - - result, err := r1.Inherits(r2) - - if err != nil { - t.Errorf("Inherits(%s,%s) should not fail. Error: %s", r1.String(), r2.String(), err.Error()) - } - - if result.String() != in2 { - t.Errorf("Inherits(%s,%s) should be %s but is %s", in1, in2, in2, result) - } - - if result.GetPointer().String() != "" { - t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "") - } -} - -func TestFileScheme(t *testing.T) { - - in1 := "file:///Users/mac/1.json#a" - in2 := "file:///Users/mac/2.json#b" - - r1, _ := New(in1) - r2, _ := New(in2) - - if r1.HasFragmentOnly != false { - t.Errorf("New(%v)::HasFragmentOnly %v expect %v", in1, r1.HasFragmentOnly, false) - } - - if r1.HasFileScheme != true { - t.Errorf("New(%v)::HasFileScheme %v expect %v", in1, r1.HasFileScheme, true) - } - - if r1.HasFullFilePath != true { - t.Errorf("New(%v)::HasFullFilePath %v expect %v", in1, r1.HasFullFilePath, true) - } - - if r1.IsCanonical() != true { - t.Errorf("New(%v)::IsCanonical %v expect %v", in1, r1.IsCanonical(), true) - } - - result, err := r1.Inherits(r2) - if err != nil { - t.Errorf("Inherits(%s,%s) should not fail. Error: %s", r1.String(), r2.String(), err.Error()) - } - if result.String() != in2 { - t.Errorf("Inherits(%s,%s) should be %s but is %s", in1, in2, in2, result) - } - - if result.GetPointer().String() != "" { - t.Errorf("result(%v)::GetPointer() %v expect %v", result.String(), result.GetPointer().String(), "") - } -} - -func TestReferenceResolution(t *testing.T) { - - // 5.4. Reference Resolution Examples - // http://tools.ietf.org/html/rfc3986#section-5.4 - - base := "http://a/b/c/d;p?q" - baseRef, err := New(base) - - if err != nil { - t.Errorf("New(%s) failed error: %s", base, err.Error()) - } - if baseRef.String() != base { - t.Errorf("New(%s) %s expected %s", base, baseRef.String(), base) - } - - checks := []string{ - // 5.4.1. Normal Examples - // http://tools.ietf.org/html/rfc3986#section-5.4.1 - - "g:h", "g:h", - "g", "http://a/b/c/g", - "./g", "http://a/b/c/g", - "g/", "http://a/b/c/g/", - "/g", "http://a/g", - "//g", "http://g", - "?y", "http://a/b/c/d;p?y", - "g?y", "http://a/b/c/g?y", - "#s", "http://a/b/c/d;p?q#s", - "g#s", "http://a/b/c/g#s", - "g?y#s", "http://a/b/c/g?y#s", - ";x", "http://a/b/c/;x", - "g;x", "http://a/b/c/g;x", - "g;x?y#s", "http://a/b/c/g;x?y#s", - "", "http://a/b/c/d;p?q", - ".", "http://a/b/c/", - "./", "http://a/b/c/", - "..", "http://a/b/", - "../", "http://a/b/", - "../g", "http://a/b/g", - "../..", "http://a/", - "../../", "http://a/", - "../../g", "http://a/g", - - // 5.4.2. Abnormal Examples - // http://tools.ietf.org/html/rfc3986#section-5.4.2 - - "../../../g", "http://a/g", - "../../../../g", "http://a/g", - - "/./g", "http://a/g", - "/../g", "http://a/g", - "g.", "http://a/b/c/g.", - ".g", "http://a/b/c/.g", - "g..", "http://a/b/c/g..", - "..g", "http://a/b/c/..g", - - "./../g", "http://a/b/g", - "./g/.", "http://a/b/c/g/", - "g/./h", "http://a/b/c/g/h", - "g/../h", "http://a/b/c/h", - "g;x=1/./y", "http://a/b/c/g;x=1/y", - "g;x=1/../y", "http://a/b/c/y", - - "g?y/./x", "http://a/b/c/g?y/./x", - "g?y/../x", "http://a/b/c/g?y/../x", - "g#s/./x", "http://a/b/c/g#s/./x", - "g#s/../x", "http://a/b/c/g#s/../x", - - "http:g", "http:g", // for strict parsers - //"http:g", "http://a/b/c/g", // for backward compatibility - - } - for i := 0; i < len(checks); i += 2 { - child := checks[i] - expected := checks[i+1] - // fmt.Printf("%d: %v -> %v\n", i/2, child, expected) - - childRef, e := New(child) - if e != nil { - t.Errorf("%d: New(%s) failed error: %s", i/2, child, e.Error()) - } - - res, e := baseRef.Inherits(childRef) - if res == nil { - t.Errorf("%d: Inherits(%s, %s) nil not expected", i/2, base, child) - } - if e != nil { - t.Errorf("%d: Inherits(%s) failed error: %s", i/2, child, e.Error()) - } - if res.String() != expected { - t.Errorf("%d: Inherits(%s, %s) %s expected %s", i/2, base, child, res.String(), expected) - } - } -} diff --git a/vendor/github.com/go-openapi/loads/.drone.sec b/vendor/github.com/go-openapi/loads/.drone.sec deleted file mode 100644 index 6d3e84399..000000000 --- a/vendor/github.com/go-openapi/loads/.drone.sec +++ /dev/null @@ -1 +0,0 @@ -eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhHQ00ifQ.xUjixvmMMeampw0Doyr_XLvcV5ICmDgDFmlcWqgmO84O3Hwn6dqbMkwOjpKMOyEJW_98b5Om5ED59IFt2S0T_OarlrsJL8jOK5fqxSMNXy2w8LfI-e5l1URverW41ofAVK8m9wK05q2BSJM_M6PyyODaQeDBiCVK1HreMZBlXpuUDVtBMPILQoga0eSZOsTR3DYEpZIS0A0Rsa5yIhMYR5d5-JMYqbqOCB7tNJ-BM83OzYgL7Hrz0J15kqaJmhQ-GJoMJDzOemSO9KxLCOfSPp11R_G3Mfd48xYnuiRuPOTakbOCLxuYviH6uoGVIOhnMyY9qKiDKbOn4BQUi1-igA.6qjQzq9nzAxRRKV_.z79R5cMFAEuEaAh6U9ykiL8oIqzMbs_I2C-hSFRh3HYRJ4fTB-9LrcbF0uASIOq7bBn4OQzW-0QFwYOs1uaawmrByGngV5d0afiZf_LBKcmTF2vtxRi_A_nxD-EHoPmh3lKBU5WNDe_8kLjEeS89HeyyFPuv5iQbqhzdqPFohHKVigwVqVYYLjB8GWQ4t7tC4c8l5rHanaXf71W0e3op2m8bebpZL0JPGhnULVA1oU27TYeLsO112JkIYtBwZxzvAs--bBFoKeGJWVMFzrKN68UACGZ9RFw0uGJbBmVC4-jRuIc6XpqeEqw3KG-rjFzkeEor3575qW-8kiXYqpub9SFUc3SSZkxJ8hB3SrnMBOuDUSenrXNpAbltmV3KAALzN3_bMBQuihwSRIn0Hg7-Dpni8BieMe44RMDvRu6p_71aeU_KW4V7Umy_h8gpIvQFuKGdTQH2ahsyCXL0ojqjMbVMdoWpDQTQ2_Fy8Qt_p2kJ8BgDo-1Akd4a6BNU2NGqsdnrJmtVKcTqLBadf9ylCwxHdGVrtNYORALSms2T6Q1s-poQnMjIwN8lnUD8ABUBpt4uVtrYkiWPVwrwywLQeiHhR-pboe_53kWDAx4Hy4rpbKsaxanYhy_bEbAYKb3aIUA.75GD4kRBCQdcGFYP1QYdCg \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/.drone.yml b/vendor/github.com/go-openapi/loads/.drone.yml deleted file mode 100644 index 982291035..000000000 --- a/vendor/github.com/go-openapi/loads/.drone.yml +++ /dev/null @@ -1,39 +0,0 @@ -clone: - path: github.com/go-openapi/loads - -matrix: - GO_VERSION: - - "1.6" - -build: - integration: - image: golang:$$GO_VERSION - pull: true - environment: - GOCOVMODE: "count" - commands: - - go get -u github.com/axw/gocov/gocov - - go get -u gopkg.in/matm/v1/gocov-html - - go get -u github.com/cee-dub/go-junit-report - - go get -u github.com/stretchr/testify/assert - - go get -u gopkg.in/yaml.v2 - - go get -u github.com/go-openapi/swag - - go get -u github.com/go-openapi/analysis - - go get -u github.com/go-openapi/spec - - ./hack/build-drone.sh - -notify: - slack: - channel: bots - webhook_url: $$SLACK_URL - username: drone - -publish: - coverage: - server: https://coverage.vmware.run - token: $$GITHUB_TOKEN - # threshold: 70 - # must_increase: true - when: - matrix: - GO_VERSION: "1.6" diff --git a/vendor/github.com/go-openapi/loads/.editorconfig b/vendor/github.com/go-openapi/loads/.editorconfig deleted file mode 100644 index 3152da69a..000000000 --- a/vendor/github.com/go-openapi/loads/.editorconfig +++ /dev/null @@ -1,26 +0,0 @@ -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -end_of_line = lf -insert_final_newline = true -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true - -# Set default charset -[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] -charset = utf-8 - -# Tab indentation (no size specified) -[*.go] -indent_style = tab - -[*.md] -trim_trailing_whitespace = false - -# Matches the exact files either package.json or .travis.yml -[{package.json,.travis.yml}] -indent_style = space -indent_size = 2 diff --git a/vendor/github.com/go-openapi/loads/.github/CONTRIBUTING.md b/vendor/github.com/go-openapi/loads/.github/CONTRIBUTING.md deleted file mode 100644 index 7dea4240d..000000000 --- a/vendor/github.com/go-openapi/loads/.github/CONTRIBUTING.md +++ /dev/null @@ -1,117 +0,0 @@ -## Contribution Guidelines - -### Pull requests are always welcome - -We are always thrilled to receive pull requests, and do our best to -process them as fast as possible. Not sure if that typo is worth a pull -request? Do it! We will appreciate it. - -If your pull request is not accepted on the first try, don't be -discouraged! If there's a problem with the implementation, hopefully you -received feedback on what to improve. - -We're trying very hard to keep go-swagger lean and focused. We don't want it -to do everything for everybody. This means that we might decide against -incorporating a new feature. However, there might be a way to implement -that feature *on top of* go-swagger. - - -### Conventions - -Fork the repo and make changes on your fork in a feature branch: - -- If it's a bugfix branch, name it XXX-something where XXX is the number of the - issue -- If it's a feature branch, create an enhancement issue to announce your - intentions, and name it XXX-something where XXX is the number of the issue. - -Submit unit tests for your changes. Go has a great test framework built in; use -it! Take a look at existing tests for inspiration. Run the full test suite on -your branch before submitting a pull request. - -Update the documentation when creating or modifying features. Test -your documentation changes for clarity, concision, and correctness, as -well as a clean documentation build. See ``docs/README.md`` for more -information on building the docs and how docs get released. - -Write clean code. Universally formatted code promotes ease of writing, reading, -and maintenance. Always run `gofmt -s -w file.go` on each changed file before -committing your changes. Most editors have plugins that do this automatically. - -Pull requests descriptions should be as clear as possible and include a -reference to all the issues that they address. - -Pull requests must not contain commits from other users or branches. - -Commit messages must start with a capitalized and short summary (max. 50 -chars) written in the imperative, followed by an optional, more detailed -explanatory text which is separated from the summary by an empty line. - -Code review comments may be added to your pull request. Discuss, then make the -suggested modifications and push additional commits to your feature branch. Be -sure to post a comment after pushing. The new commits will show up in the pull -request automatically, but the reviewers will not be notified unless you -comment. - -Before the pull request is merged, make sure that you squash your commits into -logical units of work using `git rebase -i` and `git push -f`. After every -commit the test suite should be passing. Include documentation changes in the -same commit so that a revert would remove all traces of the feature or fix. - -Commits that fix or close an issue should include a reference like `Closes #XXX` -or `Fixes #XXX`, which will automatically close the issue when merged. - -### Sign your work - -The sign-off is a simple line at the end of the explanation for the -patch, which certifies that you wrote it or otherwise have the right to -pass it on as an open-source patch. The rules are pretty simple: if you -can certify the below (from -[developercertificate.org](http://developercertificate.org/)): - -``` -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` - -then you just add a line to every git commit message: - - Signed-off-by: Joe Smith - -using your real name (sorry, no pseudonyms or anonymous contributions.) - -You can add the sign off when creating the git commit via `git commit -s`. diff --git a/vendor/github.com/go-openapi/loads/.gitignore b/vendor/github.com/go-openapi/loads/.gitignore deleted file mode 100644 index e4f15f17b..000000000 --- a/vendor/github.com/go-openapi/loads/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -secrets.yml -coverage.out -profile.cov -profile.out diff --git a/vendor/github.com/go-openapi/loads/.travis.yml b/vendor/github.com/go-openapi/loads/.travis.yml deleted file mode 100644 index b0d357e65..000000000 --- a/vendor/github.com/go-openapi/loads/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -language: go -go: -- 1.8 -install: -- go get -u github.com/stretchr/testify -- go get -u github.com/go-openapi/analysis -- go get -u github.com/go-openapi/spec -- go get -u github.com/go-openapi/swag -- go get -u gopkg.in/yaml.v2 -script: -- ./hack/coverage -after_success: -- bash <(curl -s https://codecov.io/bash) -notifications: - slack: - secure: OxkPwVp35qBTUilgWC8xykSj+sGMcj0h8IIOKD+Rflx2schZVlFfdYdyVBM+s9OqeOfvtuvnR9v1Ye2rPKAvcjWdC4LpRGUsgmItZaI6Um8Aj6+K9udCw5qrtZVfOVmRu8LieH//XznWWKdOultUuniW0MLqw5+II87Gd00RWbCGi0hk0PykHe7uK+PDA2BEbqyZ2WKKYCvfB3j+0nrFOHScXqnh0V05l2E83J4+Sgy1fsPy+1WdX58ZlNBG333ibaC1FS79XvKSmTgKRkx3+YBo97u6ZtUmJa5WZjf2OdLG3KIckGWAv6R5xgxeU31N0Ng8L332w/Edpp2O/M2bZwdnKJ8hJQikXIAQbICbr+lTDzsoNzMdEIYcHpJ5hjPbiUl3Bmd+Jnsjf5McgAZDiWIfpCKZ29tPCEkVwRsOCqkyPRMNMzHHmoja495P5jR+ODS7+J8RFg5xgcnOgpP9D4Wlhztlf5WyZMpkLxTUD+bZq2SRf50HfHFXTkfq22zPl3d1eq0yrLwh/Z/fWKkfb6SyysROL8y6s8u3dpFX1YHSg0BR6i913h4aoZw9B2BG27cafLLTwKYsp2dFo1PWl4O6u9giFJIeqwloZHLKKrwh0cBFhB7RH0I58asxkZpCH6uWjJierahmHe7iS+E6i+9oCHkOZ59hmCYNimIs3hM= diff --git a/vendor/github.com/go-openapi/loads/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/loads/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e..000000000 --- a/vendor/github.com/go-openapi/loads/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/loads/LICENSE b/vendor/github.com/go-openapi/loads/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/go-openapi/loads/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/go-openapi/loads/README.md b/vendor/github.com/go-openapi/loads/README.md deleted file mode 100644 index 6dbb8342e..000000000 --- a/vendor/github.com/go-openapi/loads/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Loads OAI specs [![Build Status](https://travis-ci.org/go-openapi/loads.svg?branch=master)](https://travis-ci.org/go-openapi/loads) [![codecov](https://codecov.io/gh/go-openapi/loads/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/loads) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/loads/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/loads?status.svg)](http://godoc.org/github.com/go-openapi/loads) - -Loading of OAI specification documents from local or remote locations. diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithArrayRef.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithArrayRef.json deleted file mode 100644 index 25e8903a7..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithArrayRef.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "required": [ - "id" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "children": { - "type": "array", - "items": { - "$ref": "Person" - } - } - } -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithComposition.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithComposition.json deleted file mode 100644 index 21e01dc2a..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithComposition.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "definitions": { - "Cat": { - "description": "A representation of a cat", - "allOf": [ - { "$ref": "#/models/Pet" }, - { - "properties": { - "huntingSkill": { - "type": "string", - "description": "The measured skill for hunting", - "default": "lazy", - "enum": ["clueless", "lazy", "adventerous", "aggressive"] - } - }, - "required": [ "huntingSkill" ] - } - ] - }, - "Dog": { - "description": "A representation of a dog", - "allOf": [ - { "$ref": "#/models/Pet" }, - { - "properties": { - "packSize": { - "type": "integer", - "format": "int32", - "description": "the size of the pack the dog is from", - "default": 0, - "minimum": 0 - } - }, - "required": [ "name", "packSize" ] - } - ] - }, - "Fish": { - "description": "A representation of a fish", - "allOf": [ - { "$ref": "#/models/Pet" }, - { - "properties": { - "fins": { - "type": "integer", - "format": "int32", - "description": "count of fins", - "minimum": 0 - } - }, - "required": [ "fins" ] - } - ] - }, - "Pet": { - "discriminator": "petType", - "properties": { - "name": { - "type": "string" - }, - "petType": { - "type": "string" - } - }, - "required": [ "name", "petType" ] - } - } -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithDateTimeMap.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithDateTimeMap.json deleted file mode 100644 index a5ebdf9b2..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithDateTimeMap.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "description": "true", - "additionalProperties": { - "type": "string", - "format": "date-time" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithExamples.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithExamples.json deleted file mode 100644 index f62be6624..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithExamples.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "definitions": { - "Pet": { - "properties": { - "name": { - "type": "string" - } - }, - "required": [ - "name" - ] - }, - "Dog": { - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - }, - "required": [ - "name" - ] - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithInt32Map.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithInt32Map.json deleted file mode 100644 index b4597e846..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithInt32Map.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "description": "This is a Map[String, Integer]", - "additionalProperties": { - "type": "integer", - "format": "int32" - } -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithInt64Map.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithInt64Map.json deleted file mode 100644 index 5160f21c4..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithInt64Map.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "description": "true", - "additionalProperties": { - "type": "integer", - "format": "int64" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithMultipleProperties.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithMultipleProperties.json deleted file mode 100644 index dba5e64ab..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithMultipleProperties.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "description": "true", - "properties": { - "booleanValue": { - "type": "boolean" - }, - "byteValue": { - "type": "string", - "format": "byte" - }, - "dateTimeValue": { - "type": "string", - "format": "date-time" - }, - "int32Value": { - "type": "integer", - "format": "int32" - }, - "int64Value": { - "type": "integer", - "format": "int64" - }, - "stringValue": { - "type": "string" - }, - "booleanArrayValue": { - "type": "array", - "items": { - "type": "boolean" - } - }, - "byteArrayValue": { - "type": "array", - "items": { - "type": "string", - "format": "byte" - } - }, - "dateTimeArrayValue": { - "type": "array", - "items": { - "type": "string", - "format": "date-time" - } - }, - "int32ArrayValue": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - }, - "int64ArrayValue": { - "type": "array", - "items": { - "type": "integer", - "format": "int64" - } - }, - "stringArrayValue": { - "type": "array", - "items": { - "type": "string" - } - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithObjectMap.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithObjectMap.json deleted file mode 100644 index 3e9fb7700..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithObjectMap.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "description": "This is a Map[String, { id: Long, name: String}]", - "additionalProperties": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - } - } -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithPrimitiveArray.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithPrimitiveArray.json deleted file mode 100644 index bc1a8e174..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithPrimitiveArray.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "required": [ - "id" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "childrensAges": { - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithStringProperty.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithStringProperty.json deleted file mode 100644 index 53b4fe1d7..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithStringProperty.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "description": "true", - "properties": { - "name": { - "type": "string" - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithXmlAttributes.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithXmlAttributes.json deleted file mode 100644 index 1aed1a9f7..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/modelWithXmlAttributes.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "description": "this model serves xml and json structures", - "xml": { - "name": "XMLModel" - }, - "properties": { - "id": { - "type": "integer", - "format": "int64", - "xml": { - "attribute": true, - "namespace": "ns1", - "prefix": "urn1" - } - }, - "items": { - "type": "array", - "items": { - "type": "string" - }, - "xml": { - "wrapped": true - } - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/models.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/models.json deleted file mode 100644 index 7eff6dbe0..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/models.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "definitions": { - "Pet": { - "properties": { - "name": { - "type": "string" - } - }, - "required": [ - "name" - ] - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/multipleModels.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/multipleModels.json deleted file mode 100644 index f62be6624..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/multipleModels.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "definitions": { - "Pet": { - "properties": { - "name": { - "type": "string" - } - }, - "required": [ - "name" - ] - }, - "Dog": { - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - }, - "required": [ - "name" - ] - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithBooleanArray.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithBooleanArray.json deleted file mode 100644 index e7ae99b07..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithBooleanArray.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "type": "array", - "items": { - "type": "boolean" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithByteArray.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithByteArray.json deleted file mode 100644 index a6cb13c18..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithByteArray.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "array", - "items": { - "type": "string", - "format": "byte" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithComplexArray.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithComplexArray.json deleted file mode 100644 index c2402e0c6..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithComplexArray.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "type": "array", - "items": { - "$ref": "ComplexType" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithDateTimeArray.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithDateTimeArray.json deleted file mode 100644 index 8b1077316..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithDateTimeArray.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "array", - "items": { - "type": "string", - "format": "date-time" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithInt32Array.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithInt32Array.json deleted file mode 100644 index 5aae819ca..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithInt32Array.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "array", - "items": { - "type": "integer", - "format": "int32" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithInt64Array.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithInt64Array.json deleted file mode 100644 index 5b1f55159..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithInt64Array.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "array", - "items": { - "type": "integer", - "format": "int64" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithRef.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithRef.json deleted file mode 100644 index d8ffdd589..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithRef.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "$ref": "Foo", - "description": "a boolean", - "readOnly": true -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithStringArray.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithStringArray.json deleted file mode 100644 index 7936520d7..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/propertyWithStringArray.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "type": "array", - "items": { - "type": "string" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleBooleanProperty.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleBooleanProperty.json deleted file mode 100644 index 04153ed86..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleBooleanProperty.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "type": "boolean", - "description": "a boolean", - "readOnly": true -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleByteProperty.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleByteProperty.json deleted file mode 100644 index 74fc007f7..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleByteProperty.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "type": "string", - "format": "byte" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleDateTimeProperty.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleDateTimeProperty.json deleted file mode 100644 index a154c6b38..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleDateTimeProperty.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "type": "string", - "format": "date-time" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleInt32Property.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleInt32Property.json deleted file mode 100644 index b436c52c7..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleInt32Property.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "type": "integer", - "format": "int32" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleInt64Property.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleInt64Property.json deleted file mode 100644 index 1f3419620..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleInt64Property.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "type": "integer", - "format": "int64" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleStringProperty.json b/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleStringProperty.json deleted file mode 100644 index 28ac6e864..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/models/properties/simpleStringProperty.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "type": "string" -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/cascadingSchemes.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/cascadingSchemes.json deleted file mode 100644 index 68c970292..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/cascadingSchemes.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.9-abcd", - "title": "Swagger Sample API", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "my.api.com", - "basePath": "/v1", - "schemes": [ - "http", - "https" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json", - "application/xml" - ], - "paths": { - "/pets/{petId}": { - "get": { - "description": "Returns a pet based on ID", - "summary": "Find pet by ID", - "operationId": "getPetsById", - "produces": [ - "application/json", - "text/html" - ], - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet that needs to be fetched", - "required": true, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "$ref": "Pet" - } - }, - "default": { - "description": "error payload", - "schema": { - "$ref": "ErrorModel" - } - } - }, - "schemes": [ "https" ] - } - } - }, - "definitions": { - "Pet": { - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "ErrorModel": { - "required": [ "code", "message" ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/commonParameters.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/commonParameters.json deleted file mode 100644 index 5a9a12841..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/commonParameters.json +++ /dev/null @@ -1,100 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.9-abcd", - "title": "Swagger Sample API", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "my.api.com", - "basePath": "/v1", - "schemes": [ - "http", - "https" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json", - "application/xml" - ], - "paths": { - "/pets/{id}": { - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to use", - "required": true, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - } - ], - "get": { - "description": "Returns pets based on ID", - "summary": "Find pets by ID", - "operationId": "getPetsById", - "produces": [ - "application/json", - "text/html" - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "type": "array", - "items": { - "$ref": "Pet" - } - } - }, - "default": { - "description": "error payload", - "schema": { - "$ref": "ErrorModel" - } - } - } - } - } - }, - "definitions": { - "Pet": { - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "ErrorModel": { - "required": [ "code", "message" ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/multipleMimeTypes.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/multipleMimeTypes.json deleted file mode 100644 index fa014914d..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/multipleMimeTypes.json +++ /dev/null @@ -1,109 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.9-abcd", - "title": "Swagger Sample API", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "my.api.com", - "basePath": "/v1", - "schemes": [ - "http", - "https" - ], - "consumes": [ - "text/plain; charset=utf-8", - "application/json", - "application/vnd.github+json", - "application/vnd.github.v3+json", - "application/vnd.github.v3.raw+json", - "application/vnd.github.v3.text+json", - "application/vnd.github.v3.html+json", - "application/vnd.github.v3.full+json", - "application/vnd.github.v3.diff", - "application/vnd.github.v3.patch" - ], - "produces": [ - "application/json", - "application/xml" - ], - "paths": { - "/pets/{id}": { - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to use", - "required": true, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - } - ], - "get": { - "description": "Returns pets based on ID", - "summary": "Find pets by ID", - "operationId": "getPetsById", - "produces": [ - "application/json", - "text/html" - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "type": "array", - "items": { - "$ref": "Pet" - } - } - }, - "default": { - "description": "error payload", - "schema": { - "$ref": "ErrorModel" - } - } - } - } - } - }, - "definitions": { - "Pet": { - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "ErrorModel": { - "required": [ "code", "message" ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/operations/operationWithTags.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/operations/operationWithTags.json deleted file mode 100644 index 832560566..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/operations/operationWithTags.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "description": "Returns a pet based on ID", - "summary": "Find pet by ID", - "operationId": "getPetsById", - "tags": [ "foo", "bar"], - "produces": [ - "application/json", - "text/html" - ], - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet that needs to be fetched", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "200": { - "description": "a pet to be returned", - "schema": {"$ref": "Pet"} - }, - "default": { - "description": "Unexpected error", - "schema": {"$ref": "ErrorModel"} - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/operations/stringPathAndBoolQueryParamResource.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/operations/stringPathAndBoolQueryParamResource.json deleted file mode 100644 index 75f0efa28..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/operations/stringPathAndBoolQueryParamResource.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "description": "Returns a pet based on ID", - "summary": "Find pet by ID", - "operationId": "getPetsById", - "produces": [ - "application/json", - "text/html" - ], - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet that needs to be fetched", - "required": true, - "type": "integer", - "format": "int64" - }, - { - "name": "includeDetails", - "in": "query", - "description": "include details in response", - "required": true, - "type": "boolean" - } - ], - "responses": { - "200": { - "description": "a pet to be returned", - "schema": {"$ref": "Pet"} - }, - "default": { - "description": "Unexpected error", - "schema": {"$ref": "ErrorModel"} - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/operations/stringPathParamResource.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/operations/stringPathParamResource.json deleted file mode 100644 index 14eba194a..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/operations/stringPathParamResource.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "description": "Returns a pet based on ID", - "summary": "Find pet by ID", - "operationId": "getPetsById", - "produces": [ - "application/json", - "text/html" - ], - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet that needs to be fetched", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "200": { - "description": "fun", - "schema": {"$ref": "Pet"} - }, - "400": { - "description": "Invalid ID supplied <= this is purely for documentation", - "schema": {"$ref": "ErrorModel"} - }, - "default": { - "description": "Unexpected error", - "schema": {"$ref": "ErrorModel"} - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/bodyComplexArrayParameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/bodyComplexArrayParameter.json deleted file mode 100644 index 5a4ef2582..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/bodyComplexArrayParameter.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "user", - "in": "body", - "description": "user to add to the system", - "required": true, - "schema": { - "type": "array", - "items": { - "type": "string" - }, - "format": "csv" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/bodyComplexParameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/bodyComplexParameter.json deleted file mode 100644 index 4a5327a81..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/bodyComplexParameter.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "user", - "in": "body", - "description": "user to add to the system", - "required": true, - "schema": { - "$ref": "User" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/bodyInt64Parameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/bodyInt64Parameter.json deleted file mode 100644 index 5bd668b81..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/bodyInt64Parameter.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "id", - "in": "body", - "description": "id to add", - "required": true, - "schema": { - "type": "integer", - "format": "int64" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/bodyStringArrayParameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/bodyStringArrayParameter.json deleted file mode 100644 index 535a3056d..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/bodyStringArrayParameter.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "user", - "in": "body", - "description": "user to add to the system", - "required": true, - "schema": { - "type": "array", - "items": { - "type": "string" - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/bodyStringParameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/bodyStringParameter.json deleted file mode 100644 index 499435a5b..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/bodyStringParameter.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "user", - "in": "body", - "description": "user to add to the system", - "required": true, - "schema": { - "type": "string" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/formDataComplexParameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/formDataComplexParameter.json deleted file mode 100644 index aa09e7160..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/formDataComplexParameter.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "firstName", - "in": "formData", - "description": "users first name", - "required": true, - "$ref": "Nothing" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/formDataInt64Parameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/formDataInt64Parameter.json deleted file mode 100644 index c00176cb4..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/formDataInt64Parameter.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "id", - "in": "formData", - "description": "username to fetch", - "required": true, - "type": "integer", - "format": "int64" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/formDataStringArrayParameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/formDataStringArrayParameter.json deleted file mode 100644 index 9d06ef465..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/formDataStringArrayParameter.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "user", - "in": "formData", - "description": "user to add to the system", - "required": true, - "type": "array", - "items": { - "type": "string" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/formDataStringParameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/formDataStringParameter.json deleted file mode 100644 index 98d66e63d..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/formDataStringParameter.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "firstName", - "in": "formData", - "description": "users first name", - "required": true, - "type": "string" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/headerInt64ArrayParameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/headerInt64ArrayParameter.json deleted file mode 100644 index 81c8f2f13..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/headerInt64ArrayParameter.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "token", - "in": "header", - "description": "token to be passed as a header", - "required": true, - "type": "array", - "items": { - "type": "integer", - "format": "int64" - }, - "collectionFormat": "csv" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/headerStringArrayParameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/headerStringArrayParameter.json deleted file mode 100644 index d6b134f93..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/headerStringArrayParameter.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "token", - "in": "header", - "description": "token to be passed as a header", - "required": true, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/headerStringParameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/headerStringParameter.json deleted file mode 100644 index d10051ed2..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/headerStringParameter.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "token", - "in": "header", - "description": "token to be passed as a header", - "required": true, - "type": "string" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/pathInt64Parameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/pathInt64Parameter.json deleted file mode 100644 index 47bf2e0b9..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/pathInt64Parameter.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "id", - "in": "path", - "description": "username to fetch", - "required": true, - "type": "integer", - "format": "int64" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/pathStringArrayParameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/pathStringArrayParameter.json deleted file mode 100644 index 6da46aa5d..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/pathStringArrayParameter.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "usernames", - "in": "path", - "description": "usernames to pass", - "required": true, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/pathStringParameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/pathStringParameter.json deleted file mode 100644 index 0ac9c6f07..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/pathStringParameter.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "username", - "in": "path", - "description": "username to fetch", - "required": true, - "type": "string" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/queryInt64ArrayParameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/queryInt64ArrayParameter.json deleted file mode 100644 index 59b557a6f..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/queryInt64ArrayParameter.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "id", - "in": "query", - "description": "ID of the object to fetch", - "required": true, - "type": "array", - "items": { - "type": "integer", - "format": "int64" - }, - "collectionFormat": "csv" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/queryStringParameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/queryStringParameter.json deleted file mode 100644 index fde2d3bad..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/queryStringParameter.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "id", - "in": "query", - "description": "ID of the object to fetch", - "required": true, - "type": "integer", - "format": "int64" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/queryWithComplexParameter.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/queryWithComplexParameter.json deleted file mode 100644 index 61f9e9323..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/parameters/queryWithComplexParameter.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "id", - "in": "query", - "description": "a complex object which should not validate", - "required": true, - "schema": { - "$ref": "Pet" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/resourceWithExamplePayload.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/resourceWithExamplePayload.json deleted file mode 100644 index 90767b6a5..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/resourceWithExamplePayload.json +++ /dev/null @@ -1,114 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.9-abcd", - "title": "Swagger Sample API", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "my.api.com", - "basePath": "/v1", - "schemes": [ - "http", - "https" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json", - "application/xml" - ], - "paths": { - "/pets/{petId}": { - "get": { - "description": "Returns a pet based on ID", - "summary": "Find pet by ID", - "operationId": "getPetsById", - "produces": [ - "application/json", - "text/html" - ], - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet that needs to be fetched", - "required": true, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "$ref": "Pet" - }, - "examples": { - "application/json": { - "id": 9, - "category": { - "name": "domestic" - }, - "name": "monster", - "tags": [ - { - "name": "for sale" - } - ], - "status": "alive" - } - } - }, - "default": { - "description": "error payload", - "schema": { - "$ref": "ErrorModel" - } - } - } - } - } - }, - "definitions": { - "Pet": { - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string", - "example": "cat" - }, - "tag": { - "type": "string", - "example": "for sale" - } - } - }, - "ErrorModel": { - "required": [ "code", "message" ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/resourceWithLinkedDefinitions.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/resourceWithLinkedDefinitions.json deleted file mode 100644 index 52f9ebd9c..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/resourceWithLinkedDefinitions.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.9-abcd", - "title": "Swagger Sample API", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "my.api.com", - "basePath": "/v1", - "schemes": [ - "http", - "https" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json", - "application/xml" - ], - "paths": { - "/pets/{petId}": { - "$ref": "https://raw.githubusercontent.com/reverb/swagger-spec/master/fixtures/v2.0/json/resources/resourceWithLinkedDefinitions_part1.json" - } - }, - "definitions": { - "Pet": { - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "ErrorModel": { - "required": [ "code", "message" ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/resourceWithLinkedDefinitions_part1.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/resourceWithLinkedDefinitions_part1.json deleted file mode 100644 index 5b7f5b9ad..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/resourceWithLinkedDefinitions_part1.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "get": { - "description": "Returns a pet based on ID", - "summary": "Find pet by ID", - "operationId": "getPetsById", - "produces": [ - "application/json", - "text/html" - ], - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet that needs to be fetched", - "required": true, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "$ref": "Pet" - } - }, - "default": { - "description": "error payload", - "schema": { - "$ref": "ErrorModel" - } - } - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/resourceWithRelativeHost.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/resourceWithRelativeHost.json deleted file mode 100644 index 2e16c3a39..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/resourceWithRelativeHost.json +++ /dev/null @@ -1,99 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.9-abcd", - "title": "Swagger Sample API", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "basePath": "/v1", - "schemes": [ - "http", - "https" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json", - "application/xml" - ], - "paths": { - "/pets/{id}": { - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to use", - "required": true, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - } - ], - "get": { - "description": "Returns pets based on ID", - "summary": "Find pets by ID", - "operationId": "getPetsById", - "produces": [ - "application/json", - "text/html" - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "type": "array", - "items": { - "$ref": "Pet" - } - } - }, - "default": { - "description": "error payload", - "schema": { - "$ref": "ErrorModel" - } - } - } - } - } - }, - "definitions": { - "Pet": { - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "ErrorModel": { - "required": [ "code", "message" ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/reusableParameters.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/reusableParameters.json deleted file mode 100644 index 3547c419f..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/reusableParameters.json +++ /dev/null @@ -1,105 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.9-abcd", - "title": "Swagger Sample API", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "my.api.com", - "basePath": "/v1", - "schemes": [ - "http", - "https" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json", - "application/xml" - ], - "paths": { - "/pets/{id}": { - "get": { - "description": "Returns pets based on ID", - "summary": "Find pets by ID", - "operationId": "getPetsById", - "parameters": [ - { "$ref": "#/parameters/skipParam" }, - { "$ref": "#/parameters/limitParam" } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "type": "array", - "items": { - "$ref": "Pet" - } - } - }, - "default": { - "description": "error payload", - "schema": { - "$ref": "ErrorModel" - } - } - } - } - } - }, - "parameters": { - "skipParam": { - "name": "skip", - "in": "query", - "description": "number of items to skip", - "required": true, - "type": "integer", - "format": "int32" - }, - "limitParam": { - "name": "limit", - "in": "query", - "description": "max records to return", - "required": true, - "type": "integer", - "format": "int32" - } - }, - "definitions": { - "Pet": { - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "ErrorModel": { - "required": [ "code", "message" ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/securityExample.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/securityExample.json deleted file mode 100644 index e4c482c4d..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/securityExample.json +++ /dev/null @@ -1,181 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.9-abcd", - "title": "Swagger Sample API", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "basePath": "/v1", - "schemes": [ - "http", - "https" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json", - "application/xml" - ], - "security": [ - { - "githubAccessCode": [ "user", "gist" ] - }, - { - "internalApiKey": [] - } - ], - "paths": { - "/pets/{id}": { - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to use", - "required": true, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - } - ], - "get": { - "description": "Returns pets based on ID", - "summary": "Find pets by ID", - "operationId": "getPetsById", - "security": [ - { - "githubAuth":[ - "user:read", - "user:write" - ] - }, - { - "internalApiKey": [] - } - ], - "produces": [ - "application/json", - "text/html" - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "type": "array", - "items": { - "$ref": "Pet" - } - } - }, - "default": { - "description": "error payload", - "schema": { - "$ref": "ErrorModel" - } - } - } - } - } - }, - "securityDefinitions": { - "githubAccessCode": { - "type": "oauth2", - "scopes": { - "user": "Grants read/write access to profile info only. Note that this scope includes user:email and user:follow.", - "user:email": "Grants read access to a user’s email addresses.", - "user:follow": "Grants access to follow or unfollow other users.", - "public_repo": "Grants read/write access to code, commit statuses, and deployment statuses for public repositories and organizations.", - "repo": "Grants read/write access to code, commit statuses, and deployment statuses for public and private repositories and organizations.", - "repo_deployment": "Grants access to deployment statuses for public and private repositories. This scope is only necessary to grant other users or services access to deployment statuses, without granting access to the code.", - "repo:status": "Grants read/write access to public and private repository commit statuses. This scope is only necessary to grant other users or services access to private repository commit statuses without granting access to the code.", - "delete_repo": "Grants access to delete adminable repositories.", - "notifications": "Grants read access to a user’s notifications. repo also provides this access.", - "gist": "Grants write access to gists.", - "read:repo_hook": "Grants read and ping access to hooks in public or private repositories.", - "write:repo_hook": "Grants read, write, and ping access to hooks in public or private repositories.", - "admin:repo_hook": "Grants read, write, ping, and delete access to hooks in public or private repositories.", - "read:org": "Read-only access to organization, teams, and membership.", - "write:org": "Publicize and unpublicize organization membership.", - "admin:org": "Fully manage organization, teams, and memberships.", - "read:public_key": "List and view details for public keys.", - "write:public_key": "Create, list, and view details for public keys.", - "admin:public_key": "Fully manage public keys." - }, - "flow": "accessCode", - "authorizationUrl": "https://github.com/login/oauth/authorize", - "tokenUrl": "https://github.com/login/oauth/access_token" - }, - "petstoreImplicit": { - "type": "oauth2", - "scopes": { - "user": "Grants read/write access to profile info only. Note that this scope includes user:email and user:follow.", - "user:email": "Grants read access to a user’s email addresses.", - "user:follow": "Grants access to follow or unfollow other users.", - "public_repo": "Grants read/write access to code, commit statuses, and deployment statuses for public repositories and organizations.", - "repo": "Grants read/write access to code, commit statuses, and deployment statuses for public and private repositories and organizations.", - "repo_deployment": "Grants access to deployment statuses for public and private repositories. This scope is only necessary to grant other users or services access to deployment statuses, without granting access to the code.", - "repo:status": "Grants read/write access to public and private repository commit statuses. This scope is only necessary to grant other users or services access to private repository commit statuses without granting access to the code.", - "delete_repo": "Grants access to delete adminable repositories.", - "notifications": "Grants read access to a user’s notifications. repo also provides this access.", - "gist": "Grants write access to gists.", - "read:repo_hook": "Grants read and ping access to hooks in public or private repositories.", - "write:repo_hook": "Grants read, write, and ping access to hooks in public or private repositories.", - "admin:repo_hook": "Grants read, write, ping, and delete access to hooks in public or private repositories.", - "read:org": "Read-only access to organization, teams, and membership.", - "write:org": "Publicize and unpublicize organization membership.", - "admin:org": "Fully manage organization, teams, and memberships.", - "read:public_key": "List and view details for public keys.", - "write:public_key": "Create, list, and view details for public keys.", - "admin:public_key": "Fully manage public keys." - }, - "flow": "implicit", - "authorizationUrl": "http://petstore.swagger.wordnik.com/oauth/dialog" - }, - "internalApiKey": { - "type": "apiKey", - "in": "header", - "name": "api_key" - } - }, - "definitions": { - "Pet": { - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "ErrorModel": { - "required": [ - "code", - "message" - ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/stringPathParamResource.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/stringPathParamResource.json deleted file mode 100644 index a438a08ea..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/stringPathParamResource.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.9-abcd", - "title": "Swagger Sample API", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "my.api.com", - "basePath": "/v1", - "schemes": [ - "http", - "https" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json", - "application/xml" - ], - "paths": { - "/pets/{petId}": { - "get": { - "description": "Returns a pet based on ID", - "summary": "Find pet by ID", - "operationId": "getPetsById", - "produces": [ - "application/json", - "text/html" - ], - "parameters": [ - { - "name": "petId", - "in": "path", - "description": "ID of pet that needs to be fetched", - "required": true, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "$ref": "Pet" - } - }, - "default": { - "description": "error payload", - "schema": { - "$ref": "ErrorModel" - } - } - } - } - } - }, - "definitions": { - "Pet": { - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "ErrorModel": { - "required": [ "code", "message" ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/taggedResource.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/taggedResource.json deleted file mode 100644 index 19394c70d..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/taggedResource.json +++ /dev/null @@ -1,112 +0,0 @@ -{ - "swagger": "2.0", - "x-reverb": { - "addAnythingYouWant": true - }, - "info": { - "x-reverb-info": "this is an example", - "version": "1.0.9-abcd", - "title": "Swagger Sample API", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "my.api.com", - "basePath": "/v1", - "schemes": [ - "http", - "https" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json", - "application/xml" - ], - "tags": [ - { - "name": "pets" - } - ], - "paths": { - "x-reverb-path-info": "vendor info", - "/pets": { - "x-vendor-method": {}, - "get": { - "x-vendor-operation-property": {}, - "description": "Returns a pet based on ID", - "summary": "Find pet by ID", - "operationId": "getPetsById", - "produces": [ - "application/json", - "text/html" - ], - "parameters": [ - { - "x-vendor-parameter-property": {}, - "name": "petId", - "in": "path", - "description": "ID of pet that needs to be fetched", - "required": true, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - } - ], - "responses": { - "x-vendor-operation-response-property": {}, - "200": { - "description": "pet response", - "schema": { - "$ref": "Pet" - } - }, - "default": { - "description": "error payload", - "schema": { - "$ref": "ErrorModel" - } - } - } - } - } - }, - "definitions": { - "Pet": { - "x-vendor-model-property": {}, - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "ErrorModel": { - "required": [ "code", "message" ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/resources/vendorExtensionExamples.json b/vendor/github.com/go-openapi/loads/fixtures/json/resources/vendorExtensionExamples.json deleted file mode 100644 index 267ce5399..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/resources/vendorExtensionExamples.json +++ /dev/null @@ -1,107 +0,0 @@ -{ - "swagger": "2.0", - "x-reverb": { - "addAnythingYouWant": true - }, - "info": { - "x-reverb-info": "this is an example", - "version": "1.0.9-abcd", - "title": "Swagger Sample API", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "my.api.com", - "basePath": "/v1", - "schemes": [ - "http", - "https" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json", - "application/xml" - ], - "paths": { - "x-reverb-path-info": "vendor info", - "/pets": { - "x-vendor-method": {}, - "get": { - "x-vendor-operation-property": {}, - "description": "Returns a pet based on ID", - "summary": "Find pet by ID", - "operationId": "getPetsById", - "produces": [ - "application/json", - "text/html" - ], - "parameters": [ - { - "x-vendor-parameter-property": {}, - "name": "petId", - "in": "path", - "description": "ID of pet that needs to be fetched", - "required": true, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - } - ], - "responses": { - "x-vendor-operation-response-property": {}, - "200": { - "description": "pet response", - "schema": { - "$ref": "Pet" - } - }, - "default": { - "description": "error payload", - "schema": { - "$ref": "ErrorModel" - } - } - } - } - } - }, - "definitions": { - "Pet": { - "x-vendor-model-property": {}, - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "ErrorModel": { - "required": [ "code", "message" ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/responses/complexArrayResponse.json b/vendor/github.com/go-openapi/loads/fixtures/json/responses/complexArrayResponse.json deleted file mode 100644 index 5d2ce79ee..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/responses/complexArrayResponse.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "description": "A complex object array response", - "schema": { - "type": "array", - "items": { - "$ref": "VeryComplexType" - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/responses/dateTimeResponse.json b/vendor/github.com/go-openapi/loads/fixtures/json/responses/dateTimeResponse.json deleted file mode 100644 index 77fe8d442..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/responses/dateTimeResponse.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "description": "A date-time response", - "schema": { - "type": "string", - "format": "date-time" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/responses/int32Response.json b/vendor/github.com/go-openapi/loads/fixtures/json/responses/int32Response.json deleted file mode 100644 index b9470c8f2..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/responses/int32Response.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "description": "A simple string response", - "schema": { - "type": "integer", - "format": "int32" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/responses/int64Response.json b/vendor/github.com/go-openapi/loads/fixtures/json/responses/int64Response.json deleted file mode 100644 index 16a4d1c1c..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/responses/int64Response.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "description": "A simple string response", - "schema": { - "type": "integer", - "format": "int64" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/responses/multipleResponses.json b/vendor/github.com/go-openapi/loads/fixtures/json/responses/multipleResponses.json deleted file mode 100644 index b7c51544e..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/responses/multipleResponses.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "200": { - "description": "simple string response", - "schema": { - "type": "string" - } - }, - "201": { - "description": "object created" - }, - "default": { - "description": "oops", - "schema": { - "type": "integer", - "format": "int32" - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/responses/stringArrayResponse.json b/vendor/github.com/go-openapi/loads/fixtures/json/responses/stringArrayResponse.json deleted file mode 100644 index 4640ea04b..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/responses/stringArrayResponse.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "description": "A string array response", - "schema": { - "type": "array", - "items": { - "type": "string" - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/responses/stringResponse.json b/vendor/github.com/go-openapi/loads/fixtures/json/responses/stringResponse.json deleted file mode 100644 index f79402737..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/responses/stringResponse.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "description": "A simple string response", - "schema": { - "type": "string" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/responses/stringResponseWithHeader.json b/vendor/github.com/go-openapi/loads/fixtures/json/responses/stringResponseWithHeader.json deleted file mode 100644 index 57a5f80b4..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/responses/stringResponseWithHeader.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "description": "A simple string response", - "schema": { - "type": "string" - }, - "headers": { - "is-dog": {"type": "boolean"}, - "is-cat": {"type": "boolean"} - } -} diff --git a/vendor/github.com/go-openapi/loads/fixtures/json/responses/voidResponse.json b/vendor/github.com/go-openapi/loads/fixtures/json/responses/voidResponse.json deleted file mode 100644 index a7edcadb3..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/json/responses/voidResponse.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "description": "object created" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/.gitkeep b/vendor/github.com/go-openapi/loads/fixtures/yaml/.gitkeep deleted file mode 100644 index e69de29bb..000000000 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithArrayRef.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithArrayRef.yaml deleted file mode 100644 index b32a35901..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithArrayRef.yaml +++ /dev/null @@ -1,5 +0,0 @@ -required: - - id -properties: - id: {type: integer, format: int64} - children: {type: array, items: {$ref: Person}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithComposition.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithComposition.yaml deleted file mode 100644 index f0ea5e80f..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithComposition.yaml +++ /dev/null @@ -1,5 +0,0 @@ -definitions: - Cat: {description: 'A representation of a cat', allOf: [{$ref: '#/models/Pet'}, {properties: {huntingSkill: {type: string, description: 'The measured skill for hunting', default: lazy, enum: [clueless, lazy, adventerous, aggressive]}}, required: [huntingSkill]}]} - Dog: {description: 'A representation of a dog', allOf: [{$ref: '#/models/Pet'}, {properties: {packSize: {type: integer, format: int32, description: 'the size of the pack the dog is from', default: 0}}, required: [name, packSize]}]} - Fish: {description: 'A representation of a fish', allOf: [{$ref: '#/models/Pet'}, {properties: {fins: {type: integer, format: int32, description: 'count of fins'}}, required: [fins]}]} - Pet: {discriminator: petType, properties: {name: {type: string}, petType: {type: string}}, required: [name, petType]} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithDateTimeMap.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithDateTimeMap.yaml deleted file mode 100644 index 653cbd182..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithDateTimeMap.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'true' -additionalProperties: - type: string - format: date-time diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithExamples.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithExamples.yaml deleted file mode 100644 index 0252ec176..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithExamples.yaml +++ /dev/null @@ -1,3 +0,0 @@ -definitions: - Pet: {properties: {name: {type: string}}, required: [name]} - Dog: {properties: {id: {type: integer, format: int64}, name: {type: string}}, required: [name]} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithInt32Map.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithInt32Map.yaml deleted file mode 100644 index 88ab02447..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithInt32Map.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'This is a Map[String, Integer]' -additionalProperties: - type: integer - format: int32 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithInt64Map.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithInt64Map.yaml deleted file mode 100644 index 16c790e42..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithInt64Map.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'true' -additionalProperties: - type: integer - format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithMultipleProperties.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithMultipleProperties.yaml deleted file mode 100644 index f69d27ef2..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithMultipleProperties.yaml +++ /dev/null @@ -1,14 +0,0 @@ -description: 'true' -properties: - booleanValue: {type: boolean} - byteValue: {type: string, format: byte} - dateTimeValue: {type: string, format: date-time} - int32Value: {type: integer, format: int32} - int64Value: {type: integer, format: int64} - stringValue: {type: string} - booleanArrayValue: {type: array, items: {type: boolean}} - byteArrayValue: {type: array, items: {type: string, format: byte}} - dateTimeArrayValue: {type: array, items: {type: string, format: date-time}} - int32ArrayValue: {type: array, items: {type: integer, format: int32}} - int64ArrayValue: {type: array, items: {type: integer, format: int64}} - stringArrayValue: {type: array, items: {type: string}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithObjectMap.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithObjectMap.yaml deleted file mode 100644 index e712e0f22..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithObjectMap.yaml +++ /dev/null @@ -1,9 +0,0 @@ -description: "This is a Map[String, { id: Long, name: String}]" -additionalProperties: - type: "object" - properties: - id: - type: "integer" - format: "int64" - name: - type: "string" diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithPrimitiveArray.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithPrimitiveArray.yaml deleted file mode 100644 index 0837bad52..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithPrimitiveArray.yaml +++ /dev/null @@ -1,5 +0,0 @@ -required: - - id -properties: - id: {type: integer, format: int64} - childrensAges: {type: array, items: {type: integer, format: int32}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithStringProperty.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithStringProperty.yaml deleted file mode 100644 index a17d21e5a..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithStringProperty.yaml +++ /dev/null @@ -1,3 +0,0 @@ -description: 'true' -properties: - name: {type: string} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithXmlAttributes.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithXmlAttributes.yaml deleted file mode 100644 index 2176983f8..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/modelWithXmlAttributes.yaml +++ /dev/null @@ -1,6 +0,0 @@ -description: 'this model serves xml and json structures' -xml: - name: XMLModel -properties: - id: {type: integer, format: int64, xml: {attribute: true, namespace: ns1, prefix: urn1}} - items: {type: array, items: {type: string}, xml: {wrapped: true}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/models.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/models.yaml deleted file mode 100644 index 71f8efeb4..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/models.yaml +++ /dev/null @@ -1,2 +0,0 @@ -definitions: - Pet: {properties: {name: {type: string}}, required: [name]} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/multipleModels.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/multipleModels.yaml deleted file mode 100644 index 0252ec176..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/multipleModels.yaml +++ /dev/null @@ -1,3 +0,0 @@ -definitions: - Pet: {properties: {name: {type: string}}, required: [name]} - Dog: {properties: {id: {type: integer, format: int64}, name: {type: string}}, required: [name]} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithBooleanArray.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithBooleanArray.yaml deleted file mode 100644 index aa02d0e74..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithBooleanArray.yaml +++ /dev/null @@ -1,3 +0,0 @@ -type: array -items: - type: boolean diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithByteArray.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithByteArray.yaml deleted file mode 100644 index f31b35036..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithByteArray.yaml +++ /dev/null @@ -1,4 +0,0 @@ -type: array -items: - type: string - format: byte diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithComplexArray.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithComplexArray.yaml deleted file mode 100644 index 69e0b1765..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithComplexArray.yaml +++ /dev/null @@ -1,3 +0,0 @@ -type: array -items: - $ref: ComplexType diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithDateTimeArray.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithDateTimeArray.yaml deleted file mode 100644 index 6efef25d8..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithDateTimeArray.yaml +++ /dev/null @@ -1,4 +0,0 @@ -type: array -items: - type: string - format: date-time diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithInt32Array.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithInt32Array.yaml deleted file mode 100644 index 26fd271b0..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithInt32Array.yaml +++ /dev/null @@ -1,4 +0,0 @@ -type: array -items: - type: integer - format: int32 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithInt64Array.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithInt64Array.yaml deleted file mode 100644 index e800895eb..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithInt64Array.yaml +++ /dev/null @@ -1,4 +0,0 @@ -type: array -items: - type: integer - format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithRef.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithRef.yaml deleted file mode 100644 index d78956949..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithRef.yaml +++ /dev/null @@ -1,3 +0,0 @@ -$ref: Foo -description: 'a boolean' -readOnly: true diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithStringArray.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithStringArray.yaml deleted file mode 100644 index 3a9108235..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/propertyWithStringArray.yaml +++ /dev/null @@ -1,3 +0,0 @@ -type: array -items: - type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleBooleanProperty.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleBooleanProperty.yaml deleted file mode 100644 index 9d1e27382..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleBooleanProperty.yaml +++ /dev/null @@ -1,3 +0,0 @@ -type: boolean -description: 'a boolean' -readOnly: true diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleByteProperty.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleByteProperty.yaml deleted file mode 100644 index 6af2139f9..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleByteProperty.yaml +++ /dev/null @@ -1,2 +0,0 @@ -type: string -format: byte diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleDateTimeProperty.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleDateTimeProperty.yaml deleted file mode 100644 index 407b1d7e8..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleDateTimeProperty.yaml +++ /dev/null @@ -1,2 +0,0 @@ -type: string -format: date-time diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleInt32Property.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleInt32Property.yaml deleted file mode 100644 index 8ed513dba..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleInt32Property.yaml +++ /dev/null @@ -1,2 +0,0 @@ -type: integer -format: int32 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleInt64Property.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleInt64Property.yaml deleted file mode 100644 index 69f359f3f..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleInt64Property.yaml +++ /dev/null @@ -1,2 +0,0 @@ -type: integer -format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleStringProperty.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleStringProperty.yaml deleted file mode 100644 index 5c21d88b9..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/models/properties/simpleStringProperty.yaml +++ /dev/null @@ -1 +0,0 @@ -type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/cascadingSchemes.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/cascadingSchemes.yaml deleted file mode 100644 index d10802774..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/cascadingSchemes.yaml +++ /dev/null @@ -1,23 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - '/pets/{petId}': {get: {description: 'Returns a pet based on ID', summary: 'Find pet by ID', operationId: getPetsById, produces: [application/json, text/html], parameters: [{name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: array, items: {type: string}, collectionFormat: csv}], responses: {'200': {description: 'pet response', schema: {$ref: Pet}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}, schemes: [https]}} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/commonParameters.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/commonParameters.yaml deleted file mode 100644 index 9851b7448..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/commonParameters.yaml +++ /dev/null @@ -1,23 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - '/pets/{id}': {parameters: [{name: id, in: path, description: 'ID of pet to use', required: true, type: array, items: {type: string}, collectionFormat: csv}], get: {description: 'Returns pets based on ID', summary: 'Find pets by ID', operationId: getPetsById, produces: [application/json, text/html], responses: {'200': {description: 'pet response', schema: {type: array, items: {$ref: Pet}}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/multipleMimeTypes.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/multipleMimeTypes.yaml deleted file mode 100644 index 23bdc2d2a..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/multipleMimeTypes.yaml +++ /dev/null @@ -1,32 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - 'text/plain; charset=utf-8' - - application/json - - application/vnd.github+json - - application/vnd.github.v3+json - - application/vnd.github.v3.raw+json - - application/vnd.github.v3.text+json - - application/vnd.github.v3.html+json - - application/vnd.github.v3.full+json - - application/vnd.github.v3.diff - - application/vnd.github.v3.patch -produces: - - application/json - - application/xml -paths: - '/pets/{id}': {parameters: [{name: id, in: path, description: 'ID of pet to use', required: true, type: array, items: {type: string}, collectionFormat: csv}], get: {description: 'Returns pets based on ID', summary: 'Find pets by ID', operationId: getPetsById, produces: [application/json, text/html], responses: {'200': {description: 'pet response', schema: {type: array, items: {$ref: Pet}}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/operations/operationWithTags.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/operations/operationWithTags.yaml deleted file mode 100644 index a3c85b26a..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/operations/operationWithTags.yaml +++ /dev/null @@ -1,14 +0,0 @@ -description: 'Returns a pet based on ID' -summary: 'Find pet by ID' -operationId: getPetsById -tags: - - foo - - bar -produces: - - application/json - - text/html -parameters: - - {name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: integer, format: int64} -responses: - '200': {description: 'a pet to be returned', schema: {$ref: Pet}} - default: {description: 'Unexpected error', schema: {$ref: ErrorModel}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/operations/stringPathAndBoolQueryParamResource.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/operations/stringPathAndBoolQueryParamResource.yaml deleted file mode 100644 index a00b8c469..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/operations/stringPathAndBoolQueryParamResource.yaml +++ /dev/null @@ -1,12 +0,0 @@ -description: 'Returns a pet based on ID' -summary: 'Find pet by ID' -operationId: getPetsById -produces: - - application/json - - text/html -parameters: - - {name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: integer, format: int64} - - {name: includeDetails, in: query, description: 'include details in response', required: true, type: boolean} -responses: - '200': {description: 'a pet to be returned', schema: {$ref: Pet}} - default: {description: 'Unexpected error', schema: {$ref: ErrorModel}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/operations/stringPathParamResource.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/operations/stringPathParamResource.yaml deleted file mode 100644 index 8c46cc7ee..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/operations/stringPathParamResource.yaml +++ /dev/null @@ -1,12 +0,0 @@ -description: 'Returns a pet based on ID' -summary: 'Find pet by ID' -operationId: getPetsById -produces: - - application/json - - text/html -parameters: - - {name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: integer, format: int64} -responses: - '200': {description: fun, schema: {$ref: Pet}} - '400': {description: 'Invalid ID supplied <= this is purely for documentation', schema: {$ref: ErrorModel}} - default: {description: 'Unexpected error', schema: {$ref: ErrorModel}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/bodyComplexArrayParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/bodyComplexArrayParameter.yaml deleted file mode 100644 index 511f8dc2b..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/bodyComplexArrayParameter.yaml +++ /dev/null @@ -1,8 +0,0 @@ -name: user -in: body -description: 'user to add to the system' -required: true -schema: - type: array - items: {type: string} - format: csv diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/bodyComplexParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/bodyComplexParameter.yaml deleted file mode 100644 index 13f8fd171..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/bodyComplexParameter.yaml +++ /dev/null @@ -1,6 +0,0 @@ -name: user -in: body -description: 'user to add to the system' -required: true -schema: - $ref: User diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/bodyInt64Parameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/bodyInt64Parameter.yaml deleted file mode 100644 index a270d94cb..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/bodyInt64Parameter.yaml +++ /dev/null @@ -1,7 +0,0 @@ -name: id -in: body -description: 'id to add' -required: true -schema: - type: integer - format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/bodyStringArrayParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/bodyStringArrayParameter.yaml deleted file mode 100644 index 7d88b10dc..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/bodyStringArrayParameter.yaml +++ /dev/null @@ -1,7 +0,0 @@ -name: user -in: body -description: 'user to add to the system' -required: true -schema: - type: array - items: {type: string} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/bodyStringParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/bodyStringParameter.yaml deleted file mode 100644 index 7fe9dbd1e..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/bodyStringParameter.yaml +++ /dev/null @@ -1,6 +0,0 @@ -name: user -in: body -description: 'user to add to the system' -required: true -schema: - type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/formDataComplexParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/formDataComplexParameter.yaml deleted file mode 100644 index b49dd9e3d..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/formDataComplexParameter.yaml +++ /dev/null @@ -1,5 +0,0 @@ -name: firstName -in: formData -description: 'users first name' -required: true -$ref: Nothing diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/formDataInt64Parameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/formDataInt64Parameter.yaml deleted file mode 100644 index 0faaa7f62..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/formDataInt64Parameter.yaml +++ /dev/null @@ -1,6 +0,0 @@ -name: id -in: formData -description: 'username to fetch' -required: true -type: integer -format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/formDataStringArrayParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/formDataStringArrayParameter.yaml deleted file mode 100644 index f6534662a..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/formDataStringArrayParameter.yaml +++ /dev/null @@ -1,7 +0,0 @@ -name: user -in: formData -description: 'user to add to the system' -required: true -type: array -items: - type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/formDataStringParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/formDataStringParameter.yaml deleted file mode 100644 index 43411cf04..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/formDataStringParameter.yaml +++ /dev/null @@ -1,5 +0,0 @@ -name: firstName -in: formData -description: 'users first name' -required: true -type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/headerInt64ArrayParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/headerInt64ArrayParameter.yaml deleted file mode 100644 index 87ec99cab..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/headerInt64ArrayParameter.yaml +++ /dev/null @@ -1,9 +0,0 @@ -name: token -in: header -description: 'token to be passed as a header' -required: true -type: array -items: - type: integer - format: int64 -collectionFormat: csv diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/headerStringArrayParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/headerStringArrayParameter.yaml deleted file mode 100644 index 70e0a0a68..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/headerStringArrayParameter.yaml +++ /dev/null @@ -1,8 +0,0 @@ -name: token -in: header -description: 'token to be passed as a header' -required: true -type: array -items: - type: string -collectionFormat: csv diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/headerStringParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/headerStringParameter.yaml deleted file mode 100644 index ac99c2f62..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/headerStringParameter.yaml +++ /dev/null @@ -1,5 +0,0 @@ -name: token -in: header -description: 'token to be passed as a header' -required: true -type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/pathInt64Parameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/pathInt64Parameter.yaml deleted file mode 100644 index 3bd860aac..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/pathInt64Parameter.yaml +++ /dev/null @@ -1,6 +0,0 @@ -name: id -in: path -description: 'username to fetch' -required: true -type: integer -format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/pathStringArrayParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/pathStringArrayParameter.yaml deleted file mode 100644 index ebb24a7e2..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/pathStringArrayParameter.yaml +++ /dev/null @@ -1,8 +0,0 @@ -name: usernames -in: path -description: 'usernames to pass' -required: true -type: array -items: - type: string -collectionFormat: csv diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/pathStringParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/pathStringParameter.yaml deleted file mode 100644 index 2cb4fb2ee..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/pathStringParameter.yaml +++ /dev/null @@ -1,5 +0,0 @@ -name: username -in: path -description: 'username to fetch' -required: true -type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/queryInt64ArrayParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/queryInt64ArrayParameter.yaml deleted file mode 100644 index 453e24f5d..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/queryInt64ArrayParameter.yaml +++ /dev/null @@ -1,9 +0,0 @@ -name: id -in: query -description: 'ID of the object to fetch' -required: true -type: array -items: - type: integer - format: int64 -collectionFormat: csv diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/queryStringParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/queryStringParameter.yaml deleted file mode 100644 index e1df68530..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/queryStringParameter.yaml +++ /dev/null @@ -1,6 +0,0 @@ -name: id -in: query -description: 'ID of the object to fetch' -required: true -type: integer -format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/queryWithComplexParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/queryWithComplexParameter.yaml deleted file mode 100644 index 80bc7951b..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/parameters/queryWithComplexParameter.yaml +++ /dev/null @@ -1,6 +0,0 @@ -name: id -in: query -description: 'a complex object which should not validate' -required: true -schema: - $ref: Pet diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/resourceWithExamplePayload.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/resourceWithExamplePayload.yaml deleted file mode 100644 index 9828d9605..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/resourceWithExamplePayload.yaml +++ /dev/null @@ -1,23 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - '/pets/{petId}': {get: {description: 'Returns a pet based on ID', summary: 'Find pet by ID', operationId: getPetsById, produces: [application/json, text/html], parameters: [{name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: array, items: {type: string}, collectionFormat: csv}], responses: {'200': {description: 'pet response', schema: {$ref: Pet}, examples: {application/json: {id: 9, category: {name: domestic}, name: monster, tags: [{name: 'for sale'}], status: alive}}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -definitions: - Pet: {required: [name], properties: {name: {type: string, example: cat}, tag: {type: string, example: 'for sale'}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/resourceWithLinkedDefinitions.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/resourceWithLinkedDefinitions.yaml deleted file mode 100644 index b9b00c47f..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/resourceWithLinkedDefinitions.yaml +++ /dev/null @@ -1,23 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - '/pets/{petId}': {$ref: 'https://raw.githubusercontent.com/reverb/swagger-spec/master/fixtures/v2.0/json/resources/resourceWithLinkedDefinitions_part1.json'} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/resourceWithLinkedDefinitions_part1.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/resourceWithLinkedDefinitions_part1.yaml deleted file mode 100644 index 7d358fbf1..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/resourceWithLinkedDefinitions_part1.yaml +++ /dev/null @@ -1,7 +0,0 @@ -get: - description: 'Returns a pet based on ID' - summary: 'Find pet by ID' - operationId: getPetsById - produces: [application/json, text/html] - parameters: [{name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: array, items: {type: string}, collectionFormat: csv}] - responses: {'200': {description: 'pet response', schema: {$ref: Pet}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/resourceWithRelativeHost.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/resourceWithRelativeHost.yaml deleted file mode 100644 index 744aa72e9..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/resourceWithRelativeHost.yaml +++ /dev/null @@ -1,22 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - '/pets/{id}': {parameters: [{name: id, in: path, description: 'ID of pet to use', required: true, type: array, items: {type: string}, collectionFormat: csv}], get: {description: 'Returns pets based on ID', summary: 'Find pets by ID', operationId: getPetsById, produces: [application/json, text/html], responses: {'200': {description: 'pet response', schema: {type: array, items: {$ref: Pet}}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/reusableParameters.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/reusableParameters.yaml deleted file mode 100644 index 1d258d082..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/reusableParameters.yaml +++ /dev/null @@ -1,26 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - '/pets/{id}': {get: {description: 'Returns pets based on ID', summary: 'Find pets by ID', operationId: getPetsById, parameters: [{$ref: '#/parameters/skipParam'}, {$ref: '#/parameters/limitParam'}], responses: {'200': {description: 'pet response', schema: {type: array, items: {$ref: Pet}}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -parameters: - skipParam: {name: skip, in: query, description: 'number of items to skip', required: true, type: integer, format: int32} - limitParam: {name: limit, in: query, description: 'max records to return', required: true, type: integer, format: int32} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/securityExample.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/securityExample.yaml deleted file mode 100644 index 007d26db4..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/securityExample.yaml +++ /dev/null @@ -1,29 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -security: - - {githubAccessCode: [user, gist]} - - {internalApiKey: []} -paths: - '/pets/{id}': {parameters: [{name: id, in: path, description: 'ID of pet to use', required: true, type: array, items: {type: string}, collectionFormat: csv}], get: {description: 'Returns pets based on ID', summary: 'Find pets by ID', operationId: getPetsById, security: [{githubAuth: ['user:read', 'user:write']}, {internalApiKey: []}], produces: [application/json, text/html], responses: {'200': {description: 'pet response', schema: {type: array, items: {$ref: Pet}}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -securityDefinitions: - githubAccessCode: {type: oauth2, scopes: {user: 'Grants read/write access to profile info only. Note that this scope includes user:email and user:follow.', 'user:email': 'Grants read access to a user’s email addresses.', 'user:follow': 'Grants access to follow or unfollow other users.', public_repo: 'Grants read/write access to code, commit statuses, and deployment statuses for public repositories and organizations.', repo: 'Grants read/write access to code, commit statuses, and deployment statuses for public and private repositories and organizations.', repo_deployment: 'Grants access to deployment statuses for public and private repositories. This scope is only necessary to grant other users or services access to deployment statuses, without granting access to the code.', 'repo:status': 'Grants read/write access to public and private repository commit statuses. This scope is only necessary to grant other users or services access to private repository commit statuses without granting access to the code.', delete_repo: 'Grants access to delete adminable repositories.', notifications: 'Grants read access to a user’s notifications. repo also provides this access.', gist: 'Grants write access to gists.', 'read:repo_hook': 'Grants read and ping access to hooks in public or private repositories.', 'write:repo_hook': 'Grants read, write, and ping access to hooks in public or private repositories.', 'admin:repo_hook': 'Grants read, write, ping, and delete access to hooks in public or private repositories.', 'read:org': 'Read-only access to organization, teams, and membership.', 'write:org': 'Publicize and unpublicize organization membership.', 'admin:org': 'Fully manage organization, teams, and memberships.', 'read:public_key': 'List and view details for public keys.', 'write:public_key': 'Create, list, and view details for public keys.', 'admin:public_key': 'Fully manage public keys.'}, flow: accessCode, authorizationUrl: 'https://github.com/login/oauth/authorize', tokenUrl: 'https://github.com/login/oauth/access_token'} - petstoreImplicit: {type: oauth2, scopes: {user: 'Grants read/write access to profile info only. Note that this scope includes user:email and user:follow.', 'user:email': 'Grants read access to a user’s email addresses.', 'user:follow': 'Grants access to follow or unfollow other users.', public_repo: 'Grants read/write access to code, commit statuses, and deployment statuses for public repositories and organizations.', repo: 'Grants read/write access to code, commit statuses, and deployment statuses for public and private repositories and organizations.', repo_deployment: 'Grants access to deployment statuses for public and private repositories. This scope is only necessary to grant other users or services access to deployment statuses, without granting access to the code.', 'repo:status': 'Grants read/write access to public and private repository commit statuses. This scope is only necessary to grant other users or services access to private repository commit statuses without granting access to the code.', delete_repo: 'Grants access to delete adminable repositories.', notifications: 'Grants read access to a user’s notifications. repo also provides this access.', gist: 'Grants write access to gists.', 'read:repo_hook': 'Grants read and ping access to hooks in public or private repositories.', 'write:repo_hook': 'Grants read, write, and ping access to hooks in public or private repositories.', 'admin:repo_hook': 'Grants read, write, ping, and delete access to hooks in public or private repositories.', 'read:org': 'Read-only access to organization, teams, and membership.', 'write:org': 'Publicize and unpublicize organization membership.', 'admin:org': 'Fully manage organization, teams, and memberships.', 'read:public_key': 'List and view details for public keys.', 'write:public_key': 'Create, list, and view details for public keys.', 'admin:public_key': 'Fully manage public keys.'}, flow: implicit, authorizationUrl: 'http://petstore.swagger.wordnik.com/oauth/dialog'} - internalApiKey: {type: apiKey, in: header, name: api_key} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/stringPathParamResource.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/stringPathParamResource.yaml deleted file mode 100644 index a4a83fea0..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/stringPathParamResource.yaml +++ /dev/null @@ -1,23 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - '/pets/{petId}': {get: {description: 'Returns a pet based on ID', summary: 'Find pet by ID', operationId: getPetsById, produces: [application/json, text/html], parameters: [{name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: array, items: {type: string}, collectionFormat: csv}], responses: {'200': {description: 'pet response', schema: {$ref: Pet}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/taggedResource.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/taggedResource.yaml deleted file mode 100644 index 1b8620e52..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/taggedResource.yaml +++ /dev/null @@ -1,29 +0,0 @@ -swagger: '2.0' -x-reverb: - addAnythingYouWant: true -info: - x-reverb-info: 'this is an example' - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -tags: - - {name: pets} -paths: - x-reverb-path-info: 'vendor info' - /pets: {x-vendor-method: {}, get: {x-vendor-operation-property: {}, description: 'Returns a pet based on ID', summary: 'Find pet by ID', operationId: getPetsById, produces: [application/json, text/html], parameters: [{x-vendor-parameter-property: {}, name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: array, items: {type: string}, collectionFormat: csv}], responses: {'200': {description: 'pet response', schema: {$ref: Pet}}, x-vendor-operation-response-property: {}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -definitions: - Pet: {x-vendor-model-property: {}, required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/vendorExtensionExamples.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/vendorExtensionExamples.yaml deleted file mode 100644 index 59bba0f3d..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/resources/vendorExtensionExamples.yaml +++ /dev/null @@ -1,27 +0,0 @@ -swagger: '2.0' -x-reverb: - addAnythingYouWant: true -info: - x-reverb-info: 'this is an example' - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - x-reverb-path-info: 'vendor info' - /pets: {x-vendor-method: {}, get: {x-vendor-operation-property: {}, description: 'Returns a pet based on ID', summary: 'Find pet by ID', operationId: getPetsById, produces: [application/json, text/html], parameters: [{x-vendor-parameter-property: {}, name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: array, items: {type: string}, collectionFormat: csv}], responses: {'200': {description: 'pet response', schema: {$ref: Pet}}, x-vendor-operation-response-property: {}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -definitions: - Pet: {x-vendor-model-property: {}, required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/complexArrayResponse.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/complexArrayResponse.yaml deleted file mode 100644 index bc5ce9534..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/complexArrayResponse.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'A complex object array response' -schema: - type: array - items: {$ref: VeryComplexType} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/dateTimeResponse.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/dateTimeResponse.yaml deleted file mode 100644 index 9bc3e8043..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/dateTimeResponse.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'A date-time response' -schema: - type: string - format: date-time diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/int32Response.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/int32Response.yaml deleted file mode 100644 index e4456c9fe..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/int32Response.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'A simple string response' -schema: - type: integer - format: int32 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/int64Response.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/int64Response.yaml deleted file mode 100644 index ca58b2a5f..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/int64Response.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'A simple string response' -schema: - type: integer - format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/multipleResponses.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/multipleResponses.yaml deleted file mode 100644 index 4cd1312c5..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/multipleResponses.yaml +++ /dev/null @@ -1,8 +0,0 @@ -'200': - description: 'simple string response' - schema: {type: string} -'201': - description: 'object created' -default: - description: oops - schema: {type: integer, format: int32} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/stringArrayResponse.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/stringArrayResponse.yaml deleted file mode 100644 index cab5fad8c..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/stringArrayResponse.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'A string array response' -schema: - type: array - items: {type: string} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/stringResponse.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/stringResponse.yaml deleted file mode 100644 index 61a25e510..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/stringResponse.yaml +++ /dev/null @@ -1,3 +0,0 @@ -description: 'A simple string response' -schema: - type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/stringResponseWithHeader.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/stringResponseWithHeader.yaml deleted file mode 100644 index 77c2c7561..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/stringResponseWithHeader.yaml +++ /dev/null @@ -1,6 +0,0 @@ -description: 'A simple string response' -schema: - type: string -headers: - is-dog: {type: boolean} - is-cat: {type: boolean} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/voidResponse.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/voidResponse.yaml deleted file mode 100644 index f2aa5e124..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/responses/voidResponse.yaml +++ /dev/null @@ -1 +0,0 @@ -description: 'object created' diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/swagger/1/2/3/4/swagger.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/swagger/1/2/3/4/swagger.yaml deleted file mode 100644 index dcaf3ff80..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/swagger/1/2/3/4/swagger.yaml +++ /dev/null @@ -1,42 +0,0 @@ -swagger: '2.0' -info: - title: Something - contact: - name: Somebody - url: https://url.com - email: email@url.com - description: Something - version: v1 -host: security.sonusnet.com -schemes: -- https -- http -basePath: /api -produces: -- application/json -- plain/text - -paths: - /whatnot: - get: - description: Get something - responses: - 200: - description: The something - schema: - $ref: '#/definitions/Something' - 500: - description: Oops - -definitions: - Something: - description: A collection of service events - type: object - properties: - page: - $ref: '../../../../shared/definitions/page.yaml#/definitions/Page' - something: - #type: array - #description: An array of something - #items: - $ref: '../../../../shared/something.yaml#/definitions/Something' diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/swagger/shared/definitions/page.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/swagger/shared/definitions/page.yaml deleted file mode 100644 index 29355d42d..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/swagger/shared/definitions/page.yaml +++ /dev/null @@ -1,18 +0,0 @@ -definitions: - Page: - description: A description of a paged result - type: object - properties: - page: - type: integer - description: the page that was requested - pages: - type: integer - description: the total number of pages available - total_items: - type: integer - description: the total number of items available - format: int64 - page_items: - type: integer - description: the number of items per page requested diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/swagger/shared/something.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/swagger/shared/something.yaml deleted file mode 100644 index f5f2e3919..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/swagger/shared/something.yaml +++ /dev/null @@ -1,44 +0,0 @@ -swagger: '2.0' -info: - title: Something definitions - contact: - name: Somebody - url: https://url.com - email: email@url.com - description: Something - version: v1 -host: security.sonusnet.com -schemes: -- https -- http -basePath: /api/something/definitions -produces: -- application/json -- plain/text - -paths: - /shared: - get: - operationId: Get - tags: - - Shared - responses: - 200: - description: OK - schema: - properties: - name: - type: string - -definitions: - Something: - description: Something - type: object - properties: - p1: - type: string - description: A string - p2: - type: integer - description: An integer - diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/swagger/spec.yml b/vendor/github.com/go-openapi/loads/fixtures/yaml/swagger/spec.yml deleted file mode 100644 index 7e6b1331a..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/swagger/spec.yml +++ /dev/null @@ -1,38 +0,0 @@ -swagger: "2.0" -info: - version: 0.1.1 - title: test 1 - description: recursively following JSON references - contact: - name: Fred - -schemes: - - http - -consumes: - - application/json -produces: - - application/json - -paths: - /getAll: - get: - operationId: getAll - parameters: - - name: a - in: body - description: max number of results - required: false - schema: - $ref: '#/definitions/a' - responses: - '200': - description: Success - schema: - $ref: '#/definitions/b' - -definitions: - a: - type: string - b: - $ref: './test3-ter-model-schema.json#/definitions/b' \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/swagger/test3-ter-model-schema.json b/vendor/github.com/go-openapi/loads/fixtures/yaml/swagger/test3-ter-model-schema.json deleted file mode 100644 index eb446c762..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/swagger/test3-ter-model-schema.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "./test3-model-schema.json", - "title": "test3-model-schema", - "description": "Test schema responses", - "definitions": { - "b": { - "type": "array", - "items": { - "type": "string" - } - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/.gitkeep b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/.gitkeep deleted file mode 100644 index e69de29bb..000000000 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithArrayRef.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithArrayRef.yaml deleted file mode 100644 index b32a35901..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithArrayRef.yaml +++ /dev/null @@ -1,5 +0,0 @@ -required: - - id -properties: - id: {type: integer, format: int64} - children: {type: array, items: {$ref: Person}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithComposition.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithComposition.yaml deleted file mode 100644 index f0ea5e80f..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithComposition.yaml +++ /dev/null @@ -1,5 +0,0 @@ -definitions: - Cat: {description: 'A representation of a cat', allOf: [{$ref: '#/models/Pet'}, {properties: {huntingSkill: {type: string, description: 'The measured skill for hunting', default: lazy, enum: [clueless, lazy, adventerous, aggressive]}}, required: [huntingSkill]}]} - Dog: {description: 'A representation of a dog', allOf: [{$ref: '#/models/Pet'}, {properties: {packSize: {type: integer, format: int32, description: 'the size of the pack the dog is from', default: 0}}, required: [name, packSize]}]} - Fish: {description: 'A representation of a fish', allOf: [{$ref: '#/models/Pet'}, {properties: {fins: {type: integer, format: int32, description: 'count of fins'}}, required: [fins]}]} - Pet: {discriminator: petType, properties: {name: {type: string}, petType: {type: string}}, required: [name, petType]} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithDateTimeMap.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithDateTimeMap.yaml deleted file mode 100644 index 653cbd182..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithDateTimeMap.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'true' -additionalProperties: - type: string - format: date-time diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithExamples.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithExamples.yaml deleted file mode 100644 index 0252ec176..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithExamples.yaml +++ /dev/null @@ -1,3 +0,0 @@ -definitions: - Pet: {properties: {name: {type: string}}, required: [name]} - Dog: {properties: {id: {type: integer, format: int64}, name: {type: string}}, required: [name]} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithInt32Map.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithInt32Map.yaml deleted file mode 100644 index 88ab02447..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithInt32Map.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'This is a Map[String, Integer]' -additionalProperties: - type: integer - format: int32 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithInt64Map.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithInt64Map.yaml deleted file mode 100644 index 16c790e42..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithInt64Map.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'true' -additionalProperties: - type: integer - format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithMultipleProperties.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithMultipleProperties.yaml deleted file mode 100644 index f69d27ef2..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithMultipleProperties.yaml +++ /dev/null @@ -1,14 +0,0 @@ -description: 'true' -properties: - booleanValue: {type: boolean} - byteValue: {type: string, format: byte} - dateTimeValue: {type: string, format: date-time} - int32Value: {type: integer, format: int32} - int64Value: {type: integer, format: int64} - stringValue: {type: string} - booleanArrayValue: {type: array, items: {type: boolean}} - byteArrayValue: {type: array, items: {type: string, format: byte}} - dateTimeArrayValue: {type: array, items: {type: string, format: date-time}} - int32ArrayValue: {type: array, items: {type: integer, format: int32}} - int64ArrayValue: {type: array, items: {type: integer, format: int64}} - stringArrayValue: {type: array, items: {type: string}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithObjectMap.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithObjectMap.yaml deleted file mode 100644 index e712e0f22..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithObjectMap.yaml +++ /dev/null @@ -1,9 +0,0 @@ -description: "This is a Map[String, { id: Long, name: String}]" -additionalProperties: - type: "object" - properties: - id: - type: "integer" - format: "int64" - name: - type: "string" diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithPrimitiveArray.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithPrimitiveArray.yaml deleted file mode 100644 index 0837bad52..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithPrimitiveArray.yaml +++ /dev/null @@ -1,5 +0,0 @@ -required: - - id -properties: - id: {type: integer, format: int64} - childrensAges: {type: array, items: {type: integer, format: int32}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithStringProperty.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithStringProperty.yaml deleted file mode 100644 index a17d21e5a..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithStringProperty.yaml +++ /dev/null @@ -1,3 +0,0 @@ -description: 'true' -properties: - name: {type: string} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithXmlAttributes.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithXmlAttributes.yaml deleted file mode 100644 index 2176983f8..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/modelWithXmlAttributes.yaml +++ /dev/null @@ -1,6 +0,0 @@ -description: 'this model serves xml and json structures' -xml: - name: XMLModel -properties: - id: {type: integer, format: int64, xml: {attribute: true, namespace: ns1, prefix: urn1}} - items: {type: array, items: {type: string}, xml: {wrapped: true}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/models.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/models.yaml deleted file mode 100644 index 71f8efeb4..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/models.yaml +++ /dev/null @@ -1,2 +0,0 @@ -definitions: - Pet: {properties: {name: {type: string}}, required: [name]} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/multipleModels.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/multipleModels.yaml deleted file mode 100644 index 0252ec176..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/multipleModels.yaml +++ /dev/null @@ -1,3 +0,0 @@ -definitions: - Pet: {properties: {name: {type: string}}, required: [name]} - Dog: {properties: {id: {type: integer, format: int64}, name: {type: string}}, required: [name]} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithBooleanArray.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithBooleanArray.yaml deleted file mode 100644 index aa02d0e74..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithBooleanArray.yaml +++ /dev/null @@ -1,3 +0,0 @@ -type: array -items: - type: boolean diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithByteArray.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithByteArray.yaml deleted file mode 100644 index f31b35036..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithByteArray.yaml +++ /dev/null @@ -1,4 +0,0 @@ -type: array -items: - type: string - format: byte diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithComplexArray.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithComplexArray.yaml deleted file mode 100644 index 69e0b1765..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithComplexArray.yaml +++ /dev/null @@ -1,3 +0,0 @@ -type: array -items: - $ref: ComplexType diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithDateTimeArray.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithDateTimeArray.yaml deleted file mode 100644 index 6efef25d8..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithDateTimeArray.yaml +++ /dev/null @@ -1,4 +0,0 @@ -type: array -items: - type: string - format: date-time diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithInt32Array.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithInt32Array.yaml deleted file mode 100644 index 26fd271b0..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithInt32Array.yaml +++ /dev/null @@ -1,4 +0,0 @@ -type: array -items: - type: integer - format: int32 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithInt64Array.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithInt64Array.yaml deleted file mode 100644 index e800895eb..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithInt64Array.yaml +++ /dev/null @@ -1,4 +0,0 @@ -type: array -items: - type: integer - format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithRef.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithRef.yaml deleted file mode 100644 index d78956949..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithRef.yaml +++ /dev/null @@ -1,3 +0,0 @@ -$ref: Foo -description: 'a boolean' -readOnly: true diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithStringArray.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithStringArray.yaml deleted file mode 100644 index 3a9108235..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/propertyWithStringArray.yaml +++ /dev/null @@ -1,3 +0,0 @@ -type: array -items: - type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleBooleanProperty.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleBooleanProperty.yaml deleted file mode 100644 index 9d1e27382..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleBooleanProperty.yaml +++ /dev/null @@ -1,3 +0,0 @@ -type: boolean -description: 'a boolean' -readOnly: true diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleByteProperty.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleByteProperty.yaml deleted file mode 100644 index 6af2139f9..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleByteProperty.yaml +++ /dev/null @@ -1,2 +0,0 @@ -type: string -format: byte diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleDateTimeProperty.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleDateTimeProperty.yaml deleted file mode 100644 index 407b1d7e8..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleDateTimeProperty.yaml +++ /dev/null @@ -1,2 +0,0 @@ -type: string -format: date-time diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleInt32Property.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleInt32Property.yaml deleted file mode 100644 index 8ed513dba..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleInt32Property.yaml +++ /dev/null @@ -1,2 +0,0 @@ -type: integer -format: int32 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleInt64Property.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleInt64Property.yaml deleted file mode 100644 index 69f359f3f..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleInt64Property.yaml +++ /dev/null @@ -1,2 +0,0 @@ -type: integer -format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleStringProperty.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleStringProperty.yaml deleted file mode 100644 index 5c21d88b9..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/models/properties/simpleStringProperty.yaml +++ /dev/null @@ -1 +0,0 @@ -type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/cascadingSchemes.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/cascadingSchemes.yaml deleted file mode 100644 index d10802774..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/cascadingSchemes.yaml +++ /dev/null @@ -1,23 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - '/pets/{petId}': {get: {description: 'Returns a pet based on ID', summary: 'Find pet by ID', operationId: getPetsById, produces: [application/json, text/html], parameters: [{name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: array, items: {type: string}, collectionFormat: csv}], responses: {'200': {description: 'pet response', schema: {$ref: Pet}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}, schemes: [https]}} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/commonParameters.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/commonParameters.yaml deleted file mode 100644 index 9851b7448..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/commonParameters.yaml +++ /dev/null @@ -1,23 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - '/pets/{id}': {parameters: [{name: id, in: path, description: 'ID of pet to use', required: true, type: array, items: {type: string}, collectionFormat: csv}], get: {description: 'Returns pets based on ID', summary: 'Find pets by ID', operationId: getPetsById, produces: [application/json, text/html], responses: {'200': {description: 'pet response', schema: {type: array, items: {$ref: Pet}}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/multipleMimeTypes.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/multipleMimeTypes.yaml deleted file mode 100644 index 23bdc2d2a..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/multipleMimeTypes.yaml +++ /dev/null @@ -1,32 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - 'text/plain; charset=utf-8' - - application/json - - application/vnd.github+json - - application/vnd.github.v3+json - - application/vnd.github.v3.raw+json - - application/vnd.github.v3.text+json - - application/vnd.github.v3.html+json - - application/vnd.github.v3.full+json - - application/vnd.github.v3.diff - - application/vnd.github.v3.patch -produces: - - application/json - - application/xml -paths: - '/pets/{id}': {parameters: [{name: id, in: path, description: 'ID of pet to use', required: true, type: array, items: {type: string}, collectionFormat: csv}], get: {description: 'Returns pets based on ID', summary: 'Find pets by ID', operationId: getPetsById, produces: [application/json, text/html], responses: {'200': {description: 'pet response', schema: {type: array, items: {$ref: Pet}}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/operations/operationWithTags.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/operations/operationWithTags.yaml deleted file mode 100644 index a3c85b26a..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/operations/operationWithTags.yaml +++ /dev/null @@ -1,14 +0,0 @@ -description: 'Returns a pet based on ID' -summary: 'Find pet by ID' -operationId: getPetsById -tags: - - foo - - bar -produces: - - application/json - - text/html -parameters: - - {name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: integer, format: int64} -responses: - '200': {description: 'a pet to be returned', schema: {$ref: Pet}} - default: {description: 'Unexpected error', schema: {$ref: ErrorModel}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/operations/stringPathAndBoolQueryParamResource.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/operations/stringPathAndBoolQueryParamResource.yaml deleted file mode 100644 index a00b8c469..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/operations/stringPathAndBoolQueryParamResource.yaml +++ /dev/null @@ -1,12 +0,0 @@ -description: 'Returns a pet based on ID' -summary: 'Find pet by ID' -operationId: getPetsById -produces: - - application/json - - text/html -parameters: - - {name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: integer, format: int64} - - {name: includeDetails, in: query, description: 'include details in response', required: true, type: boolean} -responses: - '200': {description: 'a pet to be returned', schema: {$ref: Pet}} - default: {description: 'Unexpected error', schema: {$ref: ErrorModel}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/operations/stringPathParamResource.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/operations/stringPathParamResource.yaml deleted file mode 100644 index 8c46cc7ee..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/operations/stringPathParamResource.yaml +++ /dev/null @@ -1,12 +0,0 @@ -description: 'Returns a pet based on ID' -summary: 'Find pet by ID' -operationId: getPetsById -produces: - - application/json - - text/html -parameters: - - {name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: integer, format: int64} -responses: - '200': {description: fun, schema: {$ref: Pet}} - '400': {description: 'Invalid ID supplied <= this is purely for documentation', schema: {$ref: ErrorModel}} - default: {description: 'Unexpected error', schema: {$ref: ErrorModel}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/bodyComplexArrayParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/bodyComplexArrayParameter.yaml deleted file mode 100644 index 511f8dc2b..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/bodyComplexArrayParameter.yaml +++ /dev/null @@ -1,8 +0,0 @@ -name: user -in: body -description: 'user to add to the system' -required: true -schema: - type: array - items: {type: string} - format: csv diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/bodyComplexParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/bodyComplexParameter.yaml deleted file mode 100644 index 13f8fd171..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/bodyComplexParameter.yaml +++ /dev/null @@ -1,6 +0,0 @@ -name: user -in: body -description: 'user to add to the system' -required: true -schema: - $ref: User diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/bodyInt64Parameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/bodyInt64Parameter.yaml deleted file mode 100644 index a270d94cb..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/bodyInt64Parameter.yaml +++ /dev/null @@ -1,7 +0,0 @@ -name: id -in: body -description: 'id to add' -required: true -schema: - type: integer - format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/bodyStringArrayParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/bodyStringArrayParameter.yaml deleted file mode 100644 index 7d88b10dc..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/bodyStringArrayParameter.yaml +++ /dev/null @@ -1,7 +0,0 @@ -name: user -in: body -description: 'user to add to the system' -required: true -schema: - type: array - items: {type: string} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/bodyStringParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/bodyStringParameter.yaml deleted file mode 100644 index 7fe9dbd1e..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/bodyStringParameter.yaml +++ /dev/null @@ -1,6 +0,0 @@ -name: user -in: body -description: 'user to add to the system' -required: true -schema: - type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/formDataComplexParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/formDataComplexParameter.yaml deleted file mode 100644 index b49dd9e3d..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/formDataComplexParameter.yaml +++ /dev/null @@ -1,5 +0,0 @@ -name: firstName -in: formData -description: 'users first name' -required: true -$ref: Nothing diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/formDataInt64Parameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/formDataInt64Parameter.yaml deleted file mode 100644 index 0faaa7f62..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/formDataInt64Parameter.yaml +++ /dev/null @@ -1,6 +0,0 @@ -name: id -in: formData -description: 'username to fetch' -required: true -type: integer -format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/formDataStringArrayParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/formDataStringArrayParameter.yaml deleted file mode 100644 index f6534662a..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/formDataStringArrayParameter.yaml +++ /dev/null @@ -1,7 +0,0 @@ -name: user -in: formData -description: 'user to add to the system' -required: true -type: array -items: - type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/formDataStringParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/formDataStringParameter.yaml deleted file mode 100644 index 43411cf04..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/formDataStringParameter.yaml +++ /dev/null @@ -1,5 +0,0 @@ -name: firstName -in: formData -description: 'users first name' -required: true -type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/headerInt64ArrayParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/headerInt64ArrayParameter.yaml deleted file mode 100644 index 87ec99cab..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/headerInt64ArrayParameter.yaml +++ /dev/null @@ -1,9 +0,0 @@ -name: token -in: header -description: 'token to be passed as a header' -required: true -type: array -items: - type: integer - format: int64 -collectionFormat: csv diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/headerStringArrayParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/headerStringArrayParameter.yaml deleted file mode 100644 index 70e0a0a68..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/headerStringArrayParameter.yaml +++ /dev/null @@ -1,8 +0,0 @@ -name: token -in: header -description: 'token to be passed as a header' -required: true -type: array -items: - type: string -collectionFormat: csv diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/headerStringParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/headerStringParameter.yaml deleted file mode 100644 index ac99c2f62..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/headerStringParameter.yaml +++ /dev/null @@ -1,5 +0,0 @@ -name: token -in: header -description: 'token to be passed as a header' -required: true -type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/pathInt64Parameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/pathInt64Parameter.yaml deleted file mode 100644 index 3bd860aac..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/pathInt64Parameter.yaml +++ /dev/null @@ -1,6 +0,0 @@ -name: id -in: path -description: 'username to fetch' -required: true -type: integer -format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/pathStringArrayParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/pathStringArrayParameter.yaml deleted file mode 100644 index ebb24a7e2..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/pathStringArrayParameter.yaml +++ /dev/null @@ -1,8 +0,0 @@ -name: usernames -in: path -description: 'usernames to pass' -required: true -type: array -items: - type: string -collectionFormat: csv diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/pathStringParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/pathStringParameter.yaml deleted file mode 100644 index 2cb4fb2ee..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/pathStringParameter.yaml +++ /dev/null @@ -1,5 +0,0 @@ -name: username -in: path -description: 'username to fetch' -required: true -type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/queryInt64ArrayParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/queryInt64ArrayParameter.yaml deleted file mode 100644 index 453e24f5d..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/queryInt64ArrayParameter.yaml +++ /dev/null @@ -1,9 +0,0 @@ -name: id -in: query -description: 'ID of the object to fetch' -required: true -type: array -items: - type: integer - format: int64 -collectionFormat: csv diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/queryStringParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/queryStringParameter.yaml deleted file mode 100644 index e1df68530..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/queryStringParameter.yaml +++ /dev/null @@ -1,6 +0,0 @@ -name: id -in: query -description: 'ID of the object to fetch' -required: true -type: integer -format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/queryWithComplexParameter.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/queryWithComplexParameter.yaml deleted file mode 100644 index 80bc7951b..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/parameters/queryWithComplexParameter.yaml +++ /dev/null @@ -1,6 +0,0 @@ -name: id -in: query -description: 'a complex object which should not validate' -required: true -schema: - $ref: Pet diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/resourceWithExamplePayload.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/resourceWithExamplePayload.yaml deleted file mode 100644 index 9828d9605..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/resourceWithExamplePayload.yaml +++ /dev/null @@ -1,23 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - '/pets/{petId}': {get: {description: 'Returns a pet based on ID', summary: 'Find pet by ID', operationId: getPetsById, produces: [application/json, text/html], parameters: [{name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: array, items: {type: string}, collectionFormat: csv}], responses: {'200': {description: 'pet response', schema: {$ref: Pet}, examples: {application/json: {id: 9, category: {name: domestic}, name: monster, tags: [{name: 'for sale'}], status: alive}}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -definitions: - Pet: {required: [name], properties: {name: {type: string, example: cat}, tag: {type: string, example: 'for sale'}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/resourceWithLinkedDefinitions.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/resourceWithLinkedDefinitions.yaml deleted file mode 100644 index b9b00c47f..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/resourceWithLinkedDefinitions.yaml +++ /dev/null @@ -1,23 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - '/pets/{petId}': {$ref: 'https://raw.githubusercontent.com/reverb/swagger-spec/master/fixtures/v2.0/json/resources/resourceWithLinkedDefinitions_part1.json'} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/resourceWithLinkedDefinitions_part1.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/resourceWithLinkedDefinitions_part1.yaml deleted file mode 100644 index 7d358fbf1..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/resourceWithLinkedDefinitions_part1.yaml +++ /dev/null @@ -1,7 +0,0 @@ -get: - description: 'Returns a pet based on ID' - summary: 'Find pet by ID' - operationId: getPetsById - produces: [application/json, text/html] - parameters: [{name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: array, items: {type: string}, collectionFormat: csv}] - responses: {'200': {description: 'pet response', schema: {$ref: Pet}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/resourceWithRelativeHost.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/resourceWithRelativeHost.yaml deleted file mode 100644 index 744aa72e9..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/resourceWithRelativeHost.yaml +++ /dev/null @@ -1,22 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - '/pets/{id}': {parameters: [{name: id, in: path, description: 'ID of pet to use', required: true, type: array, items: {type: string}, collectionFormat: csv}], get: {description: 'Returns pets based on ID', summary: 'Find pets by ID', operationId: getPetsById, produces: [application/json, text/html], responses: {'200': {description: 'pet response', schema: {type: array, items: {$ref: Pet}}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/reusableParameters.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/reusableParameters.yaml deleted file mode 100644 index 1d258d082..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/reusableParameters.yaml +++ /dev/null @@ -1,26 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - '/pets/{id}': {get: {description: 'Returns pets based on ID', summary: 'Find pets by ID', operationId: getPetsById, parameters: [{$ref: '#/parameters/skipParam'}, {$ref: '#/parameters/limitParam'}], responses: {'200': {description: 'pet response', schema: {type: array, items: {$ref: Pet}}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -parameters: - skipParam: {name: skip, in: query, description: 'number of items to skip', required: true, type: integer, format: int32} - limitParam: {name: limit, in: query, description: 'max records to return', required: true, type: integer, format: int32} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/securityExample.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/securityExample.yaml deleted file mode 100644 index 007d26db4..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/securityExample.yaml +++ /dev/null @@ -1,29 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -security: - - {githubAccessCode: [user, gist]} - - {internalApiKey: []} -paths: - '/pets/{id}': {parameters: [{name: id, in: path, description: 'ID of pet to use', required: true, type: array, items: {type: string}, collectionFormat: csv}], get: {description: 'Returns pets based on ID', summary: 'Find pets by ID', operationId: getPetsById, security: [{githubAuth: ['user:read', 'user:write']}, {internalApiKey: []}], produces: [application/json, text/html], responses: {'200': {description: 'pet response', schema: {type: array, items: {$ref: Pet}}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -securityDefinitions: - githubAccessCode: {type: oauth2, scopes: {user: 'Grants read/write access to profile info only. Note that this scope includes user:email and user:follow.', 'user:email': 'Grants read access to a user’s email addresses.', 'user:follow': 'Grants access to follow or unfollow other users.', public_repo: 'Grants read/write access to code, commit statuses, and deployment statuses for public repositories and organizations.', repo: 'Grants read/write access to code, commit statuses, and deployment statuses for public and private repositories and organizations.', repo_deployment: 'Grants access to deployment statuses for public and private repositories. This scope is only necessary to grant other users or services access to deployment statuses, without granting access to the code.', 'repo:status': 'Grants read/write access to public and private repository commit statuses. This scope is only necessary to grant other users or services access to private repository commit statuses without granting access to the code.', delete_repo: 'Grants access to delete adminable repositories.', notifications: 'Grants read access to a user’s notifications. repo also provides this access.', gist: 'Grants write access to gists.', 'read:repo_hook': 'Grants read and ping access to hooks in public or private repositories.', 'write:repo_hook': 'Grants read, write, and ping access to hooks in public or private repositories.', 'admin:repo_hook': 'Grants read, write, ping, and delete access to hooks in public or private repositories.', 'read:org': 'Read-only access to organization, teams, and membership.', 'write:org': 'Publicize and unpublicize organization membership.', 'admin:org': 'Fully manage organization, teams, and memberships.', 'read:public_key': 'List and view details for public keys.', 'write:public_key': 'Create, list, and view details for public keys.', 'admin:public_key': 'Fully manage public keys.'}, flow: accessCode, authorizationUrl: 'https://github.com/login/oauth/authorize', tokenUrl: 'https://github.com/login/oauth/access_token'} - petstoreImplicit: {type: oauth2, scopes: {user: 'Grants read/write access to profile info only. Note that this scope includes user:email and user:follow.', 'user:email': 'Grants read access to a user’s email addresses.', 'user:follow': 'Grants access to follow or unfollow other users.', public_repo: 'Grants read/write access to code, commit statuses, and deployment statuses for public repositories and organizations.', repo: 'Grants read/write access to code, commit statuses, and deployment statuses for public and private repositories and organizations.', repo_deployment: 'Grants access to deployment statuses for public and private repositories. This scope is only necessary to grant other users or services access to deployment statuses, without granting access to the code.', 'repo:status': 'Grants read/write access to public and private repository commit statuses. This scope is only necessary to grant other users or services access to private repository commit statuses without granting access to the code.', delete_repo: 'Grants access to delete adminable repositories.', notifications: 'Grants read access to a user’s notifications. repo also provides this access.', gist: 'Grants write access to gists.', 'read:repo_hook': 'Grants read and ping access to hooks in public or private repositories.', 'write:repo_hook': 'Grants read, write, and ping access to hooks in public or private repositories.', 'admin:repo_hook': 'Grants read, write, ping, and delete access to hooks in public or private repositories.', 'read:org': 'Read-only access to organization, teams, and membership.', 'write:org': 'Publicize and unpublicize organization membership.', 'admin:org': 'Fully manage organization, teams, and memberships.', 'read:public_key': 'List and view details for public keys.', 'write:public_key': 'Create, list, and view details for public keys.', 'admin:public_key': 'Fully manage public keys.'}, flow: implicit, authorizationUrl: 'http://petstore.swagger.wordnik.com/oauth/dialog'} - internalApiKey: {type: apiKey, in: header, name: api_key} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/stringPathParamResource.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/stringPathParamResource.yaml deleted file mode 100644 index a4a83fea0..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/stringPathParamResource.yaml +++ /dev/null @@ -1,23 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - '/pets/{petId}': {get: {description: 'Returns a pet based on ID', summary: 'Find pet by ID', operationId: getPetsById, produces: [application/json, text/html], parameters: [{name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: array, items: {type: string}, collectionFormat: csv}], responses: {'200': {description: 'pet response', schema: {$ref: Pet}}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -definitions: - Pet: {required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/taggedResource.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/taggedResource.yaml deleted file mode 100644 index 1b8620e52..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/taggedResource.yaml +++ /dev/null @@ -1,29 +0,0 @@ -swagger: '2.0' -x-reverb: - addAnythingYouWant: true -info: - x-reverb-info: 'this is an example' - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -tags: - - {name: pets} -paths: - x-reverb-path-info: 'vendor info' - /pets: {x-vendor-method: {}, get: {x-vendor-operation-property: {}, description: 'Returns a pet based on ID', summary: 'Find pet by ID', operationId: getPetsById, produces: [application/json, text/html], parameters: [{x-vendor-parameter-property: {}, name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: array, items: {type: string}, collectionFormat: csv}], responses: {'200': {description: 'pet response', schema: {$ref: Pet}}, x-vendor-operation-response-property: {}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -definitions: - Pet: {x-vendor-model-property: {}, required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/vendorExtensionExamples.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/vendorExtensionExamples.yaml deleted file mode 100644 index 59bba0f3d..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/resources/vendorExtensionExamples.yaml +++ /dev/null @@ -1,27 +0,0 @@ -swagger: '2.0' -x-reverb: - addAnythingYouWant: true -info: - x-reverb-info: 'this is an example' - version: 1.0.9-abcd - title: 'Swagger Sample API' - description: 'A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification' - termsOfService: 'http://helloreverb.com/terms/' - contact: {name: 'wordnik api team', url: 'http://developer.wordnik.com'} - license: {name: 'Creative Commons 4.0 International', url: 'http://creativecommons.org/licenses/by/4.0/'} -host: my.api.com -basePath: /v1 -schemes: - - http - - https -consumes: - - application/json -produces: - - application/json - - application/xml -paths: - x-reverb-path-info: 'vendor info' - /pets: {x-vendor-method: {}, get: {x-vendor-operation-property: {}, description: 'Returns a pet based on ID', summary: 'Find pet by ID', operationId: getPetsById, produces: [application/json, text/html], parameters: [{x-vendor-parameter-property: {}, name: petId, in: path, description: 'ID of pet that needs to be fetched', required: true, type: array, items: {type: string}, collectionFormat: csv}], responses: {'200': {description: 'pet response', schema: {$ref: Pet}}, x-vendor-operation-response-property: {}, default: {description: 'error payload', schema: {$ref: ErrorModel}}}}} -definitions: - Pet: {x-vendor-model-property: {}, required: [name], properties: {name: {type: string}, tag: {type: string}}} - ErrorModel: {required: [code, message], properties: {code: {type: integer, format: int32}, message: {type: string}}} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/complexArrayResponse.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/complexArrayResponse.yaml deleted file mode 100644 index bc5ce9534..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/complexArrayResponse.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'A complex object array response' -schema: - type: array - items: {$ref: VeryComplexType} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/dateTimeResponse.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/dateTimeResponse.yaml deleted file mode 100644 index 9bc3e8043..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/dateTimeResponse.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'A date-time response' -schema: - type: string - format: date-time diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/int32Response.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/int32Response.yaml deleted file mode 100644 index e4456c9fe..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/int32Response.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'A simple string response' -schema: - type: integer - format: int32 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/int64Response.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/int64Response.yaml deleted file mode 100644 index ca58b2a5f..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/int64Response.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'A simple string response' -schema: - type: integer - format: int64 diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/multipleResponses.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/multipleResponses.yaml deleted file mode 100644 index 4cd1312c5..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/multipleResponses.yaml +++ /dev/null @@ -1,8 +0,0 @@ -'200': - description: 'simple string response' - schema: {type: string} -'201': - description: 'object created' -default: - description: oops - schema: {type: integer, format: int32} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/stringArrayResponse.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/stringArrayResponse.yaml deleted file mode 100644 index cab5fad8c..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/stringArrayResponse.yaml +++ /dev/null @@ -1,4 +0,0 @@ -description: 'A string array response' -schema: - type: array - items: {type: string} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/stringResponse.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/stringResponse.yaml deleted file mode 100644 index 61a25e510..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/stringResponse.yaml +++ /dev/null @@ -1,3 +0,0 @@ -description: 'A simple string response' -schema: - type: string diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/stringResponseWithHeader.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/stringResponseWithHeader.yaml deleted file mode 100644 index 77c2c7561..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/stringResponseWithHeader.yaml +++ /dev/null @@ -1,6 +0,0 @@ -description: 'A simple string response' -schema: - type: string -headers: - is-dog: {type: boolean} - is-cat: {type: boolean} diff --git a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/voidResponse.yaml b/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/voidResponse.yaml deleted file mode 100644 index f2aa5e124..000000000 --- a/vendor/github.com/go-openapi/loads/fixtures/yaml/yaml/responses/voidResponse.yaml +++ /dev/null @@ -1 +0,0 @@ -description: 'object created' diff --git a/vendor/github.com/go-openapi/loads/fmts/fixture_test.go b/vendor/github.com/go-openapi/loads/fmts/fixture_test.go deleted file mode 100644 index 6213ca57c..000000000 --- a/vendor/github.com/go-openapi/loads/fmts/fixture_test.go +++ /dev/null @@ -1,298 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fmts - -import ( - "encoding/json" - "io/ioutil" - "path/filepath" - "strings" - "testing" - - "github.com/go-openapi/spec" - "github.com/stretchr/testify/assert" -) - -var extensions = []string{"json"} - -func assertSpecJSON(t testing.TB, specJSON []byte) bool { - var expected map[string]interface{} - if !assert.NoError(t, json.Unmarshal(specJSON, &expected)) { - return false - } - - obj := spec.Swagger{} - if !assert.NoError(t, json.Unmarshal(specJSON, &obj)) { - return false - } - - cb, err := json.MarshalIndent(obj, "", " ") - if assert.NoError(t, err) { - return false - } - var actual map[string]interface{} - if !assert.NoError(t, json.Unmarshal(cb, &actual)) { - return false - } - return assertSpecMaps(t, actual, expected) -} - -func assertSpecMaps(t testing.TB, actual, expected map[string]interface{}) bool { - res := true - if id, ok := expected["id"]; ok { - res = assert.Equal(t, id, actual["id"]) - } - res = res && assert.Equal(t, expected["consumes"], actual["consumes"]) - res = res && assert.Equal(t, expected["produces"], actual["produces"]) - res = res && assert.Equal(t, expected["schemes"], actual["schemes"]) - res = res && assert.Equal(t, expected["swagger"], actual["swagger"]) - res = res && assert.Equal(t, expected["info"], actual["info"]) - res = res && assert.Equal(t, expected["host"], actual["host"]) - res = res && assert.Equal(t, expected["basePath"], actual["basePath"]) - res = res && assert.Equal(t, expected["paths"], actual["paths"]) - res = res && assert.Equal(t, expected["definitions"], actual["definitions"]) - res = res && assert.Equal(t, expected["responses"], actual["responses"]) - res = res && assert.Equal(t, expected["securityDefinitions"], actual["securityDefinitions"]) - res = res && assert.Equal(t, expected["tags"], actual["tags"]) - res = res && assert.Equal(t, expected["externalDocs"], actual["externalDocs"]) - res = res && assert.Equal(t, expected["x-some-extension"], actual["x-some-extension"]) - res = res && assert.Equal(t, expected["x-schemes"], actual["x-schemes"]) - - return res -} - -func roundTripTest(t *testing.T, fixtureType, extension, fileName string, schema interface{}) bool { - if extension == "yaml" { - return roundTripTestYAML(t, fixtureType, fileName, schema) - } - return roundTripTestJSON(t, fixtureType, fileName, schema) -} - -func roundTripTestJSON(t *testing.T, fixtureType, fileName string, schema interface{}) bool { - specName := strings.TrimSuffix(fileName, filepath.Ext(fileName)) - t.Logf("verifying %s JSON fixture %q", fixtureType, specName) - - b, err := ioutil.ReadFile(fileName) - if !assert.NoError(t, err) { - return false - } - - var expected map[string]interface{} - if !assert.NoError(t, json.Unmarshal(b, &expected)) { - return false - } - - if !assert.NoError(t, json.Unmarshal(b, schema)) { - return false - } - - cb, err := json.MarshalIndent(schema, "", " ") - if !assert.NoError(t, err) { - return false - } - - var actual map[string]interface{} - if !assert.NoError(t, json.Unmarshal(cb, &actual)) { - return false - } - - return assert.EqualValues(t, expected, actual) -} - -func roundTripTestYAML(t *testing.T, fixtureType, fileName string, schema interface{}) bool { - specName := strings.TrimSuffix(fileName, filepath.Ext(fileName)) - t.Logf("verifying %s YAML fixture %q", fixtureType, specName) - - b, err := YAMLDoc(fileName) - if !assert.NoError(t, err) { - return false - } - - var expected map[string]interface{} - if !assert.NoError(t, json.Unmarshal(b, &expected)) { - return false - } - - if !assert.NoError(t, json.Unmarshal(b, schema)) { - return false - } - - cb, err := json.MarshalIndent(schema, "", " ") - if !assert.NoError(t, err) { - return false - } - - var actual map[string]interface{} - if !assert.NoError(t, json.Unmarshal(cb, &actual)) { - return false - } - - return assert.EqualValues(t, expected, actual) -} - -func TestPropertyFixtures(t *testing.T) { - for _, extension := range extensions { - path := filepath.Join("..", "fixtures", extension, "models", "properties") - files, err := ioutil.ReadDir(path) - if err != nil { - t.Fatal(err) - } - - // for _, f := range files { - // roundTripTest(t, "property", extension, filepath.Join(path, f.Name()), &Schema{}) - // } - f := files[0] - roundTripTest(t, "property", extension, filepath.Join(path, f.Name()), &spec.Schema{}) - } -} - -func TestAdditionalPropertiesWithObject(t *testing.T) { - schema := new(spec.Schema) - b, err := YAMLDoc("../fixtures/yaml/models/modelWithObjectMap.yaml") - if assert.NoError(t, err) { - var expected map[string]interface{} - if assert.NoError(t, json.Unmarshal(b, &expected)) && assert.NoError(t, json.Unmarshal(b, schema)) { - cb, err := json.MarshalIndent(schema, "", " ") - if assert.NoError(t, err) { - var actual map[string]interface{} - if assert.NoError(t, json.Unmarshal(cb, &actual)) { - assert.Equal(t, expected, actual) - } - } - } - } - -} - -func TestModelFixtures(t *testing.T) { - path := filepath.Join("..", "fixtures", "json", "models") - files, err := ioutil.ReadDir(path) - if err != nil { - t.Fatal(err) - } - specs := []string{"modelWithObjectMap", "models", "modelWithComposition", "modelWithExamples", "multipleModels"} -FILES: - for _, f := range files { - if f.IsDir() { - continue - } - for _, sp := range specs { - if strings.HasPrefix(f.Name(), sp) { - roundTripTest(t, "model", "json", filepath.Join(path, f.Name()), &spec.Schema{}) - continue FILES - } - } - //fmt.Println("trying", f.Name()) - roundTripTest(t, "model", "json", filepath.Join(path, f.Name()), &spec.Schema{}) - } - path = filepath.Join("..", "fixtures", "yaml", "models") - files, err = ioutil.ReadDir(path) - if err != nil { - t.Fatal(err) - } -YAMLFILES: - for _, f := range files { - if f.IsDir() { - continue - } - for _, sp := range specs { - if strings.HasPrefix(f.Name(), sp) { - roundTripTest(t, "model", "yaml", filepath.Join(path, f.Name()), &spec.Schema{}) - continue YAMLFILES - } - } - // fmt.Println("trying", f.Name()) - roundTripTest(t, "model", "yaml", filepath.Join(path, f.Name()), &spec.Schema{}) - } -} - -func TestParameterFixtures(t *testing.T) { - path := filepath.Join("..", "fixtures", "json", "resources", "parameters") - files, err := ioutil.ReadDir(path) - if err != nil { - t.Fatal(err) - } - - for _, f := range files { - roundTripTest(t, "parameter", "json", filepath.Join(path, f.Name()), &spec.Parameter{}) - } -} - -func TestOperationFixtures(t *testing.T) { - path := filepath.Join("..", "fixtures", "json", "resources", "operations") - files, err := ioutil.ReadDir(path) - if err != nil { - t.Fatal(err) - } - - for _, f := range files { - roundTripTest(t, "operation", "json", filepath.Join(path, f.Name()), &spec.Operation{}) - } -} - -func TestResponseFixtures(t *testing.T) { - path := filepath.Join("..", "fixtures", "json", "responses") - files, err := ioutil.ReadDir(path) - if err != nil { - t.Fatal(err) - } - - for _, f := range files { - if !strings.HasPrefix(f.Name(), "multiple") { - roundTripTest(t, "response", "json", filepath.Join(path, f.Name()), &spec.Response{}) - } else { - roundTripTest(t, "responses", "json", filepath.Join(path, f.Name()), &spec.Responses{}) - } - } -} - -func TestResourcesFixtures(t *testing.T) { - path := filepath.Join("..", "fixtures", "json", "resources") - files, err := ioutil.ReadDir(path) - if err != nil { - t.Fatal(err) - } - pathItems := []string{"resourceWithLinkedDefinitions_part1"} - toSkip := []string{} -FILES: - for _, f := range files { - if f.IsDir() { - continue - } - for _, ts := range toSkip { - if strings.HasPrefix(f.Name(), ts) { - t.Log("verifying resource" + strings.TrimSuffix(f.Name(), filepath.Ext(f.Name()))) - b, err := ioutil.ReadFile(filepath.Join(path, f.Name())) - if assert.NoError(t, err) { - assertSpecJSON(t, b) - } - continue FILES - } - } - for _, pi := range pathItems { - if strings.HasPrefix(f.Name(), pi) { - roundTripTest(t, "path items", "json", filepath.Join(path, f.Name()), &spec.PathItem{}) - continue FILES - } - } - - t.Logf("verifying resource %q", strings.TrimSuffix(f.Name(), filepath.Ext(f.Name()))) - b2, err := ioutil.ReadFile(filepath.Join(path, f.Name())) - if assert.NoError(t, err) { - assertSpecJSON(t, b2) - } - - } -} diff --git a/vendor/github.com/go-openapi/loads/fmts/yaml.go b/vendor/github.com/go-openapi/loads/fmts/yaml.go deleted file mode 100644 index 1cef2ac22..000000000 --- a/vendor/github.com/go-openapi/loads/fmts/yaml.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fmts - -import "github.com/go-openapi/swag" - -var ( - // YAMLMatcher matches yaml - YAMLMatcher = swag.YAMLMatcher - // YAMLToJSON converts YAML unmarshaled data into json compatible data - YAMLToJSON = swag.YAMLToJSON - // BytesToYAMLDoc converts raw bytes to a map[string]interface{} - BytesToYAMLDoc = swag.BytesToYAMLDoc - // YAMLDoc loads a yaml document from either http or a file and converts it to json - YAMLDoc = swag.YAMLDoc - // YAMLData loads a yaml document from either http or a file - YAMLData = swag.YAMLData -) diff --git a/vendor/github.com/go-openapi/loads/fmts/yaml_test.go b/vendor/github.com/go-openapi/loads/fmts/yaml_test.go deleted file mode 100644 index e347805d3..000000000 --- a/vendor/github.com/go-openapi/loads/fmts/yaml_test.go +++ /dev/null @@ -1,445 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package fmts - -import ( - "encoding/json" - "errors" - "net/http" - "net/http/httptest" - "testing" - - yaml "gopkg.in/yaml.v2" - - "github.com/go-openapi/swag" - "github.com/stretchr/testify/assert" -) - -type failJSONMarhal struct { -} - -func (f failJSONMarhal) MarshalJSON() ([]byte, error) { - return nil, errors.New("expected") -} - -func TestLoadHTTPBytes(t *testing.T) { - _, err := swag.LoadFromFileOrHTTP("httx://12394:abd") - assert.Error(t, err) - - serv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusNotFound) - })) - defer serv.Close() - - _, err = swag.LoadFromFileOrHTTP(serv.URL) - assert.Error(t, err) - - ts2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusOK) - rw.Write([]byte("the content")) - })) - defer ts2.Close() - - d, err := swag.LoadFromFileOrHTTP(ts2.URL) - assert.NoError(t, err) - assert.Equal(t, []byte("the content"), d) -} - -func TestYAMLToJSON(t *testing.T) { - - sd := `--- -1: the int key value -name: a string value -'y': some value -` - var data yaml.MapSlice - yaml.Unmarshal([]byte(sd), &data) - - d, err := YAMLToJSON(data) - if assert.NoError(t, err) { - assert.Equal(t, `{"1":"the int key value","name":"a string value","y":"some value"}`, string(d)) - } - - data = append(data, yaml.MapItem{Key: true, Value: "the bool value"}) - d, err = YAMLToJSON(data) - assert.Error(t, err) - assert.Nil(t, d) - - data = data[:len(data)-1] - - tag := yaml.MapSlice{{Key: "name", Value: "tag name"}} - data = append(data, yaml.MapItem{Key: "tag", Value: tag}) - - d, err = YAMLToJSON(data) - assert.NoError(t, err) - assert.Equal(t, `{"1":"the int key value","name":"a string value","y":"some value","tag":{"name":"tag name"}}`, string(d)) - - tag = yaml.MapSlice{{Key: true, Value: "bool tag name"}} - data = append(data[:len(data)-1], yaml.MapItem{Key: "tag", Value: tag}) - - d, err = YAMLToJSON(data) - assert.Error(t, err) - assert.Nil(t, d) - - var lst []interface{} - lst = append(lst, "hello") - - d, err = YAMLToJSON(lst) - assert.NoError(t, err) - assert.Equal(t, []byte(`["hello"]`), []byte(d)) - - lst = append(lst, data) - - d, err = YAMLToJSON(lst) - assert.Error(t, err) - assert.Nil(t, d) - - // _, err := yamlToJSON(failJSONMarhal{}) - // assert.Error(t, err) - - _, err = BytesToYAMLDoc([]byte("- name: hello\n")) - assert.Error(t, err) - - dd, err := BytesToYAMLDoc([]byte("description: 'object created'\n")) - assert.NoError(t, err) - - d, err = YAMLToJSON(dd) - assert.NoError(t, err) - assert.Equal(t, json.RawMessage(`{"description":"object created"}`), d) -} - -func TestLoadStrategy(t *testing.T) { - - loader := func(p string) ([]byte, error) { - return []byte(yamlPetStore), nil - } - remLoader := func(p string) ([]byte, error) { - return []byte("not it"), nil - } - - ld := swag.LoadStrategy("blah", loader, remLoader) - b, _ := ld("") - assert.Equal(t, []byte(yamlPetStore), b) - - serv := httptest.NewServer(http.HandlerFunc(yamlPestoreServer)) - defer serv.Close() - - s, err := YAMLDoc(serv.URL) - assert.NoError(t, err) - assert.NotNil(t, s) - - ts2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusNotFound) - rw.Write([]byte("\n")) - })) - defer ts2.Close() - _, err = YAMLDoc(ts2.URL) - assert.Error(t, err) -} - -var yamlPestoreServer = func(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusOK) - rw.Write([]byte(yamlPetStore)) -} - -func TestWithYKey(t *testing.T) { - doc, err := BytesToYAMLDoc([]byte(withYKey)) - if assert.NoError(t, err) { - _, err := YAMLToJSON(doc) - if assert.Error(t, err) { - doc, err := BytesToYAMLDoc([]byte(withQuotedYKey)) - if assert.NoError(t, err) { - jsond, err := YAMLToJSON(doc) - if assert.NoError(t, err) { - var yt struct { - Definitions struct { - Viewbox struct { - Properties struct { - Y struct { - Type string `json:"type"` - } `json:"y"` - } `json:"properties"` - } `json:"viewbox"` - } `json:"definitions"` - } - if assert.NoError(t, json.Unmarshal(jsond, &yt)) { - assert.Equal(t, "integer", yt.Definitions.Viewbox.Properties.Y.Type) - } - } - } - } - - } -} - -const withQuotedYKey = `consumes: -- application/json -definitions: - viewBox: - type: object - properties: - x: - type: integer - format: int16 - # y -> types don't match: expect map key string or int get: bool - "y": - type: integer - format: int16 - width: - type: integer - format: int16 - height: - type: integer - format: int16 -info: - description: Test RESTful APIs - title: Test Server - version: 1.0.0 -basePath: /api -paths: - /test: - get: - operationId: findAll - parameters: - - name: since - in: query - type: integer - format: int64 - - name: limit - in: query - type: integer - format: int32 - default: 20 - responses: - 200: - description: Array[Trigger] - schema: - type: array - items: - $ref: "#/definitions/viewBox" -produces: -- application/json -schemes: -- https -swagger: "2.0" -` - -const withYKey = `consumes: -- application/json -definitions: - viewBox: - type: object - properties: - x: - type: integer - format: int16 - # y -> types don't match: expect map key string or int get: bool - y: - type: integer - format: int16 - width: - type: integer - format: int16 - height: - type: integer - format: int16 -info: - description: Test RESTful APIs - title: Test Server - version: 1.0.0 -basePath: /api -paths: - /test: - get: - operationId: findAll - parameters: - - name: since - in: query - type: integer - format: int64 - - name: limit - in: query - type: integer - format: int32 - default: 20 - responses: - 200: - description: Array[Trigger] - schema: - type: array - items: - $ref: "#/definitions/viewBox" -produces: -- application/json -schemes: -- https -swagger: "2.0" -` - -const yamlPetStore = `swagger: '2.0' -info: - version: '1.0.0' - title: Swagger Petstore - description: A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification - termsOfService: http://helloreverb.com/terms/ - contact: - name: Swagger API team - email: foo@example.com - url: http://swagger.io - license: - name: MIT - url: http://opensource.org/licenses/MIT -host: petstore.swagger.wordnik.com -basePath: /api -schemes: - - http -consumes: - - application/json -produces: - - application/json -paths: - /pets: - get: - description: Returns all pets from the system that the user has access to - operationId: findPets - produces: - - application/json - - application/xml - - text/xml - - text/html - parameters: - - name: tags - in: query - description: tags to filter by - required: false - type: array - items: - type: string - collectionFormat: csv - - name: limit - in: query - description: maximum number of results to return - required: false - type: integer - format: int32 - responses: - '200': - description: pet response - schema: - type: array - items: - $ref: '#/definitions/pet' - default: - description: unexpected error - schema: - $ref: '#/definitions/errorModel' - post: - description: Creates a new pet in the store. Duplicates are allowed - operationId: addPet - produces: - - application/json - parameters: - - name: pet - in: body - description: Pet to add to the store - required: true - schema: - $ref: '#/definitions/newPet' - responses: - '200': - description: pet response - schema: - $ref: '#/definitions/pet' - default: - description: unexpected error - schema: - $ref: '#/definitions/errorModel' - /pets/{id}: - get: - description: Returns a user based on a single ID, if the user does not have access to the pet - operationId: findPetById - produces: - - application/json - - application/xml - - text/xml - - text/html - parameters: - - name: id - in: path - description: ID of pet to fetch - required: true - type: integer - format: int64 - responses: - '200': - description: pet response - schema: - $ref: '#/definitions/pet' - default: - description: unexpected error - schema: - $ref: '#/definitions/errorModel' - delete: - description: deletes a single pet based on the ID supplied - operationId: deletePet - parameters: - - name: id - in: path - description: ID of pet to delete - required: true - type: integer - format: int64 - responses: - '204': - description: pet deleted - default: - description: unexpected error - schema: - $ref: '#/definitions/errorModel' -definitions: - pet: - required: - - id - - name - properties: - id: - type: integer - format: int64 - name: - type: string - tag: - type: string - newPet: - allOf: - - $ref: '#/definitions/pet' - - required: - - name - properties: - id: - type: integer - format: int64 - name: - type: string - errorModel: - required: - - code - - message - properties: - code: - type: integer - format: int32 - message: - type: string -` diff --git a/vendor/github.com/go-openapi/loads/hack/build-drone.sh b/vendor/github.com/go-openapi/loads/hack/build-drone.sh deleted file mode 100755 index 52b1180cc..000000000 --- a/vendor/github.com/go-openapi/loads/hack/build-drone.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash -set -e -o pipefail - - mkdir -p /drone/{testresults,coverage,dist} - go test -race -timeout 20m -v ./... | go-junit-report -dir /drone/testresults - -# Run test coverage on each subdirectories and merge the coverage profile. -echo "mode: ${GOCOVMODE-count}" > profile.cov - -# Standard go tooling behavior is to ignore dirs with leading underscores -# skip generator for race detection and coverage -for dir in $(go list ./...) -do - pth="$GOPATH/src/$dir" - go test -covermode=${GOCOVMODE-count} -coverprofile=${pth}/profile.out $dir - if [ -f $pth/profile.out ] - then - cat $pth/profile.out | tail -n +2 >> profile.cov - # rm $pth/profile.out - fi -done - -go tool cover -func profile.cov -gocov convert profile.cov | gocov report -gocov convert profile.cov | gocov-html > /drone/coverage/coverage-${CI_BUILD_NUM-"0"}.html \ No newline at end of file diff --git a/vendor/github.com/go-openapi/loads/hack/coverage b/vendor/github.com/go-openapi/loads/hack/coverage deleted file mode 100755 index b8e6dbd0c..000000000 --- a/vendor/github.com/go-openapi/loads/hack/coverage +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash -set -e -o pipefail - -# Run test coverage on each subdirectories and merge the coverage profile. -echo "mode: ${GOCOVMODE-atomic}" > coverage.txt - -# Standard go tooling behavior is to ignore dirs with leading underscores -# skip generator for race detection and coverage -for dir in $(go list ./...) -do - pth="$GOPATH/src/$dir" - go test -race -timeout 20m -covermode=${GOCOVMODE-atomic} -coverprofile=${pth}/profile.out $dir - if [ -f $pth/profile.out ] - then - cat $pth/profile.out | tail -n +2 >> coverage.txt - rm $pth/profile.out - fi -done - -go tool cover -func coverage.txt diff --git a/vendor/github.com/go-openapi/loads/json_test.go b/vendor/github.com/go-openapi/loads/json_test.go deleted file mode 100644 index 8b60eb19f..000000000 --- a/vendor/github.com/go-openapi/loads/json_test.go +++ /dev/null @@ -1,318 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package loads - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestLoadJSON(t *testing.T) { - serv := httptest.NewServer(http.HandlerFunc(jsonPestoreServer)) - defer serv.Close() - - s, err := JSONSpec(serv.URL) - assert.NoError(t, err) - assert.NotNil(t, s) - - ts2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusNotFound) - rw.Write([]byte("{}")) - })) - defer ts2.Close() - _, err = JSONSpec(ts2.URL) - assert.Error(t, err) -} - -var jsonPestoreServer = func(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusOK) - rw.Write([]byte(petstoreJSON)) -} - -const petstoreJSON = `{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "Swagger Petstore", - "contact": { - "name": "Wordnik API Team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "petstore.swagger.wordnik.com", - "basePath": "/api", - "schemes": [ - "http" - ], - "paths": { - "/pets": { - "get": { - "security": [ - { - "oauth2": ["read"] - } - ], - "tags": [ "Pet Operations" ], - "operationId": "getAllPets", - "parameters": [ - { - "name": "status", - "in": "query", - "description": "The status to filter by", - "type": "string" - } - ], - "summary": "Finds all pets in the system", - "responses": { - "200": { - "description": "Pet response", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/Pet" - } - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "post": { - "security": [ - { - "oauth2": ["write"] - } - ], - "tags": [ "Pet Operations" ], - "operationId": "createPet", - "summary": "Creates a new pet", - "parameters": [ - { - "name": "pet", - "in": "body", - "description": "The Pet to create", - "required": true, - "schema": { - "$ref": "#/definitions/newPet" - } - } - ], - "responses": { - "200": { - "description": "Created Pet response", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - } - }, - "/pets/{id}": { - "delete": { - "security": [ - { - "oauth2": ["write"] - } - ], - "description": "Deletes the Pet by id", - "operationId": "deletePet", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to delete", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "204": { - "description": "pet deleted" - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "get": { - "security": [ - { - "oauth2": ["read"] - } - ], - "tags": [ "Pet Operations" ], - "operationId": "getPetById", - "summary": "Finds the pet by id", - "responses": { - "200": { - "description": "Pet response", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet", - "required": true, - "type": "integer", - "format": "int64" - } - ] - } - }, - "definitions": { - "Category": { - "id": "Category", - "properties": { - "id": { - "format": "int64", - "type": "integer" - }, - "name": { - "type": "string" - } - } - }, - "Pet": { - "id": "Pet", - "properties": { - "category": { - "$ref": "#/definitions/Category" - }, - "id": { - "description": "unique identifier for the pet", - "format": "int64", - "maximum": 100.0, - "minimum": 0.0, - "type": "integer" - }, - "name": { - "type": "string" - }, - "photoUrls": { - "items": { - "type": "string" - }, - "type": "array" - }, - "status": { - "description": "pet status in the store", - "enum": [ - "available", - "pending", - "sold" - ], - "type": "string" - }, - "tags": { - "items": { - "$ref": "#/definitions/Tag" - }, - "type": "array" - } - }, - "required": [ - "id", - "name" - ] - }, - "newPet": { - "allOf": [ - { - "$ref": "#/definitions/Pet" - } - ], - "required": [ - "name" - ] - }, - "Tag": { - "id": "Tag", - "properties": { - "id": { - "format": "int64", - "type": "integer" - }, - "name": { - "type": "string" - } - } - }, - "Error": { - "required": [ - "code", - "message" - ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - }, - "produces": [ - "application/json", - "application/xml", - "text/plain", - "text/html" - ], - "securityDefinitions": { - "oauth2": { - "type": "oauth2", - "scopes": { - "read": "Read access.", - "write": "Write access" - }, - "flow": "accessCode", - "authorizationUrl": "http://petstore.swagger.wordnik.com/oauth/authorize", - "tokenUrl": "http://petstore.swagger.wordnik.com/oauth/token" - } - } -}` diff --git a/vendor/github.com/go-openapi/loads/spec.go b/vendor/github.com/go-openapi/loads/spec.go deleted file mode 100644 index 649ca06e6..000000000 --- a/vendor/github.com/go-openapi/loads/spec.go +++ /dev/null @@ -1,279 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package loads - -import ( - "bytes" - "encoding/json" - "fmt" - "net/url" - - "github.com/go-openapi/analysis" - "github.com/go-openapi/spec" - "github.com/go-openapi/swag" -) - -// JSONDoc loads a json document from either a file or a remote url -func JSONDoc(path string) (json.RawMessage, error) { - data, err := swag.LoadFromFileOrHTTP(path) - if err != nil { - return nil, err - } - return json.RawMessage(data), nil -} - -// DocLoader represents a doc loader type -type DocLoader func(string) (json.RawMessage, error) - -// DocMatcher represents a predicate to check if a loader matches -type DocMatcher func(string) bool - -var ( - loaders *loader - defaultLoader *loader -) - -func init() { - defaultLoader = &loader{Match: func(_ string) bool { return true }, Fn: JSONDoc} - loaders = defaultLoader - spec.PathLoader = loaders.Fn - AddLoader(swag.YAMLMatcher, swag.YAMLDoc) -} - -// AddLoader for a document -func AddLoader(predicate DocMatcher, load DocLoader) { - prev := loaders - loaders = &loader{ - Match: predicate, - Fn: load, - Next: prev, - } - spec.PathLoader = loaders.Fn -} - -type loader struct { - Fn DocLoader - Match DocMatcher - Next *loader -} - -// JSONSpec loads a spec from a json document -func JSONSpec(path string) (*Document, error) { - data, err := JSONDoc(path) - if err != nil { - return nil, err - } - // convert to json - return Analyzed(json.RawMessage(data), "") -} - -// Document represents a swagger spec document -type Document struct { - // specAnalyzer - Analyzer *analysis.Spec - spec *spec.Swagger - specFilePath string - origSpec *spec.Swagger - schema *spec.Schema - raw json.RawMessage -} - -// Embedded returns a Document based on embedded specs. No analysis is required -func Embedded(orig, flat json.RawMessage) (*Document, error) { - var origSpec, flatSpec spec.Swagger - if err := json.Unmarshal(orig, &origSpec); err != nil { - return nil, err - } - if err := json.Unmarshal(flat, &flatSpec); err != nil { - return nil, err - } - return &Document{ - raw: orig, - origSpec: &origSpec, - spec: &flatSpec, - }, nil -} - -// Spec loads a new spec document -func Spec(path string) (*Document, error) { - specURL, err := url.Parse(path) - if err != nil { - return nil, err - } - var lastErr error - for l := loaders.Next; l != nil; l = l.Next { - if loaders.Match(specURL.Path) { - b, err2 := loaders.Fn(path) - if err2 != nil { - lastErr = err2 - continue - } - doc, err := Analyzed(b, "") - if err != nil { - return nil, err - } - if doc != nil { - doc.specFilePath = path - } - return doc, nil - } - } - if lastErr != nil { - return nil, lastErr - } - b, err := defaultLoader.Fn(path) - if err != nil { - return nil, err - } - - document, err := Analyzed(b, "") - if document != nil { - document.specFilePath = path - } - - return document, err -} - -// Analyzed creates a new analyzed spec document -func Analyzed(data json.RawMessage, version string) (*Document, error) { - if version == "" { - version = "2.0" - } - if version != "2.0" { - return nil, fmt.Errorf("spec version %q is not supported", version) - } - - raw := data - trimmed := bytes.TrimSpace(data) - if len(trimmed) > 0 { - if trimmed[0] != '{' && trimmed[0] != '[' { - yml, err := swag.BytesToYAMLDoc(trimmed) - if err != nil { - return nil, fmt.Errorf("analyzed: %v", err) - } - d, err := swag.YAMLToJSON(yml) - if err != nil { - return nil, fmt.Errorf("analyzed: %v", err) - } - raw = d - } - } - - swspec := new(spec.Swagger) - if err := json.Unmarshal(raw, swspec); err != nil { - return nil, err - } - - origsqspec := new(spec.Swagger) - if err := json.Unmarshal(raw, origsqspec); err != nil { - return nil, err - } - - d := &Document{ - Analyzer: analysis.New(swspec), - schema: spec.MustLoadSwagger20Schema(), - spec: swspec, - raw: raw, - origSpec: origsqspec, - } - return d, nil -} - -// Expanded expands the ref fields in the spec document and returns a new spec document -func (d *Document) Expanded(options ...*spec.ExpandOptions) (*Document, error) { - swspec := new(spec.Swagger) - if err := json.Unmarshal(d.raw, swspec); err != nil { - return nil, err - } - - var expandOptions *spec.ExpandOptions - if len(options) > 0 { - expandOptions = options[0] - } else { - expandOptions = &spec.ExpandOptions{ - RelativeBase: d.specFilePath, - } - } - - if err := spec.ExpandSpec(swspec, expandOptions); err != nil { - return nil, err - } - - dd := &Document{ - Analyzer: analysis.New(swspec), - spec: swspec, - specFilePath: d.specFilePath, - schema: spec.MustLoadSwagger20Schema(), - raw: d.raw, - origSpec: d.origSpec, - } - return dd, nil -} - -// BasePath the base path for this spec -func (d *Document) BasePath() string { - return d.spec.BasePath -} - -// Version returns the version of this spec -func (d *Document) Version() string { - return d.spec.Swagger -} - -// Schema returns the swagger 2.0 schema -func (d *Document) Schema() *spec.Schema { - return d.schema -} - -// Spec returns the swagger spec object model -func (d *Document) Spec() *spec.Swagger { - return d.spec -} - -// Host returns the host for the API -func (d *Document) Host() string { - return d.spec.Host -} - -// Raw returns the raw swagger spec as json bytes -func (d *Document) Raw() json.RawMessage { - return d.raw -} - -func (d *Document) OrigSpec() *spec.Swagger { - return d.origSpec -} - -// ResetDefinitions gives a shallow copy with the models reset -func (d *Document) ResetDefinitions() *Document { - defs := make(map[string]spec.Schema, len(d.origSpec.Definitions)) - for k, v := range d.origSpec.Definitions { - defs[k] = v - } - - d.spec.Definitions = defs - return d -} - -// Pristine creates a new pristine document instance based on the input data -func (d *Document) Pristine() *Document { - dd, _ := Analyzed(d.Raw(), d.Version()) - return dd -} - -// SpecFilePath returns the file path of the spec if one is defined -func (d *Document) SpecFilePath() string { - return d.specFilePath -} diff --git a/vendor/github.com/go-openapi/loads/spec_test.go b/vendor/github.com/go-openapi/loads/spec_test.go deleted file mode 100644 index a07694d33..000000000 --- a/vendor/github.com/go-openapi/loads/spec_test.go +++ /dev/null @@ -1,717 +0,0 @@ -package loads - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestUnknownSpecVersion(t *testing.T) { - _, err := Analyzed([]byte{}, "0.9") - assert.Error(t, err) -} - -func TestDefaultsTo20(t *testing.T) { - d, err := Analyzed(PetStoreJSONMessage, "") - - assert.NoError(t, err) - assert.NotNil(t, d) - assert.Equal(t, "2.0", d.Version()) - // assert.Equal(t, "2.0", d.data["swagger"].(string)) - assert.Equal(t, "/api", d.BasePath()) -} - -func TestLoadsYAMLContent(t *testing.T) { - d, err := Analyzed(json.RawMessage([]byte(YAMLSpec)), "") - if assert.NoError(t, err) { - if assert.NotNil(t, d) { - sw := d.Spec() - assert.Equal(t, "1.0.0", sw.Info.Version) - } - } -} - -// for issue 11 -func TestRegressionExpand(t *testing.T) { - swaggerFile := "fixtures/yaml/swagger/1/2/3/4/swagger.yaml" - document, err := Spec(swaggerFile) - assert.NoError(t, err) - assert.NotNil(t, document) - d, err := document.Expanded() - assert.NoError(t, err) - assert.NotNil(t, d) - b, _ := d.Spec().MarshalJSON() - assert.JSONEq(t, expectedExpanded, string(b)) -} - -func TestCascadingRefExpand(t *testing.T) { - swaggerFile := "fixtures/yaml/swagger/spec.yml" - document, err := Spec(swaggerFile) - assert.NoError(t, err) - assert.NotNil(t, document) - d, err := document.Expanded() - assert.NoError(t, err) - assert.NotNil(t, d) - b, _ := d.Spec().MarshalJSON() - assert.JSONEq(t, cascadeRefExpanded, string(b)) -} - -func TestFailsInvalidJSON(t *testing.T) { - _, err := Analyzed(json.RawMessage([]byte("{]")), "") - - assert.Error(t, err) -} - -var YAMLSpec = `swagger: '2.0' - -info: - version: "1.0.0" - title: Simple Search API - description: | - A very simple api description that makes a x-www-form-urlencoded only API to submit searches. - -produces: - - application/json - -consumes: - - application/json - -paths: - /search: - post: - operationId: search - summary: searches tasks - description: searches the task titles and descriptions for a match - consumes: - - application/x-www-form-urlencoded - parameters: - - name: q - in: formData - type: string - description: the search string - required: true - /tasks: - get: - operationId: getTasks - summary: Gets Task objects. - description: | - Optional query param of **size** determines - size of returned array - tags: - - tasks - parameters: - - name: size - in: query - description: Size of task list - type: integer - format: int32 - default: 20 - - name: completed - in: query - description: when true shows completed tasks - type: boolean - - responses: - default: - description: Generic Error - 200: - description: Successful response - headers: - X-Rate-Limit: - type: integer - format: int32 - X-Rate-Limit-Remaining: - type: integer - format: int32 - default: 42 - X-Rate-Limit-Reset: - type: integer - format: int32 - default: "1449875311" - X-Rate-Limit-Reset-Human: - type: string - default: 3 days - X-Rate-Limit-Reset-Human-Number: - type: string - default: 3 - Access-Control-Allow-Origin: - type: string - default: "*" - schema: - type: array - items: - $ref: "#/definitions/Task" - post: - operationId: createTask - summary: Creates a 'Task' object. - description: | - Validates the content property for length etc. - parameters: - - name: body - in: body - schema: - $ref: "#/definitions/Task" - tags: - - tasks - responses: - default: - description: Generic Error - 201: - description: Task Created - - /tasks/{id}: - parameters: - - name: id - in: path - type: integer - format: int32 - description: The id of the task - required: true - minimum: 1 - put: - operationId: updateTask - summary: updates a task. - description: | - Validates the content property for length etc. - tags: - - tasks - parameters: - - name: body - in: body - description: the updated task - schema: - $ref: "#/definitions/Task" - responses: - default: - description: Generic Error - 200: - description: Task updated - schema: - $ref: "#/definitions/Task" - delete: - operationId: deleteTask - summary: deletes a task - description: | - Deleting a task is irrevocable. - tags: - - tasks - responses: - default: - description: Generic Error - 204: - description: Task Deleted - - -definitions: - Task: - title: A Task object - description: | - This describes a task. Tasks require a content property to be set. - required: - - content - type: object - properties: - id: - title: the unique id of the task - description: | - This id property is autogenerated when a task is created. - type: integer - format: int64 - readOnly: true - content: - title: The content of the task - description: | - Task content can contain [GFM](https://help.github.com/articles/github-flavored-markdown/). - type: string - minLength: 5 - completed: - title: when true this task is completed - type: boolean - creditcard: - title: the credit card format usage - type: string - format: creditcard - createdAt: - title: task creation time - type: string - format: date-time - readOnly: true -` - -// PetStoreJSONMessage json raw message for Petstore20 -var PetStoreJSONMessage = json.RawMessage([]byte(PetStore20)) - -// PetStore20 json doc for swagger 2.0 pet store -const PetStore20 = `{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "Swagger Petstore", - "contact": { - "name": "Wordnik API Team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "petstore.swagger.wordnik.com", - "basePath": "/api", - "schemes": [ - "http" - ], - "paths": { - "/pets": { - "get": { - "security": [ - { - "basic": [] - } - ], - "tags": [ "Pet Operations" ], - "operationId": "getAllPets", - "parameters": [ - { - "name": "status", - "in": "query", - "description": "The status to filter by", - "type": "string" - }, - { - "name": "limit", - "in": "query", - "description": "The maximum number of results to return", - "type": "integer", - "format": "int64" - } - ], - "summary": "Finds all pets in the system", - "responses": { - "200": { - "description": "Pet response", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/Pet" - } - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "post": { - "security": [ - { - "basic": [] - } - ], - "tags": [ "Pet Operations" ], - "operationId": "createPet", - "summary": "Creates a new pet", - "consumes": ["application/x-yaml"], - "produces": ["application/x-yaml"], - "parameters": [ - { - "name": "pet", - "in": "body", - "description": "The Pet to create", - "required": true, - "schema": { - "$ref": "#/definitions/newPet" - } - } - ], - "responses": { - "200": { - "description": "Created Pet response", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - } - }, - "/pets/{id}": { - "delete": { - "security": [ - { - "apiKey": [] - } - ], - "description": "Deletes the Pet by id", - "operationId": "deletePet", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to delete", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "204": { - "description": "pet deleted" - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "get": { - "tags": [ "Pet Operations" ], - "operationId": "getPetById", - "summary": "Finds the pet by id", - "responses": { - "200": { - "description": "Pet response", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet", - "required": true, - "type": "integer", - "format": "int64" - } - ] - } - }, - "definitions": { - "Category": { - "id": "Category", - "properties": { - "id": { - "format": "int64", - "type": "integer" - }, - "name": { - "type": "string" - } - } - }, - "Pet": { - "id": "Pet", - "properties": { - "category": { - "$ref": "#/definitions/Category" - }, - "id": { - "description": "unique identifier for the pet", - "format": "int64", - "maximum": 100.0, - "minimum": 0.0, - "type": "integer" - }, - "name": { - "type": "string" - }, - "photoUrls": { - "items": { - "type": "string" - }, - "type": "array" - }, - "status": { - "description": "pet status in the store", - "enum": [ - "available", - "pending", - "sold" - ], - "type": "string" - }, - "tags": { - "items": { - "$ref": "#/definitions/Tag" - }, - "type": "array" - } - }, - "required": [ - "id", - "name" - ] - }, - "newPet": { - "anyOf": [ - { - "$ref": "#/definitions/Pet" - }, - { - "required": [ - "name" - ] - } - ] - }, - "Tag": { - "id": "Tag", - "properties": { - "id": { - "format": "int64", - "type": "integer" - }, - "name": { - "type": "string" - } - } - }, - "Error": { - "required": [ - "code", - "message" - ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - }, - "consumes": [ - "application/json", - "application/xml" - ], - "produces": [ - "application/json", - "application/xml", - "text/plain", - "text/html" - ], - "securityDefinitions": { - "basic": { - "type": "basic" - }, - "apiKey": { - "type": "apiKey", - "in": "header", - "name": "X-API-KEY" - } - } -} -` - -const expectedExpanded = ` -{ - "produces":[ - "application/json", - "plain/text" - ], - "schemes":[ - "https", - "http" - ], - "swagger":"2.0", - "info":{ - "description":"Something", - "title":"Something", - "contact":{ - "name":"Somebody", - "url":"https://url.com", - "email":"email@url.com" - }, - "version":"v1" - }, - "host":"security.sonusnet.com", - "basePath":"/api", - "paths":{ - "/whatnot":{ - "get":{ - "description":"Get something", - "responses":{ - "200":{ - "description":"The something", - "schema":{ - "description":"A collection of service events", - "type":"object", - "properties":{ - "page":{ - "description":"A description of a paged result", - "type":"object", - "properties":{ - "page":{ - "description":"the page that was requested", - "type":"integer" - }, - "page_items":{ - "description":"the number of items per page requested", - "type":"integer" - }, - "pages":{ - "description":"the total number of pages available", - "type":"integer" - }, - "total_items":{ - "description":"the total number of items available", - "type":"integer", - "format":"int64" - } - } - }, - "something":{ - "description":"Something", - "type":"object", - "properties":{ - "p1":{ - "description":"A string", - "type":"string" - }, - "p2":{ - "description":"An integer", - "type":"integer" - } - } - } - } - } - }, - "500":{ - "description":"Oops" - } - } - } - } - }, - "definitions":{ - "Something":{ - "description":"A collection of service events", - "type":"object", - "properties":{ - "page":{ - "description":"A description of a paged result", - "type":"object", - "properties":{ - "page":{ - "description":"the page that was requested", - "type":"integer" - }, - "page_items":{ - "description":"the number of items per page requested", - "type":"integer" - }, - "pages":{ - "description":"the total number of pages available", - "type":"integer" - }, - "total_items":{ - "description":"the total number of items available", - "type":"integer", - "format":"int64" - } - } - }, - "something":{ - "description":"Something", - "type":"object", - "properties":{ - "p1":{ - "description":"A string", - "type":"string" - }, - "p2":{ - "description":"An integer", - "type":"integer" - } - } - } - } - } - } -} -` - -const cascadeRefExpanded = ` -{ - "swagger": "2.0", - "consumes":[ - "application/json" - ], - "produces":[ - "application/json" - ], - "schemes":[ - "http" - ], - "info":{ - "description":"recursively following JSON references", - "title":"test 1", - "contact":{ - "name":"Fred" - }, - "version":"0.1.1" - }, - "paths":{ - "/getAll":{ - "get":{ - "operationId":"getAll", - "parameters":[ - { - "description":"max number of results", - "name":"a", - "in":"body", - "schema":{ - "type":"string" - } - } - ], - "responses":{ - "200":{ - "description":"Success", - "schema":{ - "type":"array", - "items":{ - "type":"string" - } - } - } - } - } - } - }, - "definitions":{ - "a":{ - "type":"string" - }, - "b":{ - "type":"array", - "items":{ - "type":"string" - } - } - } -} -` diff --git a/vendor/github.com/go-openapi/runtime/.editorconfig b/vendor/github.com/go-openapi/runtime/.editorconfig deleted file mode 100644 index 3152da69a..000000000 --- a/vendor/github.com/go-openapi/runtime/.editorconfig +++ /dev/null @@ -1,26 +0,0 @@ -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -end_of_line = lf -insert_final_newline = true -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true - -# Set default charset -[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] -charset = utf-8 - -# Tab indentation (no size specified) -[*.go] -indent_style = tab - -[*.md] -trim_trailing_whitespace = false - -# Matches the exact files either package.json or .travis.yml -[{package.json,.travis.yml}] -indent_style = space -indent_size = 2 diff --git a/vendor/github.com/go-openapi/runtime/.github/CONTRIBUTING.md b/vendor/github.com/go-openapi/runtime/.github/CONTRIBUTING.md deleted file mode 100644 index 7dea4240d..000000000 --- a/vendor/github.com/go-openapi/runtime/.github/CONTRIBUTING.md +++ /dev/null @@ -1,117 +0,0 @@ -## Contribution Guidelines - -### Pull requests are always welcome - -We are always thrilled to receive pull requests, and do our best to -process them as fast as possible. Not sure if that typo is worth a pull -request? Do it! We will appreciate it. - -If your pull request is not accepted on the first try, don't be -discouraged! If there's a problem with the implementation, hopefully you -received feedback on what to improve. - -We're trying very hard to keep go-swagger lean and focused. We don't want it -to do everything for everybody. This means that we might decide against -incorporating a new feature. However, there might be a way to implement -that feature *on top of* go-swagger. - - -### Conventions - -Fork the repo and make changes on your fork in a feature branch: - -- If it's a bugfix branch, name it XXX-something where XXX is the number of the - issue -- If it's a feature branch, create an enhancement issue to announce your - intentions, and name it XXX-something where XXX is the number of the issue. - -Submit unit tests for your changes. Go has a great test framework built in; use -it! Take a look at existing tests for inspiration. Run the full test suite on -your branch before submitting a pull request. - -Update the documentation when creating or modifying features. Test -your documentation changes for clarity, concision, and correctness, as -well as a clean documentation build. See ``docs/README.md`` for more -information on building the docs and how docs get released. - -Write clean code. Universally formatted code promotes ease of writing, reading, -and maintenance. Always run `gofmt -s -w file.go` on each changed file before -committing your changes. Most editors have plugins that do this automatically. - -Pull requests descriptions should be as clear as possible and include a -reference to all the issues that they address. - -Pull requests must not contain commits from other users or branches. - -Commit messages must start with a capitalized and short summary (max. 50 -chars) written in the imperative, followed by an optional, more detailed -explanatory text which is separated from the summary by an empty line. - -Code review comments may be added to your pull request. Discuss, then make the -suggested modifications and push additional commits to your feature branch. Be -sure to post a comment after pushing. The new commits will show up in the pull -request automatically, but the reviewers will not be notified unless you -comment. - -Before the pull request is merged, make sure that you squash your commits into -logical units of work using `git rebase -i` and `git push -f`. After every -commit the test suite should be passing. Include documentation changes in the -same commit so that a revert would remove all traces of the feature or fix. - -Commits that fix or close an issue should include a reference like `Closes #XXX` -or `Fixes #XXX`, which will automatically close the issue when merged. - -### Sign your work - -The sign-off is a simple line at the end of the explanation for the -patch, which certifies that you wrote it or otherwise have the right to -pass it on as an open-source patch. The rules are pretty simple: if you -can certify the below (from -[developercertificate.org](http://developercertificate.org/)): - -``` -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` - -then you just add a line to every git commit message: - - Signed-off-by: Joe Smith - -using your real name (sorry, no pseudonyms or anonymous contributions.) - -You can add the sign off when creating the git commit via `git commit -s`. diff --git a/vendor/github.com/go-openapi/runtime/.gitignore b/vendor/github.com/go-openapi/runtime/.gitignore deleted file mode 100644 index fea8b84ec..000000000 --- a/vendor/github.com/go-openapi/runtime/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -secrets.yml -coverage.out -*.cov -*.out -playground diff --git a/vendor/github.com/go-openapi/runtime/.travis.yml b/vendor/github.com/go-openapi/runtime/.travis.yml deleted file mode 100644 index 7454feb59..000000000 --- a/vendor/github.com/go-openapi/runtime/.travis.yml +++ /dev/null @@ -1,25 +0,0 @@ -language: go -dist: trusty -go: -- 1.8.x -- 1.9.x -install: -- go get -u github.com/axw/gocov/gocov -- go get -u gopkg.in/matm/v1/gocov-html -- go get -u github.com/cee-dub/go-junit-report -- go get -u github.com/stretchr/testify/assert -- go get -u golang.org/x/net/context -- go get -u gopkg.in/yaml.v2 -- go get -u github.com/go-openapi/analysis -- go get -u github.com/go-openapi/errors -- go get -u github.com/go-openapi/loads -- go get -u github.com/go-openapi/strfmt -- go get -u github.com/go-openapi/validate -- go get -u github.com/docker/go-units -script: -- ./hack/coverage -after_success: -- bash <(curl -s https://codecov.io/bash) -notifications: - slack: - secure: EmObnQuM9Mw8J9vpFaKKHqSMN4Wsr/A9+v7ewAD5cEhA0T1P4m7MbJMiJOhxUhj/X+BFh2DamW+P2lT8mybj5wg8wnkQ2BteKA8Tawi6f9PRw2NRheO8tAi8o/npLnlmet0kc93mn+oLuqHw36w4+j5mkOl2FghkfGiUVhwrhkCP7KXQN+3TU87e+/HzQumlJ3nsE+6terVxkH3PmaUTsS5ONaODZfuxFpfb7RsoEl3skHf6d+tr+1nViLxxly7558Nc33C+W1mr0qiEvMLZ+kJ/CpGWBJ6CUJM3jm6hNe2eMuIPwEK2hxZob8c7n22VPap4K6a0bBRoydoDXaba+2sD7Ym6ivDO/DVyL44VeBBLyIiIBylDGQdZH+6SoWm90Qe/i7tnY/T5Ao5igT8f3cfQY1c3EsTfqmlDfrhmACBmwSlgkdVBLTprHL63JMY24LWmh4jhxsmMRZhCL4dze8su1w6pLN/pD1pGHtKYCEVbdTmaM3PblNRFf12XB7qosmQsgUndH4Vq3bTbU0s1pKjeDhRyLvFzvR0TBbo0pDLEoF1A/i5GVFWa7yLZNUDudQERRh7qv/xBl2excIaQ1sV4DSVm7bAE9l6Kp+yeHQJW2uN6Y3X8wu9gB9nv9l5HBze7wh8KE6PyWAOLYYqZg9/sAtsv/2GcQqXcKFF1zcA= diff --git a/vendor/github.com/go-openapi/runtime/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/runtime/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e..000000000 --- a/vendor/github.com/go-openapi/runtime/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/runtime/LICENSE b/vendor/github.com/go-openapi/runtime/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/go-openapi/runtime/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/go-openapi/runtime/README.md b/vendor/github.com/go-openapi/runtime/README.md deleted file mode 100644 index 92c40705b..000000000 --- a/vendor/github.com/go-openapi/runtime/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# runtime [![Build Status](https://travis-ci.org/go-openapi/runtime.svg?branch=client-context)](https://travis-ci.org/go-openapi/runtime) [![codecov](https://codecov.io/gh/go-openapi/runtime/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/runtime) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/runtime/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/runtime?status.svg)](http://godoc.org/github.com/go-openapi/runtime) - -The runtime component for use in codegeneration or as untyped usage. diff --git a/vendor/github.com/go-openapi/runtime/authinfo_test.go b/vendor/github.com/go-openapi/runtime/authinfo_test.go deleted file mode 100644 index 0768df3b7..000000000 --- a/vendor/github.com/go-openapi/runtime/authinfo_test.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "testing" - - "github.com/go-openapi/strfmt" - "github.com/stretchr/testify/assert" -) - -func TestAuthInfoWriter(t *testing.T) { - hand := ClientAuthInfoWriterFunc(func(r ClientRequest, _ strfmt.Registry) error { - return r.SetHeaderParam("authorization", "Bearer the-token-goes-here") - }) - - tr := new(trw) - err := hand.AuthenticateRequest(tr, nil) - assert.NoError(t, err) - assert.Equal(t, "Bearer the-token-goes-here", tr.Headers.Get("Authorization")) -} diff --git a/vendor/github.com/go-openapi/runtime/bytestream.go b/vendor/github.com/go-openapi/runtime/bytestream.go deleted file mode 100644 index 9845e10cf..000000000 --- a/vendor/github.com/go-openapi/runtime/bytestream.go +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "bytes" - "encoding" - "errors" - "fmt" - "io" - "reflect" - - "github.com/go-openapi/swag" -) - -func defaultCloser() error { return nil } - -type byteStreamOpt func(opts *byteStreamOpts) - -// ClosesStream when the bytestream consumer or producer is finished -func ClosesStream(opts *byteStreamOpts) { - opts.Close = true -} - -type byteStreamOpts struct { - Close bool -} - -// ByteStreamConsumer creates a consmer for byte streams, -// takes a Writer/BinaryUnmarshaler interface or binary slice by reference, -// and reads from the provided reader -func ByteStreamConsumer(opts ...byteStreamOpt) Consumer { - var vals byteStreamOpts - for _, opt := range opts { - opt(&vals) - } - - return ConsumerFunc(func(reader io.Reader, data interface{}) error { - if reader == nil { - return errors.New("ByteStreamConsumer requires a reader") // early exit - } - - close := defaultCloser - if vals.Close { - if cl, ok := reader.(io.Closer); ok { - close = cl.Close - } - } - defer close() - - if wrtr, ok := data.(io.Writer); ok { - _, err := io.Copy(wrtr, reader) - return err - } - - buf := new(bytes.Buffer) - _, err := buf.ReadFrom(reader) - if err != nil { - return err - } - b := buf.Bytes() - - if bu, ok := data.(encoding.BinaryUnmarshaler); ok { - return bu.UnmarshalBinary(b) - } - - if t := reflect.TypeOf(data); data != nil && t.Kind() == reflect.Ptr { - v := reflect.Indirect(reflect.ValueOf(data)) - if t = v.Type(); t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8 { - v.SetBytes(b) - return nil - } - } - - return fmt.Errorf("%v (%T) is not supported by the ByteStreamConsumer, %s", - data, data, "can be resolved by supporting Writer/BinaryUnmarshaler interface") - }) -} - -// ByteStreamProducer creates a producer for byte streams, -// takes a Reader/BinaryMarshaler interface or binary slice, -// and writes to a writer (essentially a pipe) -func ByteStreamProducer(opts ...byteStreamOpt) Producer { - var vals byteStreamOpts - for _, opt := range opts { - opt(&vals) - } - return ProducerFunc(func(writer io.Writer, data interface{}) error { - if writer == nil { - return errors.New("ByteStreamProducer requires a writer") // early exit - } - close := defaultCloser - if vals.Close { - if cl, ok := writer.(io.Closer); ok { - close = cl.Close - } - } - defer close() - - if rdr, ok := data.(io.Reader); ok { - _, err := io.Copy(writer, rdr) - return err - } - - if bm, ok := data.(encoding.BinaryMarshaler); ok { - bytes, err := bm.MarshalBinary() - if err != nil { - return err - } - - _, err = writer.Write(bytes) - return err - } - - if data != nil { - if e, ok := data.(error); ok { - _, err := writer.Write([]byte(e.Error())) - return err - } - - v := reflect.Indirect(reflect.ValueOf(data)) - if t := v.Type(); t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8 { - _, err := writer.Write(v.Bytes()) - return err - } - if t := v.Type(); t.Kind() == reflect.Struct || t.Kind() == reflect.Slice { - b, err := swag.WriteJSON(data) - if err != nil { - return err - } - _, err = writer.Write(b) - return err - } - } - - return fmt.Errorf("%v (%T) is not supported by the ByteStreamProducer, %s", - data, data, "can be resolved by supporting Reader/BinaryMarshaler interface") - }) -} diff --git a/vendor/github.com/go-openapi/runtime/bytestream_test.go b/vendor/github.com/go-openapi/runtime/bytestream_test.go deleted file mode 100644 index 7560e0d5b..000000000 --- a/vendor/github.com/go-openapi/runtime/bytestream_test.go +++ /dev/null @@ -1,220 +0,0 @@ -package runtime - -import ( - "bytes" - "errors" - "fmt" - "sync/atomic" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestByteStreamConsumer(t *testing.T) { - cons := ByteStreamConsumer() - - expected := "the data for the stream to be sent over the wire" - - // can consume as a Writer - var b bytes.Buffer - if assert.NoError(t, cons.Consume(bytes.NewBufferString(expected), &b)) { - assert.Equal(t, expected, b.String()) - } - - // can consume as an UnmarshalBinary - var bu binaryUnmarshalDummy - if assert.NoError(t, cons.Consume(bytes.NewBufferString(expected), &bu)) { - assert.Equal(t, expected, bu.str) - } - - // can consume as a binary slice - var bs []byte - if assert.NoError(t, cons.Consume(bytes.NewBufferString(expected), &bs)) { - assert.Equal(t, expected, string(bs)) - } - type binarySlice []byte - var bs2 binarySlice - if assert.NoError(t, cons.Consume(bytes.NewBufferString(expected), &bs2)) { - assert.Equal(t, expected, string(bs2)) - } - - // passing in a nilslice wil result in an error - var ns *[]byte - assert.Error(t, cons.Consume(bytes.NewBufferString(expected), &ns)) - - // passing in nil wil result in an error as well - assert.Error(t, cons.Consume(bytes.NewBufferString(expected), nil)) - - // a reader who results in an error, will make it fail - assert.Error(t, cons.Consume(new(nopReader), &bu)) - assert.Error(t, cons.Consume(new(nopReader), &bs)) - - // the readers can also not be nil - assert.Error(t, cons.Consume(nil, &bs)) -} - -type binaryUnmarshalDummy struct { - str string -} - -func (b *binaryUnmarshalDummy) UnmarshalBinary(bytes []byte) error { - if len(bytes) == 0 { - return errors.New("no text given") - } - - b.str = string(bytes) - return nil -} - -func TestByteStreamProducer(t *testing.T) { - cons := ByteStreamProducer() - expected := "the data for the stream to be sent over the wire" - - var rdr bytes.Buffer - - // can produce using a reader - if assert.NoError(t, cons.Produce(&rdr, bytes.NewBufferString(expected))) { - assert.Equal(t, expected, rdr.String()) - rdr.Reset() - } - - // can produce using a binary marshaller - if assert.NoError(t, cons.Produce(&rdr, &binaryMarshalDummy{expected})) { - assert.Equal(t, expected, rdr.String()) - rdr.Reset() - } - - // binary slices can also be used to produce - if assert.NoError(t, cons.Produce(&rdr, []byte(expected))) { - assert.Equal(t, expected, rdr.String()) - rdr.Reset() - } - - // errors can also be used to produce - if assert.NoError(t, cons.Produce(&rdr, errors.New(expected))) { - assert.Equal(t, expected, rdr.String()) - rdr.Reset() - } - - // structs can also be used to produce - if assert.NoError(t, cons.Produce(&rdr, Error{Message: expected})) { - assert.Equal(t, fmt.Sprintf(`{"message":%q}`, expected), rdr.String()) - rdr.Reset() - } - - // struct pointers can also be used to produce - if assert.NoError(t, cons.Produce(&rdr, &Error{Message: expected})) { - assert.Equal(t, fmt.Sprintf(`{"message":%q}`, expected), rdr.String()) - rdr.Reset() - } - - // slices can also be used to produce - if assert.NoError(t, cons.Produce(&rdr, []string{expected})) { - assert.Equal(t, fmt.Sprintf(`[%q]`, expected), rdr.String()) - rdr.Reset() - } - - type binarySlice []byte - if assert.NoError(t, cons.Produce(&rdr, binarySlice(expected))) { - assert.Equal(t, expected, rdr.String()) - rdr.Reset() - } - - // when binaryMarshal data is used, its potential error gets propagated - assert.Error(t, cons.Produce(&rdr, new(binaryMarshalDummy))) - // nil data should never be accepted either - assert.Error(t, cons.Produce(&rdr, nil)) - // nil readers should also never be acccepted - assert.Error(t, cons.Produce(nil, bytes.NewBufferString(expected))) -} - -type binaryMarshalDummy struct { - str string -} - -func (b *binaryMarshalDummy) MarshalBinary() ([]byte, error) { - if len(b.str) == 0 { - return nil, errors.New("no text set") - } - - return []byte(b.str), nil -} - -type closingWriter struct { - calledClose int64 - calledWrite int64 - b bytes.Buffer -} - -func (c *closingWriter) Close() error { - atomic.AddInt64(&c.calledClose, 1) - return nil -} - -func (c *closingWriter) Write(p []byte) (n int, err error) { - atomic.AddInt64(&c.calledWrite, 1) - return c.b.Write(p) -} - -func (c *closingWriter) String() string { - return c.b.String() -} - -type closingReader struct { - calledClose int64 - calledRead int64 - b *bytes.Buffer -} - -func (c *closingReader) Close() error { - atomic.AddInt64(&c.calledClose, 1) - return nil -} - -func (c *closingReader) Read(p []byte) (n int, err error) { - atomic.AddInt64(&c.calledRead, 1) - return c.b.Read(p) -} - -func TestBytestreamConsumer_Close(t *testing.T) { - cons := ByteStreamConsumer(ClosesStream) - expected := "the data for the stream to be sent over the wire" - - // can consume as a Writer - var b bytes.Buffer - r := &closingReader{b: bytes.NewBufferString(expected)} - if assert.NoError(t, cons.Consume(r, &b)) { - assert.Equal(t, expected, b.String()) - assert.EqualValues(t, 1, r.calledClose) - } - - // can consume as a Writer - cons = ByteStreamConsumer() - b.Reset() - r = &closingReader{b: bytes.NewBufferString(expected)} - if assert.NoError(t, cons.Consume(r, &b)) { - assert.Equal(t, expected, b.String()) - assert.EqualValues(t, 0, r.calledClose) - } -} - -func TestBytestreamProducer_Close(t *testing.T) { - cons := ByteStreamProducer(ClosesStream) - expected := "the data for the stream to be sent over the wire" - - // can consume as a Writer - r := &closingWriter{} - // can produce using a reader - if assert.NoError(t, cons.Produce(r, bytes.NewBufferString(expected))) { - assert.Equal(t, expected, r.String()) - assert.EqualValues(t, 1, r.calledClose) - } - - cons = ByteStreamProducer() - r = &closingWriter{} - // can produce using a reader - if assert.NoError(t, cons.Produce(r, bytes.NewBufferString(expected))) { - assert.Equal(t, expected, r.String()) - assert.EqualValues(t, 0, r.calledClose) - } -} diff --git a/vendor/github.com/go-openapi/runtime/client/auth_info.go b/vendor/github.com/go-openapi/runtime/client/auth_info.go deleted file mode 100644 index 9e18222b5..000000000 --- a/vendor/github.com/go-openapi/runtime/client/auth_info.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package client - -import ( - "encoding/base64" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" -) - -// PassThroughAuth never manipulates the request -var PassThroughAuth runtime.ClientAuthInfoWriter - -func init() { - PassThroughAuth = runtime.ClientAuthInfoWriterFunc(func(_ runtime.ClientRequest, _ strfmt.Registry) error { return nil }) -} - -// BasicAuth provides a basic auth info writer -func BasicAuth(username, password string) runtime.ClientAuthInfoWriter { - return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { - encoded := base64.StdEncoding.EncodeToString([]byte(username + ":" + password)) - return r.SetHeaderParam("Authorization", "Basic "+encoded) - }) -} - -// APIKeyAuth provides an API key auth info writer -func APIKeyAuth(name, in, value string) runtime.ClientAuthInfoWriter { - if in == "query" { - return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { - return r.SetQueryParam(name, value) - }) - } - - if in == "header" { - return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { - return r.SetHeaderParam(name, value) - }) - } - return nil -} - -// BearerToken provides a header based oauth2 bearer access token auth info writer -func BearerToken(token string) runtime.ClientAuthInfoWriter { - return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { - return r.SetHeaderParam("Authorization", "Bearer "+token) - }) -} diff --git a/vendor/github.com/go-openapi/runtime/client/auth_info_test.go b/vendor/github.com/go-openapi/runtime/client/auth_info_test.go deleted file mode 100644 index ef8859443..000000000 --- a/vendor/github.com/go-openapi/runtime/client/auth_info_test.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package client - -import ( - "net/http" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestBasicAuth(t *testing.T) { - r, _ := newRequest("GET", "/", nil) - - writer := BasicAuth("someone", "with a password") - err := writer.AuthenticateRequest(r, nil) - assert.NoError(t, err) - - req := new(http.Request) - req.Header = make(http.Header) - req.Header.Set("Authorization", r.header.Get("Authorization")) - usr, pw, ok := req.BasicAuth() - if assert.True(t, ok) { - assert.Equal(t, "someone", usr) - assert.Equal(t, "with a password", pw) - } -} - -func TestAPIKeyAuth_Query(t *testing.T) { - r, _ := newRequest("GET", "/", nil) - - writer := APIKeyAuth("api_key", "query", "the-shared-key") - err := writer.AuthenticateRequest(r, nil) - assert.NoError(t, err) - - assert.Equal(t, "the-shared-key", r.query.Get("api_key")) -} - -func TestAPIKeyAuth_Header(t *testing.T) { - r, _ := newRequest("GET", "/", nil) - - writer := APIKeyAuth("x-api-token", "header", "the-shared-key") - err := writer.AuthenticateRequest(r, nil) - assert.NoError(t, err) - - assert.Equal(t, "the-shared-key", r.header.Get("x-api-token")) -} - -func TestBearerTokenAuth(t *testing.T) { - r, _ := newRequest("GET", "/", nil) - - writer := BearerToken("the-shared-token") - err := writer.AuthenticateRequest(r, nil) - assert.NoError(t, err) - - assert.Equal(t, "Bearer the-shared-token", r.header.Get("Authorization")) -} diff --git a/vendor/github.com/go-openapi/runtime/client/keepalive.go b/vendor/github.com/go-openapi/runtime/client/keepalive.go deleted file mode 100644 index f83254515..000000000 --- a/vendor/github.com/go-openapi/runtime/client/keepalive.go +++ /dev/null @@ -1,53 +0,0 @@ -package client - -import ( - "io" - "io/ioutil" - "net/http" - "sync/atomic" -) - -// KeepAliveTransport drains the remaining body from a response -// so that go will reuse the TCP connections. -// This is not enabled by default because there are servers where -// the response never gets closed and that would make the code hang forever. -// So instead it's provided as a http client middleware that can be used to override -// any request. -func KeepAliveTransport(rt http.RoundTripper) http.RoundTripper { - return &keepAliveTransport{wrapped: rt} -} - -type keepAliveTransport struct { - wrapped http.RoundTripper -} - -func (k *keepAliveTransport) RoundTrip(r *http.Request) (*http.Response, error) { - resp, err := k.wrapped.RoundTrip(r) - if err != nil { - return resp, err - } - resp.Body = &drainingReadCloser{rdr: resp.Body} - return resp, nil -} - -type drainingReadCloser struct { - rdr io.ReadCloser - seenEOF uint32 -} - -func (d *drainingReadCloser) Read(p []byte) (n int, err error) { - n, err = d.rdr.Read(p) - if err == io.EOF || n == 0 { - atomic.StoreUint32(&d.seenEOF, 1) - } - return -} - -func (d *drainingReadCloser) Close() error { - // drain buffer - if atomic.LoadUint32(&d.seenEOF) != 1 { - //#nosec - io.Copy(ioutil.Discard, d.rdr) - } - return d.rdr.Close() -} diff --git a/vendor/github.com/go-openapi/runtime/client/keepalive_test.go b/vendor/github.com/go-openapi/runtime/client/keepalive_test.go deleted file mode 100644 index 4ac035854..000000000 --- a/vendor/github.com/go-openapi/runtime/client/keepalive_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package client - -import ( - "bytes" - "io" - "io/ioutil" - "testing" - - "github.com/stretchr/testify/assert" -) - -func newCountingReader(rdr io.Reader, readOnce bool) *countingReadCloser { - return &countingReadCloser{ - rdr: rdr, - readOnce: readOnce, - } -} - -type countingReadCloser struct { - rdr io.Reader - readOnce bool - readCalled int - closeCalled int -} - -func (c *countingReadCloser) Read(b []byte) (int, error) { - c.readCalled++ - if c.readCalled > 1 && c.readOnce { - return 0, io.EOF - } - return c.rdr.Read(b) -} - -func (c *countingReadCloser) Close() error { - c.closeCalled++ - return nil -} - -func TestDrainingReadCloser(t *testing.T) { - rdr := newCountingReader(bytes.NewBufferString("There are many things to do"), false) - prevDisc := ioutil.Discard - disc := bytes.NewBuffer(nil) - ioutil.Discard = disc - defer func() { ioutil.Discard = prevDisc }() - - buf := make([]byte, 5) - ts := &drainingReadCloser{rdr: rdr} - ts.Read(buf) - ts.Close() - assert.Equal(t, "There", string(buf)) - assert.Equal(t, " are many things to do", disc.String()) - assert.Equal(t, 3, rdr.readCalled) - assert.Equal(t, 1, rdr.closeCalled) -} - -func TestDrainingReadCloser_SeenEOF(t *testing.T) { - rdr := newCountingReader(bytes.NewBufferString("There are many things to do"), true) - prevDisc := ioutil.Discard - disc := bytes.NewBuffer(nil) - ioutil.Discard = disc - defer func() { ioutil.Discard = prevDisc }() - - buf := make([]byte, 5) - ts := &drainingReadCloser{rdr: rdr} - ts.Read(buf) - _, err := ts.Read(nil) - assert.Equal(t, io.EOF, err) - ts.Close() - assert.Equal(t, string(buf), "There") - assert.Equal(t, disc.String(), "") - assert.Equal(t, 2, rdr.readCalled) - assert.Equal(t, 1, rdr.closeCalled) -} diff --git a/vendor/github.com/go-openapi/runtime/client/request.go b/vendor/github.com/go-openapi/runtime/client/request.go deleted file mode 100644 index e272a71b2..000000000 --- a/vendor/github.com/go-openapi/runtime/client/request.go +++ /dev/null @@ -1,367 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package client - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "log" - "mime/multipart" - "net/http" - "net/url" - "os" - "path" - "path/filepath" - "strings" - "time" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" -) - -// NewRequest creates a new swagger http client request -func newRequest(method, pathPattern string, writer runtime.ClientRequestWriter) (*request, error) { - return &request{ - pathPattern: pathPattern, - method: method, - writer: writer, - header: make(http.Header), - query: make(url.Values), - timeout: DefaultTimeout, - }, nil -} - -// Request represents a swagger client request. -// -// This Request struct converts to a HTTP request. -// There might be others that convert to other transports. -// There is no error checking here, it is assumed to be used after a spec has been validated. -// so impossible combinations should not arise (hopefully). -// -// The main purpose of this struct is to hide the machinery of adding params to a transport request. -// The generated code only implements what is necessary to turn a param into a valid value for these methods. -type request struct { - pathPattern string - method string - writer runtime.ClientRequestWriter - - pathParams map[string]string - header http.Header - query url.Values - formFields url.Values - fileFields map[string][]runtime.NamedReadCloser - payload interface{} - timeout time.Duration - buf *bytes.Buffer -} - -var ( - // ensure interface compliance - _ runtime.ClientRequest = new(request) -) - -func (r *request) isMultipart(mediaType string) bool { - if len(r.fileFields) > 0 { - return true - } - - return runtime.MultipartFormMime == mediaType -} - -// BuildHTTP creates a new http request based on the data from the params -func (r *request) BuildHTTP(mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry) (*http.Request, error) { - return r.buildHTTP(mediaType, basePath, producers, registry, nil) -} - -func (r *request) buildHTTP(mediaType, basePath string, producers map[string]runtime.Producer, registry strfmt.Registry, auth runtime.ClientAuthInfoWriter) (*http.Request, error) { - // build the data - if err := r.writer.WriteToRequest(r, registry); err != nil { - return nil, err - } - - if auth != nil { - if err := auth.AuthenticateRequest(r, registry); err != nil { - return nil, err - } - } - - // create http request - var reinstateSlash bool - if r.pathPattern != "" && r.pathPattern != "/" && r.pathPattern[len(r.pathPattern)-1] == '/' { - reinstateSlash = true - } - urlPath := path.Join(basePath, r.pathPattern) - for k, v := range r.pathParams { - urlPath = strings.Replace(urlPath, "{"+k+"}", url.PathEscape(v), -1) - } - if reinstateSlash { - urlPath = urlPath + "/" - } - - var body io.ReadCloser - var pr *io.PipeReader - var pw *io.PipeWriter - - r.buf = bytes.NewBuffer(nil) - if r.payload != nil || len(r.formFields) > 0 || len(r.fileFields) > 0 { - body = ioutil.NopCloser(r.buf) - if r.isMultipart(mediaType) { - pr, pw = io.Pipe() - body = pr - } - } - req, err := http.NewRequest(r.method, urlPath, body) - - if err != nil { - return nil, err - } - - req.URL.RawQuery = r.query.Encode() - req.Header = r.header - - // check if this is a form type request - if len(r.formFields) > 0 || len(r.fileFields) > 0 { - if !r.isMultipart(mediaType) { - req.Header.Set(runtime.HeaderContentType, mediaType) - formString := r.formFields.Encode() - // set content length before writing to the buffer - req.ContentLength = int64(len(formString)) - // write the form values as the body - r.buf.WriteString(formString) - return req, nil - } - - mp := multipart.NewWriter(pw) - req.Header.Set(runtime.HeaderContentType, mangleContentType(mediaType, mp.Boundary())) - - go func() { - defer func() { - mp.Close() - pw.Close() - }() - - for fn, v := range r.formFields { - for _, vi := range v { - if err := mp.WriteField(fn, vi); err != nil { - pw.CloseWithError(err) - log.Println(err) - } - } - } - - defer func() { - for _, ff := range r.fileFields { - for _, ffi := range ff { - ffi.Close() - } - } - }() - for fn, f := range r.fileFields { - for _, fi := range f { - wrtr, err := mp.CreateFormFile(fn, filepath.Base(fi.Name())) - if err != nil { - pw.CloseWithError(err) - log.Println(err) - } - if _, err := io.Copy(wrtr, fi); err != nil { - pw.CloseWithError(err) - log.Println(err) - } - } - } - - }() - return req, nil - - } - - // if there is payload, use the producer to write the payload, and then - // set the header to the content-type appropriate for the payload produced - if r.payload != nil { - // TODO: infer most appropriate content type based on the producer used, - // and the `consumers` section of the spec/operation - req.Header.Set(runtime.HeaderContentType, mediaType) - if rdr, ok := r.payload.(io.ReadCloser); ok { - req.Body = rdr - - return req, nil - } - - if rdr, ok := r.payload.(io.Reader); ok { - req.Body = ioutil.NopCloser(rdr) - - return req, nil - } - - req.GetBody = func() (io.ReadCloser, error) { - var b bytes.Buffer - producer := producers[mediaType] - if err := producer.Produce(&b, r.payload); err != nil { - return nil, err - } - - if _, err := r.buf.Write(b.Bytes()); err != nil { - return nil, err - } - return ioutil.NopCloser(&b), nil - } - - // set the content length of the request or else a chunked transfer is - // declared, and this corrupts outgoing JSON payloads. the content's - // length must be set prior to the body being written per the spec at - // https://golang.org/pkg/net/http - // - // If Body is present, Content-Length is <= 0 and TransferEncoding - // hasn't been set to "identity", Write adds - // "Transfer-Encoding: chunked" to the header. Body is closed - // after it is sent. - // - // to that end a temporary buffer, b, is created to produce the payload - // body, and then its size is used to set the request's content length - var b bytes.Buffer - producer := producers[mediaType] - if err := producer.Produce(&b, r.payload); err != nil { - return nil, err - } - req.ContentLength = int64(b.Len()) - if _, err := r.buf.Write(b.Bytes()); err != nil { - return nil, err - } - } - - if runtime.CanHaveBody(req.Method) && req.Body == nil && req.Header.Get(runtime.HeaderContentType) == "" { - req.Header.Set(runtime.HeaderContentType, mediaType) - } - - return req, nil -} - -func mangleContentType(mediaType, boundary string) string { - if strings.ToLower(mediaType) == runtime.URLencodedFormMime { - return fmt.Sprintf("%s; boundary=%s", mediaType, boundary) - } - return "multipart/form-data; boundary=" + boundary -} - -func (r *request) GetMethod() string { - return r.method -} - -func (r *request) GetPath() string { - path := r.pathPattern - for k, v := range r.pathParams { - path = strings.Replace(path, "{"+k+"}", v, -1) - } - return path -} - -func (r *request) GetBody() []byte { - if r.buf == nil { - return nil - } - return r.buf.Bytes() -} - -// SetHeaderParam adds a header param to the request -// when there is only 1 value provided for the varargs, it will set it. -// when there are several values provided for the varargs it will add it (no overriding) -func (r *request) SetHeaderParam(name string, values ...string) error { - if r.header == nil { - r.header = make(http.Header) - } - r.header[http.CanonicalHeaderKey(name)] = values - return nil -} - -// SetQueryParam adds a query param to the request -// when there is only 1 value provided for the varargs, it will set it. -// when there are several values provided for the varargs it will add it (no overriding) -func (r *request) SetQueryParam(name string, values ...string) error { - if r.query == nil { - r.query = make(url.Values) - } - r.query[name] = values - return nil -} - -// GetQueryParams returns a copy of all query params currently set for the request -func (r *request) GetQueryParams() url.Values { - var result = make(url.Values) - for key, value := range r.query { - result[key] = append([]string{}, value...) - } - return result -} - -// SetFormParam adds a forn param to the request -// when there is only 1 value provided for the varargs, it will set it. -// when there are several values provided for the varargs it will add it (no overriding) -func (r *request) SetFormParam(name string, values ...string) error { - if r.formFields == nil { - r.formFields = make(url.Values) - } - r.formFields[name] = values - return nil -} - -// SetPathParam adds a path param to the request -func (r *request) SetPathParam(name string, value string) error { - if r.pathParams == nil { - r.pathParams = make(map[string]string) - } - - r.pathParams[name] = value - return nil -} - -// SetFileParam adds a file param to the request -func (r *request) SetFileParam(name string, files ...runtime.NamedReadCloser) error { - for _, file := range files { - if actualFile, ok := file.(*os.File); ok { - fi, err := os.Stat(actualFile.Name()) - if err != nil { - return err - } - if fi.IsDir() { - return fmt.Errorf("%q is a directory, only files are supported", file.Name()) - } - } - } - - if r.fileFields == nil { - r.fileFields = make(map[string][]runtime.NamedReadCloser) - } - if r.formFields == nil { - r.formFields = make(url.Values) - } - - r.fileFields[name] = files - return nil -} - -// SetBodyParam sets a body parameter on the request. -// This does not yet serialze the object, this happens as late as possible. -func (r *request) SetBodyParam(payload interface{}) error { - r.payload = payload - return nil -} - -// SetTimeout sets the timeout for a request -func (r *request) SetTimeout(timeout time.Duration) error { - r.timeout = timeout - return nil -} diff --git a/vendor/github.com/go-openapi/runtime/client/request_test.go b/vendor/github.com/go-openapi/runtime/client/request_test.go deleted file mode 100644 index e6ee6acf0..000000000 --- a/vendor/github.com/go-openapi/runtime/client/request_test.go +++ /dev/null @@ -1,511 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package client - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "io/ioutil" - "mime" - "mime/multipart" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/stretchr/testify/assert" -) - -var testProducers = map[string]runtime.Producer{ - runtime.JSONMime: runtime.JSONProducer(), - runtime.XMLMime: runtime.XMLProducer(), - runtime.TextMime: runtime.TextProducer(), -} - -func TestBuildRequest_SetHeaders(t *testing.T) { - r, _ := newRequest("GET", "/flats/{id}/", nil) - // single value - _ = r.SetHeaderParam("X-Rate-Limit", "500") - assert.Equal(t, "500", r.header.Get("X-Rate-Limit")) - _ = r.SetHeaderParam("X-Rate-Limit", "400") - assert.Equal(t, "400", r.header.Get("X-Rate-Limit")) - - // multi value - _ = r.SetHeaderParam("X-Accepts", "json", "xml", "yaml") - assert.EqualValues(t, []string{"json", "xml", "yaml"}, r.header["X-Accepts"]) -} - -func TestBuildRequest_SetPath(t *testing.T) { - r, _ := newRequest("GET", "/flats/{id}/?hello=world", nil) - - _ = r.SetPathParam("id", "1345") - assert.Equal(t, "1345", r.pathParams["id"]) -} - -func TestBuildRequest_SetQuery(t *testing.T) { - r, _ := newRequest("GET", "/flats/{id}/", nil) - - // single value - _ = r.SetQueryParam("hello", "there") - assert.Equal(t, "there", r.query.Get("hello")) - - // multi value - _ = r.SetQueryParam("goodbye", "cruel", "world") - assert.Equal(t, []string{"cruel", "world"}, r.query["goodbye"]) -} - -func TestBuildRequest_SetForm(t *testing.T) { - // non-multipart - r, _ := newRequest("POST", "/flats", nil) - _ = r.SetFormParam("hello", "world") - assert.Equal(t, "world", r.formFields.Get("hello")) - _ = r.SetFormParam("goodbye", "cruel", "world") - assert.Equal(t, []string{"cruel", "world"}, r.formFields["goodbye"]) -} - -func TestBuildRequest_SetFile(t *testing.T) { - // needs to convert form to multipart - r, _ := newRequest("POST", "/flats/{id}/image", nil) - // error if it isn't there - err := r.SetFileParam("not there", os.NewFile(0, "./i-dont-exist")) - assert.Error(t, err) - // error if it isn't a file - err = r.SetFileParam("directory", os.NewFile(0, "../client")) - assert.Error(t, err) - // success adds it to the map - err = r.SetFileParam("file", mustGetFile("./runtime.go")) - if assert.NoError(t, err) { - fl, ok := r.fileFields["file"] - if assert.True(t, ok) { - assert.Equal(t, "runtime.go", filepath.Base(fl[0].Name())) - } - } - // success adds a file param with multiple files - err = r.SetFileParam("otherfiles", mustGetFile("./runtime.go"), mustGetFile("./request.go")) - if assert.NoError(t, err) { - fl, ok := r.fileFields["otherfiles"] - if assert.True(t, ok) { - assert.Equal(t, "runtime.go", filepath.Base(fl[0].Name())) - assert.Equal(t, "request.go", filepath.Base(fl[1].Name())) - } - } -} - -func mustGetFile(path string) *os.File { - f, err := os.Open(path) - if err != nil { - panic(err) - } - return f -} - -func TestBuildRequest_SetBody(t *testing.T) { - r, _ := newRequest("GET", "/flats/{id}/?hello=world", nil) - bd := []struct{ Name, Hobby string }{{"Tom", "Organ trail"}, {"John", "Bird watching"}} - - _ = r.SetBodyParam(bd) - assert.Equal(t, bd, r.payload) -} - -func TestBuildRequest_BuildHTTP_NoPayload(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - _ = req.SetBodyParam(nil) - _ = req.SetQueryParam("hello", "world") - _ = req.SetPathParam("id", "1234") - _ = req.SetHeaderParam("X-Rate-Limit", "200") - return nil - }) - r, _ := newRequest("POST", "/flats/{id}/", reqWrtr) - - req, err := r.BuildHTTP(runtime.JSONMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - assert.Equal(t, runtime.JSONMime, req.Header.Get(runtime.HeaderContentType)) - } -} - -func TestBuildRequest_BuildHTTP_Payload(t *testing.T) { - bd := []struct{ Name, Hobby string }{{"Tom", "Organ trail"}, {"John", "Bird watching"}} - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - _ = req.SetBodyParam(bd) - _ = req.SetQueryParam("hello", "world") - _ = req.SetPathParam("id", "1234") - _ = req.SetHeaderParam("X-Rate-Limit", "200") - return nil - }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime) - - req, err := r.BuildHTTP(runtime.JSONMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expectedBody, _ := json.Marshal(bd) - actualBody, _ := ioutil.ReadAll(req.Body) - assert.Equal(t, append(expectedBody, '\n'), actualBody) - } -} - -func TestBuildRequest_BuildHTTP_SetsInAuth(t *testing.T) { - bd := []struct{ Name, Hobby string }{{"Tom", "Organ trail"}, {"John", "Bird watching"}} - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - _ = req.SetBodyParam(bd) - _ = req.SetQueryParam("hello", "wrong") - _ = req.SetPathParam("id", "wrong") - _ = req.SetHeaderParam("X-Rate-Limit", "wrong") - return nil - }) - - auth := runtime.ClientAuthInfoWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - _ = req.SetBodyParam(bd) - _ = req.SetQueryParam("hello", "world") - _ = req.SetPathParam("id", "1234") - _ = req.SetHeaderParam("X-Rate-Limit", "200") - return nil - }) - - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime) - - req, err := r.buildHTTP(runtime.JSONMime, "", testProducers, nil, auth) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expectedBody, _ := json.Marshal(bd) - actualBody, _ := ioutil.ReadAll(req.Body) - assert.Equal(t, append(expectedBody, '\n'), actualBody) - } -} - -func TestBuildRequest_BuildHTTP_XMLPayload(t *testing.T) { - bd := []struct { - XMLName xml.Name `xml:"person"` - Name string `xml:"name"` - Hobby string `xml:"hobby"` - }{{xml.Name{}, "Tom", "Organ trail"}, {xml.Name{}, "John", "Bird watching"}} - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - _ = req.SetBodyParam(bd) - _ = req.SetQueryParam("hello", "world") - _ = req.SetPathParam("id", "1234") - _ = req.SetHeaderParam("X-Rate-Limit", "200") - return nil - }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.XMLMime) - - req, err := r.BuildHTTP(runtime.XMLMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expectedBody, _ := xml.Marshal(bd) - actualBody, _ := ioutil.ReadAll(req.Body) - assert.Equal(t, expectedBody, actualBody) - } -} - -func TestBuildRequest_BuildHTTP_TextPayload(t *testing.T) { - bd := "Tom: Organ trail; John: Bird watching" - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - _ = req.SetBodyParam(bd) - _ = req.SetQueryParam("hello", "world") - _ = req.SetPathParam("id", "1234") - _ = req.SetHeaderParam("X-Rate-Limit", "200") - return nil - }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.TextMime) - - req, err := r.BuildHTTP(runtime.TextMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expectedBody := []byte(bd) - actualBody, _ := ioutil.ReadAll(req.Body) - assert.Equal(t, expectedBody, actualBody) - } -} - -func TestBuildRequest_BuildHTTP_Form(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - _ = req.SetFormParam("something", "some value") - _ = req.SetQueryParam("hello", "world") - _ = req.SetPathParam("id", "1234") - _ = req.SetHeaderParam("X-Rate-Limit", "200") - return nil - }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime) - - req, err := r.BuildHTTP(runtime.JSONMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expected := []byte("something=some+value") - actual, _ := ioutil.ReadAll(req.Body) - assert.Equal(t, expected, actual) - } -} - -func TestBuildRequest_BuildHTTP_Form_URLEncoded(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - _ = req.SetFormParam("something", "some value") - _ = req.SetQueryParam("hello", "world") - _ = req.SetPathParam("id", "1234") - _ = req.SetHeaderParam("X-Rate-Limit", "200") - return nil - }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.URLencodedFormMime) - - req, err := r.BuildHTTP(runtime.URLencodedFormMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, runtime.URLencodedFormMime, req.Header.Get(runtime.HeaderContentType)) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expected := []byte("something=some+value") - actual, _ := ioutil.ReadAll(req.Body) - assert.Equal(t, expected, actual) - } -} - -func TestBuildRequest_BuildHTTP_Form_Content_Length(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - _ = req.SetFormParam("something", "some value") - _ = req.SetQueryParam("hello", "world") - _ = req.SetPathParam("id", "1234") - _ = req.SetHeaderParam("X-Rate-Limit", "200") - return nil - }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.MultipartFormMime) - - req, err := r.BuildHTTP(runtime.JSONMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - assert.Condition(t, func() bool { return req.ContentLength > 0 }, - "ContentLength must great than 0. got %d", req.ContentLength) - expected := []byte("something=some+value") - actual, _ := ioutil.ReadAll(req.Body) - assert.Equal(t, expected, actual) - } -} - -func TestBuildRequest_BuildHTTP_FormMultipart(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - _ = req.SetFormParam("something", "some value") - _ = req.SetQueryParam("hello", "world") - _ = req.SetPathParam("id", "1234") - _ = req.SetHeaderParam("X-Rate-Limit", "200") - return nil - }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.MultipartFormMime) - - req, err := r.BuildHTTP(runtime.MultipartFormMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expected1 := []byte("Content-Disposition: form-data; name=\"something\"") - expected2 := []byte("some value") - actual, _ := ioutil.ReadAll(req.Body) - actuallines := bytes.Split(actual, []byte("\r\n")) - assert.Equal(t, 6, len(actuallines)) - boundary := string(actuallines[0]) - lastboundary := string(actuallines[4]) - assert.True(t, strings.HasPrefix(boundary, "--")) - assert.True(t, strings.HasPrefix(lastboundary, "--") && strings.HasSuffix(lastboundary, "--")) - assert.Equal(t, lastboundary, boundary+"--") - assert.Equal(t, expected1, actuallines[1]) - assert.Equal(t, expected2, actuallines[3]) - } -} - -func TestBuildRequest_BuildHTTP_FormMultiples(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - _ = req.SetFormParam("something", "some value", "another value") - _ = req.SetQueryParam("hello", "world") - _ = req.SetPathParam("id", "1234") - _ = req.SetHeaderParam("X-Rate-Limit", "200") - return nil - }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.MultipartFormMime) - - req, err := r.BuildHTTP(runtime.MultipartFormMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - expected1 := []byte("Content-Disposition: form-data; name=\"something\"") - expected2 := []byte("some value") - expected3 := []byte("another value") - actual, _ := ioutil.ReadAll(req.Body) - actuallines := bytes.Split(actual, []byte("\r\n")) - assert.Equal(t, 10, len(actuallines)) - boundary := string(actuallines[0]) - lastboundary := string(actuallines[8]) - assert.True(t, strings.HasPrefix(boundary, "--")) - assert.True(t, strings.HasPrefix(lastboundary, "--") && strings.HasSuffix(lastboundary, "--")) - assert.Equal(t, lastboundary, boundary+"--") - assert.Equal(t, expected1, actuallines[1]) - assert.Equal(t, expected2, actuallines[3]) - assert.Equal(t, actuallines[0], actuallines[4]) - assert.Equal(t, expected1, actuallines[5]) - assert.Equal(t, expected3, actuallines[7]) - } -} - -func TestBuildRequest_BuildHTTP_Files(t *testing.T) { - cont, _ := ioutil.ReadFile("./runtime.go") - cont2, _ := ioutil.ReadFile("./request.go") - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - _ = req.SetFormParam("something", "some value") - _ = req.SetFileParam("file", mustGetFile("./runtime.go")) - _ = req.SetFileParam("otherfiles", mustGetFile("./runtime.go"), mustGetFile("./request.go")) - _ = req.SetQueryParam("hello", "world") - _ = req.SetPathParam("id", "1234") - _ = req.SetHeaderParam("X-Rate-Limit", "200") - return nil - }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.JSONMime) - req, err := r.BuildHTTP(runtime.JSONMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - mediaType, params, err := mime.ParseMediaType(req.Header.Get(runtime.HeaderContentType)) - if assert.NoError(t, err) { - assert.Equal(t, runtime.MultipartFormMime, mediaType) - boundary := params["boundary"] - mr := multipart.NewReader(req.Body, boundary) - defer req.Body.Close() - frm, err := mr.ReadForm(1 << 20) - if assert.NoError(t, err) { - assert.Equal(t, "some value", frm.Value["something"][0]) - fileverifier := func(name string, index int, filename string, content []byte) { - mpff := frm.File[name][index] - mpf, _ := mpff.Open() - defer mpf.Close() - assert.Equal(t, filename, mpff.Filename) - actual, _ := ioutil.ReadAll(mpf) - assert.Equal(t, content, actual) - } - fileverifier("file", 0, "runtime.go", cont) - - fileverifier("otherfiles", 0, "runtime.go", cont) - fileverifier("otherfiles", 1, "request.go", cont2) - } - } - } -} -func TestBuildRequest_BuildHTTP_Files_URLEncoded(t *testing.T) { - cont, _ := ioutil.ReadFile("./runtime.go") - cont2, _ := ioutil.ReadFile("./request.go") - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - _ = req.SetFormParam("something", "some value") - _ = req.SetFileParam("file", mustGetFile("./runtime.go")) - _ = req.SetFileParam("otherfiles", mustGetFile("./runtime.go"), mustGetFile("./request.go")) - _ = req.SetQueryParam("hello", "world") - _ = req.SetPathParam("id", "1234") - _ = req.SetHeaderParam("X-Rate-Limit", "200") - return nil - }) - r, _ := newRequest("GET", "/flats/{id}/", reqWrtr) - _ = r.SetHeaderParam(runtime.HeaderContentType, runtime.URLencodedFormMime) - req, err := r.BuildHTTP(runtime.URLencodedFormMime, "", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/flats/1234/", req.URL.Path) - mediaType, params, err := mime.ParseMediaType(req.Header.Get(runtime.HeaderContentType)) - if assert.NoError(t, err) { - assert.Equal(t, runtime.URLencodedFormMime, mediaType) - boundary := params["boundary"] - mr := multipart.NewReader(req.Body, boundary) - defer req.Body.Close() - frm, err := mr.ReadForm(1 << 20) - if assert.NoError(t, err) { - assert.Equal(t, "some value", frm.Value["something"][0]) - fileverifier := func(name string, index int, filename string, content []byte) { - mpff := frm.File[name][index] - mpf, _ := mpff.Open() - defer mpf.Close() - assert.Equal(t, filename, mpff.Filename) - actual, _ := ioutil.ReadAll(mpf) - assert.Equal(t, content, actual) - } - fileverifier("file", 0, "runtime.go", cont) - - fileverifier("otherfiles", 0, "runtime.go", cont) - fileverifier("otherfiles", 1, "request.go", cont2) - } - } - } -} - -func TestBuildRequest_BuildHTTP_BasePath(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - _ = req.SetBodyParam(nil) - _ = req.SetQueryParam("hello", "world") - _ = req.SetPathParam("id", "1234") - _ = req.SetHeaderParam("X-Rate-Limit", "200") - return nil - }) - r, _ := newRequest("POST", "/flats/{id}/", reqWrtr) - - req, err := r.BuildHTTP(runtime.JSONMime, "/basepath", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/basepath/flats/1234/", req.URL.Path) - assert.Equal(t, runtime.JSONMime, req.Header.Get(runtime.HeaderContentType)) - } -} - -func TestBuildRequest_BuildHTTP_EscapedPath(t *testing.T) { - reqWrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { - _ = req.SetBodyParam(nil) - _ = req.SetQueryParam("hello", "world") - _ = req.SetPathParam("id", "1234/?*&^%") - _ = req.SetHeaderParam("X-Rate-Limit", "200") - return nil - }) - r, _ := newRequest("POST", "/flats/{id}/", reqWrtr) - - req, err := r.BuildHTTP(runtime.JSONMime, "/basepath", testProducers, nil) - if assert.NoError(t, err) && assert.NotNil(t, req) { - assert.Equal(t, "200", req.Header.Get("x-rate-limit")) - assert.Equal(t, "world", req.URL.Query().Get("hello")) - assert.Equal(t, "/basepath/flats/1234/?*&^%/", req.URL.Path) - assert.Equal(t, "/basepath/flats/1234%2F%3F%2A&%5E%25/", req.URL.RawPath) - assert.Equal(t, req.URL.RawPath, req.URL.EscapedPath()) - assert.Equal(t, runtime.JSONMime, req.Header.Get(runtime.HeaderContentType)) - } -} diff --git a/vendor/github.com/go-openapi/runtime/client/response.go b/vendor/github.com/go-openapi/runtime/client/response.go deleted file mode 100644 index bd238588b..000000000 --- a/vendor/github.com/go-openapi/runtime/client/response.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package client - -import ( - "io" - "net/http" - - "github.com/go-openapi/runtime" -) - -var _ runtime.ClientResponse = response{} - -type response struct { - resp *http.Response -} - -func (r response) Code() int { - return r.resp.StatusCode -} - -func (r response) Message() string { - return r.resp.Status -} - -func (r response) GetHeader(name string) string { - return r.resp.Header.Get(name) -} - -func (r response) Body() io.ReadCloser { - return r.resp.Body -} diff --git a/vendor/github.com/go-openapi/runtime/client/response_test.go b/vendor/github.com/go-openapi/runtime/client/response_test.go deleted file mode 100644 index 6b63426ad..000000000 --- a/vendor/github.com/go-openapi/runtime/client/response_test.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package client - -import ( - "bytes" - "io/ioutil" - "net/http" - "testing" - - "github.com/go-openapi/runtime" - "github.com/stretchr/testify/assert" -) - -func TestResponse(t *testing.T) { - under := new(http.Response) - under.Status = "the status message" - under.StatusCode = 392 - under.Header = make(http.Header) - under.Header.Set("Blah", "blah blah") - under.Body = ioutil.NopCloser(bytes.NewBufferString("some content")) - - var resp runtime.ClientResponse = response{under} - assert.EqualValues(t, under.StatusCode, resp.Code()) - assert.Equal(t, under.Status, resp.Message()) - assert.Equal(t, "blah blah", resp.GetHeader("blah")) - assert.Equal(t, under.Body, resp.Body()) -} diff --git a/vendor/github.com/go-openapi/runtime/client/runtime.go b/vendor/github.com/go-openapi/runtime/client/runtime.go deleted file mode 100644 index bae9c3c5c..000000000 --- a/vendor/github.com/go-openapi/runtime/client/runtime.go +++ /dev/null @@ -1,435 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package client - -import ( - "crypto" - "crypto/ecdsa" - "crypto/rsa" - "crypto/tls" - "crypto/x509" - "encoding/pem" - "fmt" - "io/ioutil" - "mime" - "net/http" - "net/http/httputil" - "strings" - "sync" - "time" - - "golang.org/x/net/context" - "golang.org/x/net/context/ctxhttp" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/logger" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/strfmt" -) - -// TLSClientOptions to configure client authentication with mutual TLS -type TLSClientOptions struct { - // Certificate is the path to a PEM-encoded certificate to be used for - // client authentication. If set then Key must also be set. - Certificate string - - // LoadedCertificate is the certificate to be used for client authentication. - // This field is ignored if Certificate is set. If this field is set, LoadedKey - // is also required. - LoadedCertificate *x509.Certificate - - // Key is the path to an unencrypted PEM-encoded private key for client - // authentication. This field is required if Certificate is set. - Key string - - // LoadedKey is the key for client authentication. This field is required if - // LoadedCertificate is set. - LoadedKey crypto.PrivateKey - - // CA is a path to a PEM-encoded certificate that specifies the root certificate - // to use when validating the TLS certificate presented by the server. If this field - // (and LoadedCA) is not set, the system certificate pool is used. This field is ignored if LoadedCA - // is set. - CA string - - // LoadedCA specifies the root certificate to use when validating the server's TLS certificate. - // If this field (and CA) is not set, the system certificate pool is used. - LoadedCA *x509.Certificate - - // ServerName specifies the hostname to use when verifying the server certificate. - // If this field is set then InsecureSkipVerify will be ignored and treated as - // false. - ServerName string - - // InsecureSkipVerify controls whether the certificate chain and hostname presented - // by the server are validated. If false, any certificate is accepted. - InsecureSkipVerify bool - - // Prevents callers using unkeyed fields. - _ struct{} -} - -// TLSClientAuth creates a tls.Config for mutual auth -func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) { - // create client tls config - cfg := &tls.Config{} - - // load client cert if specified - if opts.Certificate != "" { - cert, err := tls.LoadX509KeyPair(opts.Certificate, opts.Key) - if err != nil { - return nil, fmt.Errorf("tls client cert: %v", err) - } - cfg.Certificates = []tls.Certificate{cert} - } else if opts.LoadedCertificate != nil { - block := pem.Block{Type: "CERTIFICATE", Bytes: opts.LoadedCertificate.Raw} - certPem := pem.EncodeToMemory(&block) - - var keyBytes []byte - switch k := opts.LoadedKey.(type) { - case *rsa.PrivateKey: - keyBytes = x509.MarshalPKCS1PrivateKey(k) - case *ecdsa.PrivateKey: - var err error - keyBytes, err = x509.MarshalECPrivateKey(k) - if err != nil { - return nil, fmt.Errorf("tls client priv key: %v", err) - } - default: - return nil, fmt.Errorf("tls client priv key: unsupported key type") - } - - block = pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes} - keyPem := pem.EncodeToMemory(&block) - - cert, err := tls.X509KeyPair(certPem, keyPem) - if err != nil { - return nil, fmt.Errorf("tls client cert: %v", err) - } - cfg.Certificates = []tls.Certificate{cert} - } - - cfg.InsecureSkipVerify = opts.InsecureSkipVerify - - // When no CA certificate is provided, default to the system cert pool - // that way when a request is made to a server known by the system trust store, - // the name is still verified - if opts.LoadedCA != nil { - caCertPool := x509.NewCertPool() - caCertPool.AddCert(opts.LoadedCA) - cfg.RootCAs = caCertPool - } else if opts.CA != "" { - // load ca cert - caCert, err := ioutil.ReadFile(opts.CA) - if err != nil { - return nil, fmt.Errorf("tls client ca: %v", err) - } - caCertPool := x509.NewCertPool() - caCertPool.AppendCertsFromPEM(caCert) - cfg.RootCAs = caCertPool - } - - // apply servername overrride - if opts.ServerName != "" { - cfg.InsecureSkipVerify = false - cfg.ServerName = opts.ServerName - } - - cfg.BuildNameToCertificate() - - return cfg, nil -} - -// TLSTransport creates a http client transport suitable for mutual tls auth -func TLSTransport(opts TLSClientOptions) (http.RoundTripper, error) { - cfg, err := TLSClientAuth(opts) - if err != nil { - return nil, err - } - - return &http.Transport{TLSClientConfig: cfg}, nil -} - -// TLSClient creates a http.Client for mutual auth -func TLSClient(opts TLSClientOptions) (*http.Client, error) { - transport, err := TLSTransport(opts) - if err != nil { - return nil, err - } - return &http.Client{Transport: transport}, nil -} - -// DefaultTimeout the default request timeout -var DefaultTimeout = 30 * time.Second - -// Runtime represents an API client that uses the transport -// to make http requests based on a swagger specification. -type Runtime struct { - DefaultMediaType string - DefaultAuthentication runtime.ClientAuthInfoWriter - Consumers map[string]runtime.Consumer - Producers map[string]runtime.Producer - - Transport http.RoundTripper - Jar http.CookieJar - //Spec *spec.Document - Host string - BasePath string - Formats strfmt.Registry - Context context.Context - - Debug bool - logger logger.Logger - - clientOnce *sync.Once - client *http.Client - schemes []string - do func(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) -} - -// New creates a new default runtime for a swagger api runtime.Client -func New(host, basePath string, schemes []string) *Runtime { - var rt Runtime - rt.DefaultMediaType = runtime.JSONMime - - // TODO: actually infer this stuff from the spec - rt.Consumers = map[string]runtime.Consumer{ - runtime.JSONMime: runtime.JSONConsumer(), - runtime.XMLMime: runtime.XMLConsumer(), - runtime.TextMime: runtime.TextConsumer(), - runtime.DefaultMime: runtime.ByteStreamConsumer(), - } - rt.Producers = map[string]runtime.Producer{ - runtime.JSONMime: runtime.JSONProducer(), - runtime.XMLMime: runtime.XMLProducer(), - runtime.TextMime: runtime.TextProducer(), - runtime.DefaultMime: runtime.ByteStreamProducer(), - } - rt.Transport = http.DefaultTransport - rt.Jar = nil - rt.Host = host - rt.BasePath = basePath - rt.Context = context.Background() - rt.clientOnce = new(sync.Once) - if !strings.HasPrefix(rt.BasePath, "/") { - rt.BasePath = "/" + rt.BasePath - } - - rt.Debug = logger.DebugEnabled() - rt.logger = logger.StandardLogger{} - - if len(schemes) > 0 { - rt.schemes = schemes - } - rt.do = ctxhttp.Do - return &rt -} - -// NewWithClient allows you to create a new transport with a configured http.Client -func NewWithClient(host, basePath string, schemes []string, client *http.Client) *Runtime { - rt := New(host, basePath, schemes) - if client != nil { - rt.clientOnce.Do(func() { - rt.client = client - }) - } - return rt -} - -func (r *Runtime) pickScheme(schemes []string) string { - if v := r.selectScheme(r.schemes); v != "" { - return v - } - if v := r.selectScheme(schemes); v != "" { - return v - } - return "http" -} - -func (r *Runtime) selectScheme(schemes []string) string { - schLen := len(schemes) - if schLen == 0 { - return "" - } - - scheme := schemes[0] - // prefer https, but skip when not possible - if scheme != "https" && schLen > 1 { - for _, sch := range schemes { - if sch == "https" { - scheme = sch - break - } - } - } - return scheme -} -func transportOrDefault(left, right http.RoundTripper) http.RoundTripper { - if left == nil { - return right - } - return left -} - -// EnableConnectionReuse drains the remaining body from a response -// so that go will reuse the TCP connections. -// -// This is not enabled by default because there are servers where -// the response never gets closed and that would make the code hang forever. -// So instead it's provided as a http client middleware that can be used to override -// any request. -func (r *Runtime) EnableConnectionReuse() { - if r.client == nil { - r.Transport = KeepAliveTransport( - transportOrDefault(r.Transport, http.DefaultTransport), - ) - return - } - - r.client.Transport = KeepAliveTransport( - transportOrDefault(r.client.Transport, - transportOrDefault(r.Transport, http.DefaultTransport), - ), - ) -} - -// Submit a request and when there is a body on success it will turn that into the result -// all other things are turned into an api error for swagger which retains the status code -func (r *Runtime) Submit(operation *runtime.ClientOperation) (interface{}, error) { - params, readResponse, auth := operation.Params, operation.Reader, operation.AuthInfo - - request, err := newRequest(operation.Method, operation.PathPattern, params) - if err != nil { - return nil, err - } - - var accept []string - accept = append(accept, operation.ProducesMediaTypes...) - if err = request.SetHeaderParam(runtime.HeaderAccept, accept...); err != nil { - return nil, err - } - - if auth == nil && r.DefaultAuthentication != nil { - auth = r.DefaultAuthentication - } - //if auth != nil { - // if err := auth.AuthenticateRequest(request, r.Formats); err != nil { - // return nil, err - // } - //} - - // TODO: pick appropriate media type - cmt := r.DefaultMediaType - for _, mediaType := range operation.ConsumesMediaTypes { - // Pick first non-empty media type - if mediaType != "" { - cmt = mediaType - break - } - } - - req, err := request.buildHTTP(cmt, r.BasePath, r.Producers, r.Formats, auth) - if err != nil { - return nil, err - } - req.URL.Scheme = r.pickScheme(operation.Schemes) - req.URL.Host = r.Host - - r.clientOnce.Do(func() { - r.client = &http.Client{ - Transport: r.Transport, - Jar: r.Jar, - } - }) - - if r.Debug { - b, err2 := httputil.DumpRequestOut(req, true) - if err2 != nil { - return nil, err2 - } - r.logger.Debugf("%s\n", string(b)) - } - - var hasTimeout bool - pctx := operation.Context - if pctx == nil { - pctx = r.Context - } else { - hasTimeout = true - } - if pctx == nil { - pctx = context.Background() - } - var ctx context.Context - var cancel context.CancelFunc - if hasTimeout { - ctx, cancel = context.WithCancel(pctx) - } else { - ctx, cancel = context.WithTimeout(pctx, request.timeout) - } - defer cancel() - - client := operation.Client - if client == nil { - client = r.client - } - if r.do == nil { - r.do = ctxhttp.Do - } - res, err := r.do(ctx, client, req) // make requests, by default follows 10 redirects before failing - if err != nil { - return nil, err - } - defer res.Body.Close() - - if r.Debug { - b, err2 := httputil.DumpResponse(res, true) - if err2 != nil { - return nil, err2 - } - r.logger.Debugf("%s\n", string(b)) - } - - ct := res.Header.Get(runtime.HeaderContentType) - if ct == "" { // this should really really never occur - ct = r.DefaultMediaType - } - - mt, _, err := mime.ParseMediaType(ct) - if err != nil { - return nil, fmt.Errorf("parse content type: %s", err) - } - - cons, ok := r.Consumers[mt] - if !ok { - // scream about not knowing what to do - return nil, fmt.Errorf("no consumer: %q", ct) - } - return readResponse.ReadResponse(response{res}, cons) -} - -// SetDebug changes the debug flag. -// It ensures that client and middlewares have the set debug level. -func (r *Runtime) SetDebug(debug bool) { - r.Debug = debug - middleware.Debug = debug -} - -// SetLogger changes the logger stream. -// It ensures that client and middlewares use the same logger. -func (r *Runtime) SetLogger(logger logger.Logger) { - r.logger = logger - middleware.Logger = logger -} diff --git a/vendor/github.com/go-openapi/runtime/client/runtime_test.go b/vendor/github.com/go-openapi/runtime/client/runtime_test.go deleted file mode 100644 index 80a52794c..000000000 --- a/vendor/github.com/go-openapi/runtime/client/runtime_test.go +++ /dev/null @@ -1,810 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package client - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "errors" - "io/ioutil" - "net/http" - "net/http/cookiejar" - "net/http/httptest" - "net/url" - "os" - "testing" - "time" - - "golang.org/x/net/context" - - "crypto/x509" - "encoding/pem" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// task This describes a task. Tasks require a content property to be set. -type task struct { - - // Completed - Completed bool `json:"completed" xml:"completed"` - - // Content Task content can contain [GFM](https://help.github.com/articles/github-flavored-markdown/). - Content string `json:"content" xml:"content"` - - // ID This id property is autogenerated when a task is created. - ID int64 `json:"id" xml:"id"` -} - -func TestRuntime_TLSAuthConfig(t *testing.T) { - var opts TLSClientOptions - opts.CA = "../fixtures/certs/myCA.crt" - opts.Key = "../fixtures/certs/myclient.key" - opts.Certificate = "../fixtures/certs/myclient.crt" - opts.ServerName = "somewhere" - - cfg, err := TLSClientAuth(opts) - if assert.NoError(t, err) { - if assert.NotNil(t, cfg) { - assert.Len(t, cfg.Certificates, 1) - assert.NotNil(t, cfg.RootCAs) - assert.Equal(t, "somewhere", cfg.ServerName) - } - } -} - -func TestRuntime_TLSAuthConfigWithRSAKey(t *testing.T) { - - keyPem, err := ioutil.ReadFile("../fixtures/certs/myclient.key") - require.NoError(t, err) - - keyDer, _ := pem.Decode(keyPem) - require.NotNil(t, keyDer) - - key, err := x509.ParsePKCS1PrivateKey(keyDer.Bytes) - require.NoError(t, err) - - certPem, err := ioutil.ReadFile("../fixtures/certs/myclient.crt") - require.NoError(t, err) - - certDer, _ := pem.Decode(certPem) - require.NotNil(t, certDer) - - cert, err := x509.ParseCertificate(certDer.Bytes) - - var opts TLSClientOptions - opts.LoadedKey = key - opts.LoadedCertificate = cert - - cfg, err := TLSClientAuth(opts) - if assert.NoError(t, err) { - if assert.NotNil(t, cfg) { - assert.Len(t, cfg.Certificates, 1) - } - } -} - -func TestRuntime_TLSAuthConfigWithECKey(t *testing.T) { - - keyPem, err := ioutil.ReadFile("../fixtures/certs/myclient-ecc.key") - require.NoError(t, err) - - _, remainder := pem.Decode(keyPem) - keyDer, _ := pem.Decode(remainder) - require.NotNil(t, keyDer) - - key, err := x509.ParseECPrivateKey(keyDer.Bytes) - require.NoError(t, err) - - certPem, err := ioutil.ReadFile("../fixtures/certs/myclient-ecc.crt") - require.NoError(t, err) - - certDer, _ := pem.Decode(certPem) - require.NotNil(t, certDer) - - cert, err := x509.ParseCertificate(certDer.Bytes) - - var opts TLSClientOptions - opts.LoadedKey = key - opts.LoadedCertificate = cert - - cfg, err := TLSClientAuth(opts) - if assert.NoError(t, err) { - if assert.NotNil(t, cfg) { - assert.Len(t, cfg.Certificates, 1) - } - } -} - -func TestRuntime_TLSAuthConfigWithLoadedCA(t *testing.T) { - - certPem, err := ioutil.ReadFile("../fixtures/certs/myCA.crt") - require.NoError(t, err) - - block, _ := pem.Decode(certPem) - require.NotNil(t, block) - - cert, err := x509.ParseCertificate(block.Bytes) - require.NoError(t, err) - - var opts TLSClientOptions - opts.LoadedCA = cert - - cfg, err := TLSClientAuth(opts) - if assert.NoError(t, err) { - if assert.NotNil(t, cfg) { - assert.NotNil(t, cfg.RootCAs) - } - } -} - -func TestRuntime_Concurrent(t *testing.T) { - // test that it can make a simple request - // and get the response for it. - // defaults all the way down - result := []task{ - {false, "task 1 content", 1}, - {false, "task 2 content", 2}, - } - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime) - rw.WriteHeader(http.StatusOK) - jsongen := json.NewEncoder(rw) - _ = jsongen.Encode(result) - })) - defer server.Close() - - rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { - return nil - }) - - hu, _ := url.Parse(server.URL) - rt := New(hu.Host, "/", []string{"http"}) - resCC := make(chan interface{}) - errCC := make(chan error) - var res interface{} - var err error - - for j := 0; j < 6; j++ { - go func() { - resC := make(chan interface{}) - errC := make(chan error) - - go func() { - var resp interface{} - var errp error - for i := 0; i < 3; i++ { - resp, errp = rt.Submit(&runtime.ClientOperation{ - ID: "getTasks", - Method: "GET", - PathPattern: "/", - Params: rwrtr, - Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []task - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err - } - return result, nil - } - return nil, errors.New("Generic error") - }), - }) - <-time.After(100 * time.Millisecond) - } - resC <- resp - errC <- errp - }() - resCC <- <-resC - errCC <- <-errC - }() - } - - c := 6 - for c > 0 { - res = <-resCC - err = <-errCC - c-- - } - - if assert.NoError(t, err) { - assert.IsType(t, []task{}, res) - actual := res.([]task) - assert.EqualValues(t, result, actual) - } -} - -func TestRuntime_Canary(t *testing.T) { - // test that it can make a simple request - // and get the response for it. - // defaults all the way down - result := []task{ - {false, "task 1 content", 1}, - {false, "task 2 content", 2}, - } - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime) - rw.WriteHeader(http.StatusOK) - jsongen := json.NewEncoder(rw) - _ = jsongen.Encode(result) - })) - defer server.Close() - - rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { - return nil - }) - - hu, _ := url.Parse(server.URL) - rt := New(hu.Host, "/", []string{"http"}) - res, err := rt.Submit(&runtime.ClientOperation{ - ID: "getTasks", - Method: "GET", - PathPattern: "/", - Params: rwrtr, - Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []task - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err - } - return result, nil - } - return nil, errors.New("Generic error") - }), - }) - - if assert.NoError(t, err) { - assert.IsType(t, []task{}, res) - actual := res.([]task) - assert.EqualValues(t, result, actual) - } -} - -type tasks struct { - Tasks []task `xml:"task"` -} - -func TestRuntime_XMLCanary(t *testing.T) { - // test that it can make a simple XML request - // and get the response for it. - result := tasks{ - Tasks: []task{ - {false, "task 1 content", 1}, - {false, "task 2 content", 2}, - }, - } - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - rw.Header().Add(runtime.HeaderContentType, runtime.XMLMime) - rw.WriteHeader(http.StatusOK) - xmlgen := xml.NewEncoder(rw) - _ = xmlgen.Encode(result) - })) - defer server.Close() - - rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { - return nil - }) - - hu, _ := url.Parse(server.URL) - rt := New(hu.Host, "/", []string{"http"}) - res, err := rt.Submit(&runtime.ClientOperation{ - ID: "getTasks", - Method: "GET", - PathPattern: "/", - Params: rwrtr, - Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result tasks - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err - } - return result, nil - } - return nil, errors.New("Generic error") - }), - }) - - if assert.NoError(t, err) { - assert.IsType(t, tasks{}, res) - actual := res.(tasks) - assert.EqualValues(t, result, actual) - } -} - -func TestRuntime_TextCanary(t *testing.T) { - // test that it can make a simple text request - // and get the response for it. - result := "1: task 1 content; 2: task 2 content" - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - rw.Header().Add(runtime.HeaderContentType, runtime.TextMime) - rw.WriteHeader(http.StatusOK) - _, _ = rw.Write([]byte(result)) - })) - defer server.Close() - - rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { - return nil - }) - - hu, _ := url.Parse(server.URL) - rt := New(hu.Host, "/", []string{"http"}) - res, err := rt.Submit(&runtime.ClientOperation{ - ID: "getTasks", - Method: "GET", - PathPattern: "/", - Params: rwrtr, - Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result string - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err - } - return result, nil - } - return nil, errors.New("Generic error") - }), - }) - - if assert.NoError(t, err) { - assert.IsType(t, "", res) - actual := res.(string) - assert.EqualValues(t, result, actual) - } -} - -type roundTripperFunc func(*http.Request) (*http.Response, error) - -func (fn roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { - return fn(req) -} - -func TestRuntime_CustomTransport(t *testing.T) { - rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { - return nil - }) - result := []task{ - {false, "task 1 content", 1}, - {false, "task 2 content", 2}, - } - - rt := New("localhost:3245", "/", []string{"ws", "wss", "https"}) - rt.Transport = roundTripperFunc(func(req *http.Request) (*http.Response, error) { - if req.URL.Scheme != "https" { - return nil, errors.New("this was not a https request") - } - var resp http.Response - resp.StatusCode = 200 - resp.Header = make(http.Header) - resp.Header.Set("content-type", "application/json") - buf := bytes.NewBuffer(nil) - enc := json.NewEncoder(buf) - _ = enc.Encode(result) - resp.Body = ioutil.NopCloser(buf) - return &resp, nil - }) - - res, err := rt.Submit(&runtime.ClientOperation{ - ID: "getTasks", - Method: "GET", - PathPattern: "/", - Schemes: []string{"ws", "wss", "https"}, - Params: rwrtr, - Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []task - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err - } - return result, nil - } - return nil, errors.New("Generic error") - }), - }) - - if assert.NoError(t, err) { - assert.IsType(t, []task{}, res) - actual := res.([]task) - assert.EqualValues(t, result, actual) - } -} - -func TestRuntime_CustomCookieJar(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - authenticated := false - for _, cookie := range req.Cookies() { - if cookie.Name == "sessionid" && cookie.Value == "abc" { - authenticated = true - } - } - if !authenticated { - username, password, ok := req.BasicAuth() - if ok && username == "username" && password == "password" { - authenticated = true - http.SetCookie(rw, &http.Cookie{Name: "sessionid", Value: "abc"}) - } - } - if authenticated { - rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime) - rw.WriteHeader(http.StatusOK) - jsongen := json.NewEncoder(rw) - _ = jsongen.Encode([]task{}) - } else { - rw.WriteHeader(http.StatusUnauthorized) - } - })) - defer server.Close() - - rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { - return nil - }) - - hu, _ := url.Parse(server.URL) - rt := New(hu.Host, "/", []string{"http"}) - rt.Jar, _ = cookiejar.New(nil) - - submit := func(authInfo runtime.ClientAuthInfoWriter) { - _, err := rt.Submit(&runtime.ClientOperation{ - ID: "getTasks", - Method: "GET", - PathPattern: "/", - Params: rwrtr, - AuthInfo: authInfo, - Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - return nil, nil - } - return nil, errors.New("Generic error") - }), - }) - - assert.NoError(t, err) - } - - submit(BasicAuth("username", "password")) - submit(nil) -} - -func TestRuntime_AuthCanary(t *testing.T) { - // test that it can make a simple request - // and get the response for it. - // defaults all the way down - result := []task{ - {false, "task 1 content", 1}, - {false, "task 2 content", 2}, - } - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - if req.Header.Get("Authorization") != "Bearer the-super-secret-token" { - rw.WriteHeader(400) - return - } - rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime) - rw.WriteHeader(http.StatusOK) - jsongen := json.NewEncoder(rw) - _ = jsongen.Encode(result) - })) - defer server.Close() - - rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { - return nil - }) - - hu, _ := url.Parse(server.URL) - - rt := New(hu.Host, "/", []string{"http"}) - res, err := rt.Submit(&runtime.ClientOperation{ - ID: "getTasks", - Params: rwrtr, - Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []task - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err - } - return result, nil - } - return nil, errors.New("Generic error") - }), - AuthInfo: BearerToken("the-super-secret-token"), - }) - - if assert.NoError(t, err) { - assert.IsType(t, []task{}, res) - actual := res.([]task) - assert.EqualValues(t, result, actual) - } -} - -func TestRuntime_PickConsumer(t *testing.T) { - result := []task{ - {false, "task 1 content", 1}, - {false, "task 2 content", 2}, - } - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - if req.Header.Get("Content-Type") != "application/octet-stream" { - rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8") - rw.WriteHeader(400) - return - } - rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8") - rw.WriteHeader(http.StatusOK) - jsongen := json.NewEncoder(rw) - _ = jsongen.Encode(result) - })) - defer server.Close() - - rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { - return req.SetBodyParam(bytes.NewBufferString("hello")) - }) - - hu, _ := url.Parse(server.URL) - rt := New(hu.Host, "/", []string{"http"}) - res, err := rt.Submit(&runtime.ClientOperation{ - ID: "getTasks", - Method: "POST", - PathPattern: "/", - Schemes: []string{"http"}, - ConsumesMediaTypes: []string{"application/octet-stream"}, - Params: rwrtr, - Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []task - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err - } - return result, nil - } - return nil, errors.New("Generic error") - }), - AuthInfo: BearerToken("the-super-secret-token"), - }) - - if assert.NoError(t, err) { - assert.IsType(t, []task{}, res) - actual := res.([]task) - assert.EqualValues(t, result, actual) - } -} - -func TestRuntime_ContentTypeCanary(t *testing.T) { - // test that it can make a simple request - // and get the response for it. - // defaults all the way down - result := []task{ - {false, "task 1 content", 1}, - {false, "task 2 content", 2}, - } - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - if req.Header.Get("Authorization") != "Bearer the-super-secret-token" { - rw.WriteHeader(400) - return - } - rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8") - rw.WriteHeader(http.StatusOK) - jsongen := json.NewEncoder(rw) - _ = jsongen.Encode(result) - })) - defer server.Close() - - rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { - return nil - }) - - hu, _ := url.Parse(server.URL) - rt := New(hu.Host, "/", []string{"http"}) - rt.do = nil - res, err := rt.Submit(&runtime.ClientOperation{ - ID: "getTasks", - Method: "GET", - PathPattern: "/", - Schemes: []string{"http"}, - Params: rwrtr, - Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []task - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err - } - return result, nil - } - return nil, errors.New("Generic error") - }), - AuthInfo: BearerToken("the-super-secret-token"), - }) - - if assert.NoError(t, err) { - assert.IsType(t, []task{}, res) - actual := res.([]task) - assert.EqualValues(t, result, actual) - } -} - -func TestRuntime_ChunkedResponse(t *testing.T) { - // test that it can make a simple request - // and get the response for it. - // defaults all the way down - result := []task{ - {false, "task 1 content", 1}, - {false, "task 2 content", 2}, - } - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - if req.Header.Get("Authorization") != "Bearer the-super-secret-token" { - rw.WriteHeader(400) - return - } - rw.Header().Add(runtime.HeaderTransferEncoding, "chunked") - rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8") - rw.WriteHeader(http.StatusOK) - jsongen := json.NewEncoder(rw) - _ = jsongen.Encode(result) - })) - defer server.Close() - - rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { - return nil - }) - - //specDoc, err := spec.Load("../../fixtures/codegen/todolist.simple.yml") - hu, _ := url.Parse(server.URL) - - rt := New(hu.Host, "/", []string{"http"}) - res, err := rt.Submit(&runtime.ClientOperation{ - ID: "getTasks", - Method: "GET", - PathPattern: "/", - Schemes: []string{"http"}, - Params: rwrtr, - Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if response.Code() == 200 { - var result []task - if err := consumer.Consume(response.Body(), &result); err != nil { - return nil, err - } - return result, nil - } - return nil, errors.New("Generic error") - }), - AuthInfo: BearerToken("the-super-secret-token"), - }) - - if assert.NoError(t, err) { - assert.IsType(t, []task{}, res) - actual := res.([]task) - assert.EqualValues(t, result, actual) - } -} - -func TestRuntime_DebugValue(t *testing.T) { - original := os.Getenv("DEBUG") - - // Emtpy DEBUG means Debug is False - _ = os.Setenv("DEBUG", "") - runtime := New("", "/", []string{"https"}) - assert.False(t, runtime.Debug) - - // Non-Empty Debug means Debug is True - - _ = os.Setenv("DEBUG", "1") - runtime = New("", "/", []string{"https"}) - assert.True(t, runtime.Debug) - - _ = os.Setenv("DEBUG", "true") - runtime = New("", "/", []string{"https"}) - assert.True(t, runtime.Debug) - - _ = os.Setenv("DEBUG", "foo") - runtime = New("", "/", []string{"https"}) - assert.True(t, runtime.Debug) - - // Make sure DEBUG is initial value once again - _ = os.Setenv("DEBUG", original) -} - -func TestRuntime_OverrideScheme(t *testing.T) { - runtime := New("", "/", []string{"https"}) - sch := runtime.pickScheme([]string{"http"}) - assert.Equal(t, "https", sch) -} - -func TestRuntime_OverrideClient(t *testing.T) { - client := &http.Client{} - runtime := NewWithClient("", "/", []string{"https"}, client) - var i int - runtime.clientOnce.Do(func() { i++ }) - assert.Equal(t, client, runtime.client) - assert.Equal(t, 0, i) -} - -func TestRuntime_OverrideClientOperation(t *testing.T) { - client := &http.Client{} - rt := NewWithClient("", "/", []string{"https"}, client) - var i int - rt.clientOnce.Do(func() { i++ }) - assert.Equal(t, client, rt.client) - assert.Equal(t, 0, i) - - var seen *http.Client - rt.do = func(_ context.Context, cl *http.Client, _ *http.Request) (*http.Response, error) { - seen = cl - res := new(http.Response) - res.StatusCode = 200 - res.Body = ioutil.NopCloser(bytes.NewBufferString("OK")) - return res, nil - } - - client2 := new(http.Client) - client2.Timeout = 3 * time.Second - if assert.NotEqual(t, client, client2) { - _, err := rt.Submit(&runtime.ClientOperation{ - Client: client2, - Params: runtime.ClientRequestWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { - return nil - }), - Reader: runtime.ClientResponseReaderFunc(func(_ runtime.ClientResponse, _ runtime.Consumer) (interface{}, error) { - return nil, nil - }), - }) - if assert.NoError(t, err) { - - assert.Equal(t, client2, seen) - } - } -} - -func TestRuntime_PreserveTrailingSlash(t *testing.T) { - var redirected bool - - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - rw.Header().Add(runtime.HeaderContentType, runtime.JSONMime+";charset=utf-8") - - if req.URL.Path == "/api/tasks" { - redirected = true - return - } - if req.URL.Path == "/api/tasks/" { - rw.WriteHeader(http.StatusOK) - } - })) - defer server.Close() - - hu, _ := url.Parse(server.URL) - - rt := New(hu.Host, "/", []string{"http"}) - - rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error { - return nil - }) - - _, err := rt.Submit(&runtime.ClientOperation{ - ID: "getTasks", - Method: "GET", - PathPattern: "/api/tasks/", - Params: rwrtr, - Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - if redirected { - return nil, errors.New("expected Submit to preserve trailing slashes - this caused a redirect") - } - if response.Code() == http.StatusOK { - return nil, nil - } - return nil, errors.New("Generic error") - }), - }) - - assert.NoError(t, err) -} diff --git a/vendor/github.com/go-openapi/runtime/client_auth_info.go b/vendor/github.com/go-openapi/runtime/client_auth_info.go deleted file mode 100644 index c6c97d9a7..000000000 --- a/vendor/github.com/go-openapi/runtime/client_auth_info.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import "github.com/go-openapi/strfmt" - -// A ClientAuthInfoWriterFunc converts a function to a request writer interface -type ClientAuthInfoWriterFunc func(ClientRequest, strfmt.Registry) error - -// AuthenticateRequest adds authentication data to the request -func (fn ClientAuthInfoWriterFunc) AuthenticateRequest(req ClientRequest, reg strfmt.Registry) error { - return fn(req, reg) -} - -// A ClientAuthInfoWriter implementor knows how to write authentication info to a request -type ClientAuthInfoWriter interface { - AuthenticateRequest(ClientRequest, strfmt.Registry) error -} diff --git a/vendor/github.com/go-openapi/runtime/client_operation.go b/vendor/github.com/go-openapi/runtime/client_operation.go deleted file mode 100644 index ccf8ff722..000000000 --- a/vendor/github.com/go-openapi/runtime/client_operation.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "net/http" - - "golang.org/x/net/context" -) - -// ClientOperation represents the context for a swagger operation to be submitted to the transport -type ClientOperation struct { - ID string - Method string - PathPattern string - ProducesMediaTypes []string - ConsumesMediaTypes []string - Schemes []string - AuthInfo ClientAuthInfoWriter - Params ClientRequestWriter - Reader ClientResponseReader - Context context.Context - Client *http.Client -} - -// A ClientTransport implementor knows how to submit Request objects to some destination -type ClientTransport interface { - //Submit(string, RequestWriter, ResponseReader, AuthInfoWriter) (interface{}, error) - Submit(*ClientOperation) (interface{}, error) -} diff --git a/vendor/github.com/go-openapi/runtime/client_request.go b/vendor/github.com/go-openapi/runtime/client_request.go deleted file mode 100644 index 029603eee..000000000 --- a/vendor/github.com/go-openapi/runtime/client_request.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "io" - "io/ioutil" - "net/url" - "time" - - "github.com/go-openapi/strfmt" -) - -// ClientRequestWriterFunc converts a function to a request writer interface -type ClientRequestWriterFunc func(ClientRequest, strfmt.Registry) error - -// WriteToRequest adds data to the request -func (fn ClientRequestWriterFunc) WriteToRequest(req ClientRequest, reg strfmt.Registry) error { - return fn(req, reg) -} - -// ClientRequestWriter is an interface for things that know how to write to a request -type ClientRequestWriter interface { - WriteToRequest(ClientRequest, strfmt.Registry) error -} - -// ClientRequest is an interface for things that know how to -// add information to a swagger client request -type ClientRequest interface { - SetHeaderParam(string, ...string) error - - SetQueryParam(string, ...string) error - - SetFormParam(string, ...string) error - - SetPathParam(string, string) error - - GetQueryParams() url.Values - - SetFileParam(string, ...NamedReadCloser) error - - SetBodyParam(interface{}) error - - SetTimeout(time.Duration) error - - GetMethod() string - - GetPath() string - - GetBody() []byte -} - -// NamedReadCloser represents a named ReadCloser interface -type NamedReadCloser interface { - io.ReadCloser - Name() string -} - -// NamedReader creates a NamedReadCloser for use as file upload -func NamedReader(name string, rdr io.Reader) NamedReadCloser { - rc, ok := rdr.(io.ReadCloser) - if !ok { - rc = ioutil.NopCloser(rdr) - } - return &namedReadCloser{ - name: name, - cr: rc, - } -} - -type namedReadCloser struct { - name string - cr io.ReadCloser -} - -func (n *namedReadCloser) Close() error { - return n.cr.Close() -} -func (n *namedReadCloser) Read(p []byte) (int, error) { - return n.cr.Read(p) -} -func (n *namedReadCloser) Name() string { - return n.name -} diff --git a/vendor/github.com/go-openapi/runtime/client_request_test.go b/vendor/github.com/go-openapi/runtime/client_request_test.go deleted file mode 100644 index f76dcaddd..000000000 --- a/vendor/github.com/go-openapi/runtime/client_request_test.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "net/http" - "net/url" - "testing" - "time" - - "github.com/go-openapi/strfmt" - "github.com/stretchr/testify/assert" -) - -type trw struct { - Headers http.Header - Body interface{} -} - -func (t *trw) SetHeaderParam(name string, values ...string) error { - if t.Headers == nil { - t.Headers = make(http.Header) - } - t.Headers.Set(name, values[0]) - return nil -} - -func (t *trw) SetQueryParam(_ string, _ ...string) error { return nil } - -func (t *trw) SetFormParam(_ string, _ ...string) error { return nil } - -func (t *trw) SetPathParam(_ string, _ string) error { return nil } - -func (t *trw) SetFileParam(_ string, _ ...NamedReadCloser) error { return nil } - -func (t *trw) SetBodyParam(body interface{}) error { - t.Body = body - return nil -} - -func (t *trw) SetTimeout(timeout time.Duration) error { - return nil -} - -func (t *trw) GetQueryParams() url.Values { return nil } - -func (t *trw) GetMethod() string { return "" } - -func (t *trw) GetPath() string { return "" } - -func (t *trw) GetBody() []byte { return nil } - -func TestRequestWriterFunc(t *testing.T) { - - hand := ClientRequestWriterFunc(func(r ClientRequest, reg strfmt.Registry) error { - _ = r.SetHeaderParam("blah", "blah blah") - _ = r.SetBodyParam(struct{ Name string }{"Adriana"}) - return nil - }) - - tr := new(trw) - _ = hand.WriteToRequest(tr, nil) - assert.Equal(t, "blah blah", tr.Headers.Get("blah")) - assert.Equal(t, "Adriana", tr.Body.(struct{ Name string }).Name) -} diff --git a/vendor/github.com/go-openapi/runtime/client_response.go b/vendor/github.com/go-openapi/runtime/client_response.go deleted file mode 100644 index 729e18b22..000000000 --- a/vendor/github.com/go-openapi/runtime/client_response.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "fmt" - "io" -) - -// A ClientResponse represents a client response -// This bridges between responses obtained from different transports -type ClientResponse interface { - Code() int - Message() string - GetHeader(string) string - Body() io.ReadCloser -} - -// A ClientResponseReaderFunc turns a function into a ClientResponseReader interface implementation -type ClientResponseReaderFunc func(ClientResponse, Consumer) (interface{}, error) - -// ReadResponse reads the response -func (read ClientResponseReaderFunc) ReadResponse(resp ClientResponse, consumer Consumer) (interface{}, error) { - return read(resp, consumer) -} - -// A ClientResponseReader is an interface for things want to read a response. -// An application of this is to create structs from response values -type ClientResponseReader interface { - ReadResponse(ClientResponse, Consumer) (interface{}, error) -} - -// NewAPIError creates a new API error -func NewAPIError(opName string, payload interface{}, code int) *APIError { - return &APIError{ - OperationName: opName, - Response: payload, - Code: code, - } -} - -// APIError wraps an error model and captures the status code -type APIError struct { - OperationName string - Response interface{} - Code int -} - -func (a *APIError) Error() string { - return fmt.Sprintf("%s (status %d): %+v ", a.OperationName, a.Code, a.Response) -} diff --git a/vendor/github.com/go-openapi/runtime/client_response_test.go b/vendor/github.com/go-openapi/runtime/client_response_test.go deleted file mode 100644 index 7422d349d..000000000 --- a/vendor/github.com/go-openapi/runtime/client_response_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "bytes" - "io" - "io/ioutil" - "testing" - - "github.com/stretchr/testify/assert" -) - -type response struct { -} - -func (r response) Code() int { - return 490 -} -func (r response) Message() string { - return "the message" -} -func (r response) GetHeader(_ string) string { - return "the header" -} -func (r response) Body() io.ReadCloser { - return ioutil.NopCloser(bytes.NewBufferString("the content")) -} - -func TestResponseReaderFunc(t *testing.T) { - var actual struct { - Header, Message, Body string - Code int - } - reader := ClientResponseReaderFunc(func(r ClientResponse, _ Consumer) (interface{}, error) { - b, _ := ioutil.ReadAll(r.Body()) - actual.Body = string(b) - actual.Code = r.Code() - actual.Message = r.Message() - actual.Header = r.GetHeader("blah") - return actual, nil - }) - _, _ = reader.ReadResponse(response{}, nil) - assert.Equal(t, "the content", actual.Body) - assert.Equal(t, "the message", actual.Message) - assert.Equal(t, "the header", actual.Header) - assert.Equal(t, 490, actual.Code) -} diff --git a/vendor/github.com/go-openapi/runtime/constants.go b/vendor/github.com/go-openapi/runtime/constants.go deleted file mode 100644 index fa9d45f7d..000000000 --- a/vendor/github.com/go-openapi/runtime/constants.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -const ( - // HeaderContentType represents a http content-type header, it's value is supposed to be a mime type - HeaderContentType = "Content-Type" - - // HeaderTransferEncoding represents a http transfer-encoding header. - HeaderTransferEncoding = "Transfer-Encoding" - - // HeaderAccept the Accept header - HeaderAccept = "Accept" - - charsetKey = "charset" - - // DefaultMime the default fallback mime type - DefaultMime = "application/octet-stream" - // JSONMime the json mime type - JSONMime = "application/json" - // YAMLMime the yaml mime type - YAMLMime = "application/x-yaml" - // XMLMime the xml mime type - XMLMime = "application/xml" - // TextMime the text mime type - TextMime = "text/plain" - // MultipartFormMime the multipart form mime type - MultipartFormMime = "multipart/form-data" - // URLencodedFormMime the url encoded form mime type - URLencodedFormMime = "application/x-www-form-urlencoded" -) diff --git a/vendor/github.com/go-openapi/runtime/discard.go b/vendor/github.com/go-openapi/runtime/discard.go deleted file mode 100644 index 0d390cfd6..000000000 --- a/vendor/github.com/go-openapi/runtime/discard.go +++ /dev/null @@ -1,9 +0,0 @@ -package runtime - -import "io" - -// DiscardConsumer does absolutely nothing, it's a black hole. -var DiscardConsumer = ConsumerFunc(func(_ io.Reader, _ interface{}) error { return nil }) - -// DiscardProducer does absolutely nothing, it's a black hole. -var DiscardProducer = ProducerFunc(func(_ io.Writer, _ interface{}) error { return nil }) diff --git a/vendor/github.com/go-openapi/runtime/file.go b/vendor/github.com/go-openapi/runtime/file.go deleted file mode 100644 index 85971c18c..000000000 --- a/vendor/github.com/go-openapi/runtime/file.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import "mime/multipart" - -// File represents an uploaded file. -type File struct { - Data multipart.File - Header *multipart.FileHeader -} - -// Read bytes from the file -func (f *File) Read(p []byte) (n int, err error) { - return f.Data.Read(p) -} - -// Close the file -func (f *File) Close() error { - return f.Data.Close() -} diff --git a/vendor/github.com/go-openapi/runtime/file_test.go b/vendor/github.com/go-openapi/runtime/file_test.go deleted file mode 100644 index dd602949f..000000000 --- a/vendor/github.com/go-openapi/runtime/file_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package runtime - -import ( - "io" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestFileImplementsIOReader(t *testing.T) { - var file interface{} = &File{} - expected := "that File implements io.Reader" - assert.Implements(t, new(io.Reader), file, expected) -} - -func TestFileImplementsIOReadCloser(t *testing.T) { - var file interface{} = &File{} - expected := "that File implements io.ReadCloser" - assert.Implements(t, new(io.ReadCloser), file, expected) -} diff --git a/vendor/github.com/go-openapi/runtime/fixtures/bugs/264/swagger.yml b/vendor/github.com/go-openapi/runtime/fixtures/bugs/264/swagger.yml deleted file mode 100644 index e26cd855c..000000000 --- a/vendor/github.com/go-openapi/runtime/fixtures/bugs/264/swagger.yml +++ /dev/null @@ -1,21 +0,0 @@ -swagger: '2.0' -info: - version: 1.0.0 - title: 'Test' -schemes: - - http -produces: - - application/json -consumes: - - application/json -paths: - /key/{id}: - delete: - parameters: - - name: id - in: path - type: integer - required: true - responses: - '200': - description: OK diff --git a/vendor/github.com/go-openapi/runtime/fixtures/certs/myCA.crt b/vendor/github.com/go-openapi/runtime/fixtures/certs/myCA.crt deleted file mode 100644 index 8851cac79..000000000 --- a/vendor/github.com/go-openapi/runtime/fixtures/certs/myCA.crt +++ /dev/null @@ -1,29 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIE/TCCAuWgAwIBAgIJAJ0kpLFo4pEzMA0GCSqGSIb3DQEBCwUAMBUxEzARBgNV -BAMMCkdvIFN3YWdnZXIwHhcNMTYxMjIxMDgzMzM4WhcNMTgxMjIxMDgzMzM4WjAV -MRMwEQYDVQQDDApHbyBTd2FnZ2VyMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC -CgKCAgEAzQ5NC1JBNNP79HPiUBAO59LoUMGbmSU9K9v+cQMuyyOuv0nwuiXc5anU -J1BINqgLR1VJjwTnQsXSlsr2SPs/144KgTsgk/QpMXdlFQwfqLJBIFlsQQBbMx6L -/2Ho6KE7z/qz6cqgKvYrGDu6ELUu016MbUsPWfhPBJE7Ftoajk5AIomDPmiTi0cZ -wdhC8SB0aVVQ2IWrsusfgPeOQ+ZLa/WHmpJ2Syfq41i/VKllEeCrMwtMP2By2kA/ -ufBLCnhr7yZ0u22O1Bl1+0XedWli2GiXyt1h9nQ5blTTKZi5grOzAgCcshb/bw1H -1hdJKMqkzbqt2Mxc/78PJbDgicJU1ap+fhfBmUviWIMML6eum2ObuKd4ihhXKfqp -T/nSUA0P9565W71SLAHFLdZX/VSMZnoehkwIicVGgEzjlYj2j9qBc0CjYzbEtQXH -TRGhbjMX5LSByeE6hwLM6hIbQL4nriRobar63rbOc74Tm1ed02R6BvQjgXgOGqAN -BgCKKjfUIm0Qm2qV4WkwGIAOi+hdUpbNJ0X2dU/B00qLhar+h4NT9TW4PmKf4agk -NZ6O3C1saGxjtuPnIdDxWTdRhPSUyjsllmWhrmkY2bsRB8Z47zqrdfyajXlPOmBM -1f0am4Zeo3ditBTfFqtA2LLQbn1yZwYJQ8+sESu6bsm3S89DFT0CAwEAAaNQME4w -HQYDVR0OBBYEFN4BShcjqDbbgaGvPiGMNrUEi/RZMB8GA1UdIwQYMBaAFN4BShcj -qDbbgaGvPiGMNrUEi/RZMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggIB -AIqZYn+PFMcOwraYtXtAzJwU4gElWDjIA+xVMMzulHde8t7EWo+I5iDdtn+sHzhG -B1oYFhKv/HIX9GR3XDYWluoUVA4Ed9eBamL0Qqzq4Era6ZN1VQd0egvyOT40UQ7m -2aNw1nLgWadCmsxeVMKQRdzct9G3dOfJp7K5WybINWTibNMTuoSuU5RwtzriK000 -C9pnxCD8boSNY/flOX0M5Mt3kv2JaIH2UsMKNGBf5+rXcKfhTE6JgiXorUEEztHP -PFpZ6VFKDlr8QC/4aLYhOJ9LIloaxZyk/rccCuHbdPPX5XGA3Z9i/lxSoqtShYlS -mt5vmdRwQob/ul6hPch3YRqD4VgeM1O80FEsWBK2WmGGH3wKNKea7u6dZyfQv3t3 -fUVmByAVMllVRA1YiKmBZ/kOeAMku5hpR9kzErCXZd/xrKWVym000RsvRb6apltM -sYnlCyKfIdKxUXavO0Bf4+YoaN4/p3mZchxpLBwrzhPyUpGQ9b3TuGjoEmtG57yn -6I3U40/TouJR0aF7i1bAF5QJWYOS7OycJbHAIZiQx9ENDP3ZMfYNWQO6STFJAjvC -C0u23DyiJWZqE4Uw51O7jWKh7bSEKWutwa0XKWrpxhUjHFX4qGigIvXpO9LMjR60 -YDhdCEmUiu/Hc0tt0QzyTA6w47TP0gXREeBLabzuEDPi ------END CERTIFICATE----- diff --git a/vendor/github.com/go-openapi/runtime/fixtures/certs/myCA.key b/vendor/github.com/go-openapi/runtime/fixtures/certs/myCA.key deleted file mode 100644 index 0a8547864..000000000 --- a/vendor/github.com/go-openapi/runtime/fixtures/certs/myCA.key +++ /dev/null @@ -1,51 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIJKgIBAAKCAgEAzQ5NC1JBNNP79HPiUBAO59LoUMGbmSU9K9v+cQMuyyOuv0nw -uiXc5anUJ1BINqgLR1VJjwTnQsXSlsr2SPs/144KgTsgk/QpMXdlFQwfqLJBIFls -QQBbMx6L/2Ho6KE7z/qz6cqgKvYrGDu6ELUu016MbUsPWfhPBJE7Ftoajk5AIomD -PmiTi0cZwdhC8SB0aVVQ2IWrsusfgPeOQ+ZLa/WHmpJ2Syfq41i/VKllEeCrMwtM -P2By2kA/ufBLCnhr7yZ0u22O1Bl1+0XedWli2GiXyt1h9nQ5blTTKZi5grOzAgCc -shb/bw1H1hdJKMqkzbqt2Mxc/78PJbDgicJU1ap+fhfBmUviWIMML6eum2ObuKd4 -ihhXKfqpT/nSUA0P9565W71SLAHFLdZX/VSMZnoehkwIicVGgEzjlYj2j9qBc0Cj -YzbEtQXHTRGhbjMX5LSByeE6hwLM6hIbQL4nriRobar63rbOc74Tm1ed02R6BvQj -gXgOGqANBgCKKjfUIm0Qm2qV4WkwGIAOi+hdUpbNJ0X2dU/B00qLhar+h4NT9TW4 -PmKf4agkNZ6O3C1saGxjtuPnIdDxWTdRhPSUyjsllmWhrmkY2bsRB8Z47zqrdfya -jXlPOmBM1f0am4Zeo3ditBTfFqtA2LLQbn1yZwYJQ8+sESu6bsm3S89DFT0CAwEA -AQKCAgAjBkBOoLwWg+bTOD/9oOCK5FFeCdPD8sJiDW+Gah7B/9RHRB/kC7eRWtKr -7GCJRWa3xm+MCDBgDV4M95ndmVysOsy8ihbkbp3inxwa3jlCHUBWgC+nYqIxNxR+ -iIC5y2BmA9JbKor1C5sMxpbfZ7MZ01p1CI8UtP76LrxDCPnkOKVnwMk0DbS1420Y -2RGGEh8QJsxqT1qmctastpwMKPfU9tk0o7Ok3qqWLoBvu4dR6GgVjeZ2JMk5UiQQ -ZGTM4wi8jnr90JbGz5qBUsvOjjOd9y+GLQ4ghHWSzNZMkpONKZh3zRb2rErw8vnE -LbIHT6Wapjovf6ia3k1+CJoxrYnDrsOHcWopm2kle7FXjgfHRXubcNU2aLdIAcRg -ZGGyalex3/NXKjhGf8jhaXKkOYDL37ZFtEmaUJVjjhiIE5jGByBHU0pqKk9Tdtv0 -s5r5m0T8Gk8h70+fZ/C+wkYE4h8uzqAlq/yrxBSlGMHEVG9PI9tr9bM1FLM/H92q -CqoVR6YWTC7o5Kasr33RKYJg5vPHfFoIGHX9etbfHPGQsbCLaWhTLIYus+0b4ZS1 -D1jHCoxHCjKzf2PFwogtRsmhyQSS3A3GyEWy7BZgFvgKFpq9hRC66k8Z7pnnkKrW -i4YihK17ivI5uG67Aqlc+kdahRNVWOOaPbwjGosmlULyfCOdGQKCAQEA79dD3caa -zXqFQkYDZwZcthXw9Hn+ChTCcfucJz9I0DUeL8FpUQYCkFZRUoEgF/eNrKSG+ctn -VDgrj0IZAcumpfjc4ZMug8svFYkE+vsUVgSI03KPRJ5NZ+Egn+HExURzCSQY6fK8 -mCp05+gXndiUhoco2H851esmMtCSd/5IyR3d3C64ZfFGSk/Nx66A4Z643ffB6tOH -KYWFgVoQtSb92pgyxuBzZ1JhxuBVihRzAQtuE+uZ14xPoVv52fUlYXUhGmdqtZ3l -Cio3YGZTaUqtF0BP8HshzAWQ2k2vCJUxY99dbFfsE+v8vCojgMz8KmzO7C+j3Pa1 -hq77rT29WFvaHwKCAQEA2t8R3QCkcaCRDMAPomqPJjUHrX2gdPM2zFFCvSqiVkh6 -8ft9NF8sO1aXq600IxTiTf/L8ZvM0HlPlYQSjFzGWsOgNww9MKF7L4NnJ7e/8mwP -jqfajNcqecHIXvNi0AqXOpN/hEhm5MWKce/BPV6GpnRnb5doy8wOG0ESsmUA/5TJ -y/65LVxDKT9SdymDVayRwq2vNn9qW2BBcM9yan5GstkE3zzkrzKcCgz5X09/vO3R -K3fYk0FReE9CY9XAQGtz36Ra19efETzvWPi18zsP96QMUYIS2+Y45sVPhGZbY2aG -HQXTg8xIJN51E+jmWpJ1vv27izFh5TXeloRD4qldIwKCAQEAqkG6+KVy4OjXzlsb -MTiP+eaLfVFYaFmiSv3dNPM0wjDi8+2t0Imeqk3MPvBRExJ17ReChbLB8ERLj8/R -Jrgl3e5TBoLP41kKXJQ/B9fS8NkZNFk/oOtrcZGb8kN3xr23l8abNQBOpwqEoNfe -Y/wKO5GZCk8OhHAAVtQ/FZVaoAJmq1YzKpLjXf9WyihzbzaYb2Hgs81jRrN1OYTx -FVfPnyyp5woQgkk2BdLchj/L//LYOqXmOOBu6tH7BKGE3rEiRbciRjkHDXc4hmM9 -VSJgy3+o/8K5FDbjREUfOs2GGSrIDBBCE0ZTzFNxjo51d7x0C7Ap98Ley/RNzwZj -8mSJ6wKCAQEA0NXvcXPfdBvEyumnAU2zcL1AqiUoKO635pPSnjRD2RgnVySi/omg -5q1k4oXNLXwLwmjD67DA6FoXuY3fNNaA3LGz+VJQQEqUA23Zy2fkWicJYRB/08qp -2KsxyIdqTR8N1PJPxaRfqQFja/tb4naC++gtmahacbot64tXj6gYH8WUFnThs4pI -+t5UjSarDeAu5BZdDB7fGHjrd/w4K6x5QMUZhPfRK+maQWzHtE1ikJ5J6rPbjgXQ -+n6F1kRpwA3G7ikgFLrEJ+qAZeBJm99LCPsaVdtKq08sE+VITghsQpfcd2zLuQH+ -BE/OXkTnJpyAhNANVm6z/cQ8sllZfLglCQKCAQEAkZTQ0xnUeJTV0CqljMNCIN4M -i6Xyqf5uUDPfooY+fILbemT/acYUAkbjamgJlQMQ7yui9WV7Q/9HiCHaVh3o5zrV -zaq3vocA9x9nK998/He7772/uJarINvLFj/p/vTQM4Lni+bJ93bk6XE+FQKPgY9B -GfeFFaVtH7gimB4CjrxYprhAfqyxyE/m6JVMRg1olIFuav37GYP+TJ2K85klQRNa -TEXbm6ZJpSHfNjKZzUczziaIbwnMN9OxJY6M3a1JuEy2h+og5oRdMOoB6RETzhle -mxT5uEtA6mR6KyBZBjWhcl/V/Rw1DVMmtVbHCdc0+Xn/CMemRLCw1bxRUu/iww== ------END RSA PRIVATE KEY----- diff --git a/vendor/github.com/go-openapi/runtime/fixtures/certs/mycert1.crt b/vendor/github.com/go-openapi/runtime/fixtures/certs/mycert1.crt deleted file mode 100644 index 678531014..000000000 --- a/vendor/github.com/go-openapi/runtime/fixtures/certs/mycert1.crt +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIEqzCCApMCCQChJZEdSdrQkjANBgkqhkiG9w0BAQsFADAVMRMwEQYDVQQDDApH -byBTd2FnZ2VyMB4XDTE2MTIyMTA4MzMzOFoXDTE3MTIyMTA4MzMzOFowGjEYMBYG -A1UEAwwPZ29zd2FnZ2VyLmxvY2FsMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC -CgKCAgEAs1MHhleossLBkYKYwOT+82RT651CfCOilpEUhm92KGRSMQXZEk+2TUgc -dGPeQNDNmbpXGzdk1HZkqWR5XKfSjWWxfmBlbBoYnkL3neoiXBdBVsgHkEPdP5ly -uJRkohy6az1vnq2vLaI+YujStutf8hSdcPu9VeALbrR027dMbY2XMC97FteeVaw1 -mXmW9UHDVSV9UPBPswUOQWhjIADBk5IYaYASCY3M4X5BPCWFu1oQhgVMEhodBoBj -pHhHrfoDm1TwtT+dp53TmR10zpUiN+FcaVMsjqN4DWX4ma0uhu+zJew2XjCJkNfX -wVqGFpe2Hx+lupOGs/kwBvQ4PYn5ydgcm5DTggBC45JxCAVi3tQCYGsg2xkX9yPj -aXYc8E4/aeQI9UZxUeR2siBn8ECX4gJTmPJbQ4Xykqn6YOHyxIVoqd+9wo9Z1weH -xCWtPGESg7l7Jn/6WQ5V8z6RzrquGi67asrpYpv2lxNXMQA0f3S8sWYe4f8QVazy -ALtu8+0XE17UPjlbNBqEfCIrMsYmL5VyMVbL0dlXXBxHjzfpXraNGoSD4v6LxRxP -dWQgrhEZ6DmfiWfX8uhLdMwlvUxNXj33UDtM8dtN6mHERA9wF2RQQzPddZ0MYmUF -DI92i9mRC7Yzx6mcv/yUnFw213Jnzg297lW0Xp0ifawyPi2V8f8CAwEAATANBgkq -hkiG9w0BAQsFAAOCAgEAme1gyNQry3E5bj4XfdL4aNvZamzLaQVRlNZSHUzDhhpH -6N/DK/CAw4g4Msty7g3KBZPmldJhxH0bnSoRGMjFdKn9tVQeJOjaHQ2Z3cQWwdte -iXtu2F38SVfP5HCh9ASQ9vQXahGOruUPUUNUnDLfOBea7vrT3DmVugXlMSmaYuSJ -JdrbPzD48yy60AEDlCVpY2m1cEc5SmTkXbrAg2jhQd6ytaPQ28vGQnpZHSS/xWjC -Hh68o5SUoGoFErZxPd0o2brHavi4YybYt7CXlWG2TJ89s3BCSPIHclNF2HjxRq/r -2Q/Ttzo3cRBxi3RBnrLdn4qNgJjZnWaLobjaWcs1fbI32allogLsiurCwZb0ToC0 -fNMzyHVNWY8BqsuyWyF2H0F9rklmqGFJSmrqt8kDLx0xpkZchGPIDSRh+f+PPDmE -jGPPH2qxz4un0foJx99dtw18TPaplFo2LxRK89koTiQNyzAHwSn6PHGlyXhNPsUt -K5GzjAu6B4uyldcg2m+4O/dbNdeqSczYAFenfEO7PRAy3AP7Lxs2xqQaNiA10965 -vYmCNIOuV24CuFEIrjOQkZeFCw+odsgFs5Nv8JfDdA+BRr+Haq8FVX8afEc0BEnr -xY6f2fvgYTMvx0Z3UVT/XJ3POWHRL0HFLj5avHE0eOOkrcPbX6UsANd1v0F2BH8= ------END CERTIFICATE----- diff --git a/vendor/github.com/go-openapi/runtime/fixtures/certs/mycert1.key b/vendor/github.com/go-openapi/runtime/fixtures/certs/mycert1.key deleted file mode 100644 index 90cb03653..000000000 --- a/vendor/github.com/go-openapi/runtime/fixtures/certs/mycert1.key +++ /dev/null @@ -1,51 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIJKQIBAAKCAgEAs1MHhleossLBkYKYwOT+82RT651CfCOilpEUhm92KGRSMQXZ -Ek+2TUgcdGPeQNDNmbpXGzdk1HZkqWR5XKfSjWWxfmBlbBoYnkL3neoiXBdBVsgH -kEPdP5lyuJRkohy6az1vnq2vLaI+YujStutf8hSdcPu9VeALbrR027dMbY2XMC97 -FteeVaw1mXmW9UHDVSV9UPBPswUOQWhjIADBk5IYaYASCY3M4X5BPCWFu1oQhgVM -EhodBoBjpHhHrfoDm1TwtT+dp53TmR10zpUiN+FcaVMsjqN4DWX4ma0uhu+zJew2 -XjCJkNfXwVqGFpe2Hx+lupOGs/kwBvQ4PYn5ydgcm5DTggBC45JxCAVi3tQCYGsg -2xkX9yPjaXYc8E4/aeQI9UZxUeR2siBn8ECX4gJTmPJbQ4Xykqn6YOHyxIVoqd+9 -wo9Z1weHxCWtPGESg7l7Jn/6WQ5V8z6RzrquGi67asrpYpv2lxNXMQA0f3S8sWYe -4f8QVazyALtu8+0XE17UPjlbNBqEfCIrMsYmL5VyMVbL0dlXXBxHjzfpXraNGoSD -4v6LxRxPdWQgrhEZ6DmfiWfX8uhLdMwlvUxNXj33UDtM8dtN6mHERA9wF2RQQzPd -dZ0MYmUFDI92i9mRC7Yzx6mcv/yUnFw213Jnzg297lW0Xp0ifawyPi2V8f8CAwEA -AQKCAgBZtF8/RPqO8f4C3GGtnOAswTN52eE4WFstFsY9ueRRsF2tSE+eaWG4pyoU -zyCPK+St0hlg9ATsg403b5uGTi11rjlsDqyttyA5iyZzSHyHtNpqnwWplUlIV2qc -Cx+MOPLIUqNTrW7EVTUAJZfDCVulrcpUipncK4eMiZkrkDYbV4kaAaaBdrsuAEeP -ztNFPPCJ14coxg4Yb58B+UYc7EPpnlu36uka/mRPKOlZPSv43MUHRf8XzxhV+EPg -Moso7LiBK6x9/qTPBJSlM6cK8G99pK6lwYW4lO2pRilmNsvflGj5v4Ay/fTTECZO -AwqwopPoXdx5yPLJdQ4hbGn13t+k0pB4LYXl1xqLg2Z9QN+pgC2h41OrSx8Ozw9U -KTocbsMV6pafnMRoQ5Fjb+eTy4VE8rZl/OlMDX2cR2XL+a3ypIAA5E4KrYDiIBiU -MSA3EA3GsOOnyrV+fII+f2tVo/qDnvxQO/ZPUr/XG2xtJ+gqThWlrBft/O4/lCju -+kfNg8cMHtahGOmLz1ALsl32ANj5jTZmVOEs9xTG7+TeQ2RzWeBYTB7oNTMNIbaL -pTZTzxoeRyxx8sUvtaTb23IWSpRUiS4+F7Tn97g6ks8fYQPsVkl3WzXeECaL9uNN -hFkAwd0omD4TwQlmOUVm3IH7A0InTAaooC9jJfNqmhhHcLUAgQKCAQEA3N+pR1ed -aCXQit6bgw0rIF6RzjeGp6lLGaPdvCUM7sdAUwSGbFOgkcaw9TELFpCpfZGKFXI9 -IxPOwjFrURY4S2iuyAVv+Cw7trXW4BF1z+08M9RWYGLvyUsO7FIsGUmdYRtasb5L -IfHfGoXttadKWcdFMSF+25CUcbleyCNrJzXOzeMn1/UoN6+qfsyfaAD03nw/ZmhA -mK3UKjR7UOUPXt9gIXVivRaEQBakrLkJtK33fl1hztqxComE3/h6Qmj6iRmyxX3y -v3mzXbyC6jobq1tLUWpxvlQgoAyk+zZ0LNEHlkVfertaz0XdN/L2ZgjoGjJxfn/y -OK0a4jJyCpXXEwKCAQEAz9fJcpqaB25joZsqG+islNljyFjJRT9+E8IU97OglhJM -8T9TFs4RNsAxIqHwYm4KuoSlI4GhYeuOxGk6yUGm8cO314J7Wv4CAgZeJBcmxJUs -C8FbcXKbesK3VIuvATgzI9Vq/UF+GxJCkPctZJ9Oa0t578rVS4JH5ZJQdw2A77Lq -kGunMDboVY7EYDOn/fNMKGfcnH8KIQn/2b6CKLarj39b1fG7MeCuxPRejijaKtZI -ra5n0ofLluGo9HBXLgqgsjhjkSWU79lRypuKS8qOcjI08Xaw3Q8+qn0uLCARd8rN -2+mQy5OAZJCWpYIKPL6E41GaxcaTdOYzlOCs9Oz65QKCAQEAgSqzXitYvC1RFcU1 -AKDU1as4bXZ/YtFYP/halcq9E26mqWX+Dp+hSV7+4YT6zQlwdSSFsiEKq9bLlTk9 -X0A1T7Q6cnLrliCYEzOoI4VSdnRwPocwtFFnlTo10fIEJA2u4bkTgtqcKY+/P02P -RCo/Ct3EEwVZoKGejhsv2K8N3PJUrIbpKBwQlvA+LsUPe80DZpEWqpbRH/iYGM50 -R0yNfpf3KdnyEk52rNwRFYloqacLE3Uc29F8s4LUl/5B0VB/I2pJ58DOEzfiszCp -Br1QrRdIpqYvOnUMV0zNtrOToRnk6/ZJ7gZfBtP+mNeXTPhsc9WIFchRKN/i1uFV -W+dgzQKCAQEArcXTDdio85GeB1395PuyX3kqbjWdgiJFvStF8JvkpdSDNCknxSdh -SQ+DhVsz6nfqzGtezsLxNTeHVDxPBDm55OUobi0QCdHZx+ufBjm9FhtKikGNvNp/ -mDH4qd1n4nMkfs9O9pOtZeDsetvOvhRbsmWWe6BwmQNCLXUZhZBqvv4uE7WOQUeH -FRGaqnxF9pNWl2nPD6E/zMPZgCpCFNw1sHJhTA0h39/k/5L5A46waaRje6MX9vPG -ik39vvG2Ui5ckOWIibCMR8TBF87X3+ppEp1bmo8L7Kd0U4L5+baOJEQRvc4YW7zl -Wi9xZMvG12bLIGv4JWeTnediNRVsRhNk6QKCAQBXYkpxk6LTgP+b6FJ7fiImzDbH -QJ+RbBYJdgYLEarKWdWhNqj3YiDOUJt+ve13reybL4cLmOYoNzeUO9IHyGeTp+WV -gtPf1g2hm2TZannWsoTvnoXJ8yR52ZQQ5JusNosbmlrqWRAN8GhISdYTJDNcS2hD -PnVX/kaJfRDennokD+FWuyygua66LBdZi3UNgGMay15/2CCoC3PoejfQORxDyPP9 -am+e3/U6QG1/VWMHen3Mb0AZKwEBAwX1jL4EpoDZ+Y6jP0tbQ5xL7RivsUNtAVlQ -m7lumflcBy1WqkmviVJ9M2iFuo0HznuH1qlgOJpUiqZZjL/gEvkdDNMcQSmH ------END RSA PRIVATE KEY----- diff --git a/vendor/github.com/go-openapi/runtime/fixtures/certs/mycert1.req b/vendor/github.com/go-openapi/runtime/fixtures/certs/mycert1.req deleted file mode 100644 index ee4728f01..000000000 --- a/vendor/github.com/go-openapi/runtime/fixtures/certs/mycert1.req +++ /dev/null @@ -1,26 +0,0 @@ ------BEGIN CERTIFICATE REQUEST----- -MIIEXzCCAkcCAQAwGjEYMBYGA1UEAwwPZ29zd2FnZ2VyLmxvY2FsMIICIjANBgkq -hkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAs1MHhleossLBkYKYwOT+82RT651CfCOi -lpEUhm92KGRSMQXZEk+2TUgcdGPeQNDNmbpXGzdk1HZkqWR5XKfSjWWxfmBlbBoY -nkL3neoiXBdBVsgHkEPdP5lyuJRkohy6az1vnq2vLaI+YujStutf8hSdcPu9VeAL -brR027dMbY2XMC97FteeVaw1mXmW9UHDVSV9UPBPswUOQWhjIADBk5IYaYASCY3M -4X5BPCWFu1oQhgVMEhodBoBjpHhHrfoDm1TwtT+dp53TmR10zpUiN+FcaVMsjqN4 -DWX4ma0uhu+zJew2XjCJkNfXwVqGFpe2Hx+lupOGs/kwBvQ4PYn5ydgcm5DTggBC -45JxCAVi3tQCYGsg2xkX9yPjaXYc8E4/aeQI9UZxUeR2siBn8ECX4gJTmPJbQ4Xy -kqn6YOHyxIVoqd+9wo9Z1weHxCWtPGESg7l7Jn/6WQ5V8z6RzrquGi67asrpYpv2 -lxNXMQA0f3S8sWYe4f8QVazyALtu8+0XE17UPjlbNBqEfCIrMsYmL5VyMVbL0dlX -XBxHjzfpXraNGoSD4v6LxRxPdWQgrhEZ6DmfiWfX8uhLdMwlvUxNXj33UDtM8dtN -6mHERA9wF2RQQzPddZ0MYmUFDI92i9mRC7Yzx6mcv/yUnFw213Jnzg297lW0Xp0i -fawyPi2V8f8CAwEAAaAAMA0GCSqGSIb3DQEBCwUAA4ICAQB7U21HoBp5Qfrwd8aA -KzBY2BfEp5ouyn32kpfkB3Ha6+XJ69Lt1WHMSKnmYamlwZCSOS2uQ6DzdTLDfZpC -8PH5Gs32O9zJwUeSuYcUQGfcAenauu9gwC5ZnIbhOs5YTnEFquVsBqrNUKS+hLKJ -sAPtucoqlLX5qSkv/BOK2X4os90LAmx+yB/yarAzZOO0ku8qXt+MHI+rOMPLTmm9 -kYhtyXejQaXLOVbvQ9b2gxHvMcyLhklc4KpJPRfPzOdNebHsf5o4Em6lxeglGw/A -z05sBSAla69sEygcItZryQ4WjMRUpsLePXJrlSL5DYWGK6BX1gCkWtpXLqE1HgR3 -4L/xvaJQ5ZWpLoyJoJauU37Zhd5dLNGpNiSSEA0BKOjj9Kjm8nvsJE9DgziTaG57 -qFLRkMkDdBdb5wOfVYI/MY9zc+igrFPQJkQ0Xkdza8yXegBldv1JRe+49zifysea -Y/B+qWx8IpeHke0iEMqR6iWrw6oGBG/obHJ/V09DwC6iU8vot+pLr/bSyoUCUP30 -OEATJf50ic9oZYXgdT9oNBcAlAriuzoQuGi9nAKZJss6YkhooWoqXlXNQgAEc2gl -WF4fNumXwVaPVeW2q36Xk1btHz7k+IeVUg1jaPMPUJ+1dgIOZA7FcoYotvF6StyX -xoHybhvC7lbeif8EK7tJ2p4hug== ------END CERTIFICATE REQUEST----- diff --git a/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient-ecc.crt b/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient-ecc.crt deleted file mode 100644 index 3bd5545b7..000000000 --- a/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient-ecc.crt +++ /dev/null @@ -1,18 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIC3TCBxgIJAKElkR1J2tCUMA0GCSqGSIb3DQEBCwUAMBUxEzARBgNVBAMMCkdv -IFN3YWdnZXIwHhcNMTgwMTIyMTUyODA3WhcNMTkwMTIyMTUyODA3WjAYMRYwFAYD -VQQDDA1UZXN0IEVDQyBDZXJ0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAENlON -9ojzKxcMlsAIFcsc+JoMSOd1bREjEHAPaj77L0NjO6p605jT2TTLbj1lpDGD9XRc -vw5iiHvhF41Sl454wjANBgkqhkiG9w0BAQsFAAOCAgEAyYwVGVG/Jzei9zxmWT+k -LeK7OpGzOIyfBdEvQDFSfmyHoVJsR2LdicMJAI0gnVl5V0LdfBpu1MRz6Jdsto+u -RKL1WdygESzWQ/LtqvT4rb5vLhkpCBY6Ua+SoTpY/93iOZpf1ArKOtHzL4Xop2Lb -6/0hHYU73vaBjd9YnA3T0jVFsI/otpfJhSY8FGdKSYKMf6rob9+iv2Tyjm1svkV0 -IBL0D0v/LlGeM8UqXC3ZLaHsTxWi2v6PNfRyFnSNoRX4+I9ejjYvjIKQ9giVcPFQ -SfhR5xm0C0xxYVqoIb6gX6owlmX2duIaV6qjU5YSzwEZqkv0Ze9i+zztBVqBRA7q -fC/AMSxtqo4+Faj+hxX9T4D15hysx76uS7LxCi8GkypSZTGkjhHdMRKa2jIEvW3A -9nKW4nnC5sEBDrOTwaH4Mn6zFik3r9LTfh1gljLu9Ieqizb1gXloFhWJYvC2UwXO -ins3tX2VYBF7p6yIXRmc5nZlpFErGqu2MR/lwJKD6zGIJOzCza/4DP+Mppw+DSPN -XkNJG05uymsaEZceupeBH0uCgVSuVaZ3nfA73RM+0evxsscii/Kw/VFNvNDy5fLg -OQWRm6RlBTK2dRqpsfo9irjdd6NVC0EfqZceYIte/eWn9aPU5uTy/TzRG24ouKtY -Ixs1usnXCabNN/n0AMI+xVc= ------END CERTIFICATE----- diff --git a/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient-ecc.csr b/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient-ecc.csr deleted file mode 100644 index 3f698e073..000000000 --- a/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient-ecc.csr +++ /dev/null @@ -1,7 +0,0 @@ ------BEGIN CERTIFICATE REQUEST----- -MIHSMHoCAQAwGDEWMBQGA1UEAwwNVGVzdCBFQ0MgQ2VydDBZMBMGByqGSM49AgEG -CCqGSM49AwEHA0IABDZTjfaI8ysXDJbACBXLHPiaDEjndW0RIxBwD2o++y9DYzuq -etOY09k0y249ZaQxg/V0XL8OYoh74ReNUpeOeMKgADAKBggqhkjOPQQDAgNIADBF -AiEAsqdXJEIuedKkuiavgfc0YXssFWBORAC37F5w+Z0kGEMCIDRGiCaZG4Z/Gutm -id7N5T0Uxah0p5i6OzvCpYPN8f3Y ------END CERTIFICATE REQUEST----- diff --git a/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient-ecc.key b/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient-ecc.key deleted file mode 100644 index c123550d6..000000000 --- a/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient-ecc.key +++ /dev/null @@ -1,8 +0,0 @@ ------BEGIN EC PARAMETERS----- -BggqhkjOPQMBBw== ------END EC PARAMETERS----- ------BEGIN EC PRIVATE KEY----- -MHcCAQEEIJyZvFqw3os7TVGOSvK8XM1qysN32jG6G0AQ2mDxcRaaoAoGCCqGSM49 -AwEHoUQDQgAENlON9ojzKxcMlsAIFcsc+JoMSOd1bREjEHAPaj77L0NjO6p605jT -2TTLbj1lpDGD9XRcvw5iiHvhF41Sl454wg== ------END EC PRIVATE KEY----- diff --git a/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient.crt b/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient.crt deleted file mode 100644 index 92a581495..000000000 --- a/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient.crt +++ /dev/null @@ -1,29 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIE7jCCAtYCCQChJZEdSdrQkzANBgkqhkiG9w0BAQsFADAVMRMwEQYDVQQDDApH -byBTd2FnZ2VyMB4XDTE2MTIyMTA4MzM0N1oXDTE3MTIyMTA4MzM0N1owXTELMAkG -A1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExETAPBgNVBAcMCE1pbGxicmFl -MRIwEAYDVQQKDAlMb2NhbCBEZXYxEjAQBgNVBAMMCWxvY2FsaG9zdDCCAiIwDQYJ -KoZIhvcNAQEBBQADggIPADCCAgoCggIBALGjhpJfej7btWCO4OCRJBliUAUyPMO8 -B649Qjn1Yiw9E1L5viByYJSihsfUQ7u2gHip7QdigKCA/s4+w8V2L0Dv8lCowCLk -exf10b7XGQaOqhk2mlr/jOapAg0pKDoUlVErBBZK2s6UbD/gLXAbxudwxCFKJ1Y7 -d/Dw5aTl1vlWZpHzf2o9/ZCeHXf8Xu3aMIEPJ79wG0vzNZK7bL1r1lQVzACdHAr3 -4HAQAvgWB4ZjKqN8z0vGC0N0MpaAuHD8fH8wQ5YiWBbDhDPFVzRYU8PcQjeZSMFq -Oulew9KVm+vXtcMvteEoXMXwWlqAGlvnv7sskc/VbrLJJQaoswyKgy1QCKxVO47E -f2iU4kP75iDYx6NpApdnpN3zxHMHyZDxuwmtoKealenxl5cZeHc6uUU1wXk+nmy7 -TrgW509mcopHzHj+Q0zyGUg/dRws3qXPAGZehJPoaYF1F54eiindF1yLMMH5osvy -1bNp2EQezOlY3P4gqW9VHq3CQvytmDbXqS0vPzVAsFu8YazM3Bs0mW2bBXrEsajW -DSjrvbhdZjlL9j2jqwZ2nzyan88M5t5T0vZhcu+wKisATI1yLdV3oWvLmdFz/XA9 -L6UyosTiwC1MWPmkOY4mcHn/Px70f40+wO815pZ6FbjecxRSyMfAm6vDPWtLAMUr -1UoD4vasyvQNAgMBAAEwDQYJKoZIhvcNAQELBQADggIBACI85R1LfDwKpmWFdCeN -M8O6TwSftxh113QzMvobYDMmBI+yVn0ZvpcfP7E+LWRjzNcDxMFbntbbFWt99Rcd -rJek6CVxLJug53mUEFmvktreHsJ1T7cMbk1ZVroAurE7hZOWYM2HwXlKzVyXX0qh -wR26HSuzQcGBfo5/8e6dzMuy0fUVkgDMu4oKt0+mGgS4kXsOyexfRRBkY9GPusVk -gSzu/WbSGNxNvp/ewWNi8waqrN3noM83iae+BXxI0Sq4eLTQ/vnV1ReM4gRR12Vw -anwZqHZ/WzBV27z9gW36t7wRxJS/uTXQ8J08KtBRBPv+19NXSqqjys5Jg0P1f+l9 -k+sWwpVqIF2rAQ3FyMfboaFKPC0jRn7iJMjp9KyvMbSI+25/rP5xvMicoJwRlk9I -GNGasxSfmRpVpV+WG04xMGp3cPrCXHBdAAjI3O68YIPOX3VqZ6MasN1iGuYWOmam -yeKzLUApYdtkR7yJ+X1FOKVfbzX27CLYmzwrHnDLJzu8NVgqLGU+qTSK0zm3sYE3 -w3ex6WX86Oz2QBJ5h/s2TLbsWis7ZkKjMyXqVWlbg4P3reyNrfpAoc0y1R9EjZlf -1c9HZBRBuRMgaPWmdSR4lxw1FhQBTstIfzC8lBYNbt8QRRtJIxVF9mxiL7H+6XH5 -FZXcQCHun6klGtCkypeAaviE ------END CERTIFICATE----- diff --git a/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient.csr b/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient.csr deleted file mode 100644 index f65d21f0f..000000000 --- a/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient.csr +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN CERTIFICATE REQUEST----- -MIIEojCCAooCAQAwXTELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWEx -ETAPBgNVBAcMCE1pbGxicmFlMRIwEAYDVQQKDAlMb2NhbCBEZXYxEjAQBgNVBAMM -CWxvY2FsaG9zdDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALGjhpJf -ej7btWCO4OCRJBliUAUyPMO8B649Qjn1Yiw9E1L5viByYJSihsfUQ7u2gHip7Qdi -gKCA/s4+w8V2L0Dv8lCowCLkexf10b7XGQaOqhk2mlr/jOapAg0pKDoUlVErBBZK -2s6UbD/gLXAbxudwxCFKJ1Y7d/Dw5aTl1vlWZpHzf2o9/ZCeHXf8Xu3aMIEPJ79w -G0vzNZK7bL1r1lQVzACdHAr34HAQAvgWB4ZjKqN8z0vGC0N0MpaAuHD8fH8wQ5Yi -WBbDhDPFVzRYU8PcQjeZSMFqOulew9KVm+vXtcMvteEoXMXwWlqAGlvnv7sskc/V -brLJJQaoswyKgy1QCKxVO47Ef2iU4kP75iDYx6NpApdnpN3zxHMHyZDxuwmtoKea -lenxl5cZeHc6uUU1wXk+nmy7TrgW509mcopHzHj+Q0zyGUg/dRws3qXPAGZehJPo -aYF1F54eiindF1yLMMH5osvy1bNp2EQezOlY3P4gqW9VHq3CQvytmDbXqS0vPzVA -sFu8YazM3Bs0mW2bBXrEsajWDSjrvbhdZjlL9j2jqwZ2nzyan88M5t5T0vZhcu+w -KisATI1yLdV3oWvLmdFz/XA9L6UyosTiwC1MWPmkOY4mcHn/Px70f40+wO815pZ6 -FbjecxRSyMfAm6vDPWtLAMUr1UoD4vasyvQNAgMBAAGgADANBgkqhkiG9w0BAQsF -AAOCAgEAM9VLDurmvoYQyNEpRvFpOLPkgr8rgboo/HN+O/hN9jtmXranLxzTzd+u -OJCujyzS3sbqiZwPeT3APHH4c/mLdrEKZHjfy2sEeXMsVW6dCOcIEYsADSCM6chi -zU86aw4rAkd6YYB+lXFsEmBq78AIpw0vcdpoPoqGRG9ETQsjr4kD3ATGHTnaP551 -61JJed7Kn5FTbieTmzmMa46dn7GjTTmPEcoAnHNCx4CbJAHwWEzvQWF4lVlyb2di -jFD0NQ0WeaFHK/f6UQMqMq+7TpurN8sLWDlyPHA2X/FT+OsUMAX2mLcwZEsYhTjP -dC4ZCuZ/itDgEp3hyPeKiLo+mL/bhhy50nzah/qclI9PS8ufUXEjWoObqiJ5eyIZ -jTZ73qpLupS+Yrami98IYfuOotwGzKkVLwUPtCWQrKsun6YNtotuKKmqEEQX3Fm3 -ZXIYv0BckkXIGd0aKPeMGgMUO26pyxPBSRWB29F07LXzS6eEmfOHvZcT+QLZmys9 -FkH3yePeTilojCnxNINPyKT4Dk0NiZviCdKavUIJ5QtOyDJ1Nc9j5ss+QaAaNtZZ -VTTjupNp+cfCh/kdyGpGP+GgXQQcGgw4OaIbfXqmec7RsqTOppK5gDR4Ne3e5FVm -SpPDyHbv2GJolPG8/HCOsLCJED+wAEfhK/wUg8ZpC+7Ymct2TU8= ------END CERTIFICATE REQUEST----- diff --git a/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient.key b/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient.key deleted file mode 100644 index dbcedf27e..000000000 --- a/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient.key +++ /dev/null @@ -1,51 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIJJwIBAAKCAgEAsaOGkl96Ptu1YI7g4JEkGWJQBTI8w7wHrj1COfViLD0TUvm+ -IHJglKKGx9RDu7aAeKntB2KAoID+zj7DxXYvQO/yUKjAIuR7F/XRvtcZBo6qGTaa -Wv+M5qkCDSkoOhSVUSsEFkrazpRsP+AtcBvG53DEIUonVjt38PDlpOXW+VZmkfN/ -aj39kJ4dd/xe7dowgQ8nv3AbS/M1krtsvWvWVBXMAJ0cCvfgcBAC+BYHhmMqo3zP -S8YLQ3QyloC4cPx8fzBDliJYFsOEM8VXNFhTw9xCN5lIwWo66V7D0pWb69e1wy+1 -4ShcxfBaWoAaW+e/uyyRz9VussklBqizDIqDLVAIrFU7jsR/aJTiQ/vmINjHo2kC -l2ek3fPEcwfJkPG7Ca2gp5qV6fGXlxl4dzq5RTXBeT6ebLtOuBbnT2ZyikfMeP5D -TPIZSD91HCzepc8AZl6Ek+hpgXUXnh6KKd0XXIswwfmiy/LVs2nYRB7M6Vjc/iCp -b1UercJC/K2YNtepLS8/NUCwW7xhrMzcGzSZbZsFesSxqNYNKOu9uF1mOUv2PaOr -BnafPJqfzwzm3lPS9mFy77AqKwBMjXIt1Xeha8uZ0XP9cD0vpTKixOLALUxY+aQ5 -jiZwef8/HvR/jT7A7zXmlnoVuN5zFFLIx8Cbq8M9a0sAxSvVSgPi9qzK9A0CAwEA -AQKCAgAb4VyHsLCRGQ64nvQwitctnL6OcjoTRnm2ISs5yYelBdj4lvX+RbVe3rtk -ta4D0jsLtS/cjts9VcGoQTWc0lXMTVysyC+Pymh/dDd9SmlFHDMaTfWf/qfws+n8 -gs8rfnuJB8VWcl0xOx5aUCcRh2qKfKprxyWxZRgIGucQIHrDG4pxsdP3qs8XWZmq -cVO85RfjyaslYsUGAKAR7ZS9jiVPgTRJjF8QYaM6M2kj4uE/eGUCz94BOI4gAibG -dGF+akJn+/0/nRhSSlF/hqOPNaXAAdvqugYvRSsF4be+X3jfZTXD8sMLGbil4Hlt -5tk8P31aNT6Vbhw3t1Y2W1fuyfaYbPZfprpR/6ZPV3Uf1oWoh1ystIxWnfU7Qdxu -vrkHkrtho6Qt/7d8nNg0mQ8y5glNcVh/iNu9gkyHIpQ2dZpM9tpHArBGweHVDMvZ -vrb/oJ5fRxnKkyouMtWvqO1TY4STPBwCDNSwJa0yxTn3fLvkOdHk1nGEKra7E7Nc -hgsIe4q1ZoEikg7cZe8pvcsHIFfju3Kv/zgDTvHjzHPTdNear7mpk/LihlWdbTiI -UKkgv17JHRsIhfE5G4pZXLRv2qjCGh+uS8yn2k5qPJqGoyIQ2A7BYbaQ/y2gVh6u -hnVdKeETT2uUqIS3xHrV0U9grAeldPJu7bHRwSoJ+HUbp+D8QQKCAQEA4/5K0+Qq -p4rpB+4FpPkMcM4yE1j0ASwHsKGMDPU70/t8yfzZBlpf5WNHTOWa8frnxOyazo8E -sjm2Xw1RlMb21bFF0wjb3uhN2ak++0zIKMf5vWnM0bb2z7yzbcOJVxLzO9DmRUh0 -OXvHvbeKbW9KXHT3YKA2zjaw0mO1zl7sd7r028wYpD6owGtfzooyXwWCnByIQ3nM -JFB7wFJGIg6Kbu2eJULrN1EaT1Ye0FUVmc4x55FLmZvkYziQ88e4UsjYdZ4R5EFi -2XULVI1RA+NPqDXkXmpIx3JnRRvaPc74QatGvDFwY8YeCAjfGFN5LiwFJ6Cz3/jf -WjDLOhqoSiYQ2QKCAQEAx3W7uPE7WNQRsyu2QnsEDdlikgP0FJf3fFZOYurfsxp7 -iqTpNkR9pSWXftP4FBM/KRruoY5TucmPTfGPRS6sQWTfUkVOhrUpOLnuWjf2DJxH -Qqb0wnT76WcAB4L5Gr//91a+w3dwAX5YhdTZLxEKgpm8ky290otCg3+AYOb/P3Ja -V8RR8RQCNV1+y7peBgjj/mbYeVpxjTiZ5cq4cx2OU4rnup/k3HIg1Gw+qr0N9AUN -2WYOL+X0qaKffDa2ekv88H6mVnfRSReFIpteuV0XITwvMc0DbHdj6zEj1TSZMExu -rDVe7eh2BeL1QxbuazRUgwZ+kfy2NUzPkB1SSwi8VQKCAQBs8K4qj0S+Z8avjlFO -Id6K7EvLKN72zGYkRRzZeDiNMwbOsS22NmrJ/eUs3i1qYJxsYS4bcwUocCEvS/rm -XyfEtf8KNppw6YmBbrh0dZzSt7MiibJfptBKNP17fkpau+hTdZ8CDfvTF806XsAb -SGk8wnsNxaBKaqGU9iYCJSNSlpe3is9fc71IrEXMOAaXltdw5sVJkKI12+s121o9 -nbsSBCJj5ZTlCrDKpfj1TSKUKo13+9om3PGFY5sHkTAHBoc/tDcSXRfxllbCoP/M -HsqKMq4bWyfJfWXRBN0EWagQINocxHbShfEFn8+SHRizMj+ITuaEJ7P5sYT6D5DI -VWYJAoIBAEqaxdFiIYGTKN+sbOqm2phXhB/7bJM7WC1glsc29N8n+6ebEUPkEF7y -FZ0xqavQmyJD2ZgCBV0LgBd2T9FfqLx4/3LlS37lSfrWyMlj/xsuZRUQH6KQYR0n -EoK8wXH4+MPJ5WZ1SSa13GSKfYW2SQkaecdPJ54VypYm3ZzhKf3QRuxnGQMkKcNO -KjwHhF2be7PPQg75/lkFH8MstRsRpgengA90+QRfh9oMdtAkEJECRvDW1F2kFIRS -uHacfFp4C67koFDdViGRs5GDLcYFhL5ApaJp/WrXqT7yTWXU26uOGyM8fzpbZbHD -91rVu+3LUAUGK9ds/7Yl+cj8vqgkJ1UCggEAc0a5kmBREz/8rAWKnlCZrhBsxUUM -tiIj32h6dVdFo5SsoyVTxdB394npw1DAsC8xdowrcm/zsYstB3IDMYlrBnCdRxTU -Xu6RD3Jci0Qg1cfLQg5snlRnrNz12wygXcvTvW8cHsda8vO+FL1RgFdehDtYoyZr -swcLLRAOOLTRXy1Xdbv+8vE6s5ryl3uAO+2Zwbmur3tRL+rhXE+Tb308jlt8g2NK -WrRbc3c092aImdGcKmkMGqo6H+xnL9Jj7sR161uO5JJQjxcYbZ5PBmm3J5Z71cSY -LR5snbYdxUy7WKE3yxAoWi+FMsoGf+O77+oHAcpXRaTDv0Enr/7rEku5Yw== ------END RSA PRIVATE KEY----- diff --git a/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient.p12 b/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient.p12 deleted file mode 100644 index 14208f6ba..000000000 Binary files a/vendor/github.com/go-openapi/runtime/fixtures/certs/myclient.p12 and /dev/null differ diff --git a/vendor/github.com/go-openapi/runtime/fixtures/certs/serial b/vendor/github.com/go-openapi/runtime/fixtures/certs/serial deleted file mode 100644 index 3e1d186dd..000000000 --- a/vendor/github.com/go-openapi/runtime/fixtures/certs/serial +++ /dev/null @@ -1 +0,0 @@ -A125911D49DAD094 diff --git a/vendor/github.com/go-openapi/runtime/flagext/byte_size.go b/vendor/github.com/go-openapi/runtime/flagext/byte_size.go deleted file mode 100644 index 0f3eeba1f..000000000 --- a/vendor/github.com/go-openapi/runtime/flagext/byte_size.go +++ /dev/null @@ -1,38 +0,0 @@ -package flagext - -import ( - "github.com/docker/go-units" -) - -// ByteSize used to pass byte sizes to a go-flags CLI -type ByteSize int - -// MarshalFlag implements go-flags Marshaller interface -func (b ByteSize) MarshalFlag() (string, error) { - return units.HumanSize(float64(b)), nil -} - -// UnmarshalFlag implements go-flags Unmarshaller interface -func (b *ByteSize) UnmarshalFlag(value string) error { - sz, err := units.FromHumanSize(value) - if err != nil { - return err - } - *b = ByteSize(int(sz)) - return nil -} - -// String method for a bytesize (pflag value and stringer interface) -func (b ByteSize) String() string { - return units.HumanSize(float64(b)) -} - -// Set the value of this bytesize (pflag value interfaces) -func (b *ByteSize) Set(value string) error { - return b.UnmarshalFlag(value) -} - -// Type returns the type of the pflag value (pflag value interface) -func (b *ByteSize) Type() string { - return "byte-size" -} diff --git a/vendor/github.com/go-openapi/runtime/flagext/byte_size_test.go b/vendor/github.com/go-openapi/runtime/flagext/byte_size_test.go deleted file mode 100644 index 4e569e5f8..000000000 --- a/vendor/github.com/go-openapi/runtime/flagext/byte_size_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package flagext - -import "testing" -import "github.com/stretchr/testify/assert" - -func TestMarshalBytesize(t *testing.T) { - v, err := ByteSize(1024).MarshalFlag() - if assert.NoError(t, err) { - assert.Equal(t, "1.024kB", v) - } -} - -func TestStringBytesize(t *testing.T) { - v := ByteSize(2048).String() - assert.Equal(t, "2.048kB", v) -} - -func TestUnmarshalBytesize(t *testing.T) { - var b ByteSize - err := b.UnmarshalFlag("notASize") - assert.Error(t, err) - - err = b.UnmarshalFlag("1MB") - if assert.NoError(t, err) { - assert.Equal(t, ByteSize(1000000), b) - } -} - -func TestSetBytesize(t *testing.T) { - var b ByteSize - err := b.Set("notASize") - assert.Error(t, err) - - err = b.Set("2MB") - if assert.NoError(t, err) { - assert.Equal(t, ByteSize(2000000), b) - } -} - -func TestTypeBytesize(t *testing.T) { - var b ByteSize - assert.Equal(t, "byte-size", b.Type()) -} diff --git a/vendor/github.com/go-openapi/runtime/hack/coverage b/vendor/github.com/go-openapi/runtime/hack/coverage deleted file mode 100755 index b8e6dbd0c..000000000 --- a/vendor/github.com/go-openapi/runtime/hack/coverage +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash -set -e -o pipefail - -# Run test coverage on each subdirectories and merge the coverage profile. -echo "mode: ${GOCOVMODE-atomic}" > coverage.txt - -# Standard go tooling behavior is to ignore dirs with leading underscores -# skip generator for race detection and coverage -for dir in $(go list ./...) -do - pth="$GOPATH/src/$dir" - go test -race -timeout 20m -covermode=${GOCOVMODE-atomic} -coverprofile=${pth}/profile.out $dir - if [ -f $pth/profile.out ] - then - cat $pth/profile.out | tail -n +2 >> coverage.txt - rm $pth/profile.out - fi -done - -go tool cover -func coverage.txt diff --git a/vendor/github.com/go-openapi/runtime/hack/gen-self-signed-certs.sh b/vendor/github.com/go-openapi/runtime/hack/gen-self-signed-certs.sh deleted file mode 100755 index 10b020e76..000000000 --- a/vendor/github.com/go-openapi/runtime/hack/gen-self-signed-certs.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh - -# generate CA -openssl genrsa -out myCA.key 4096 -openssl req -x509 -new -key myCA.key -out myCA.crt -days 730 -subj /CN="Go Swagger" - -# generate server cert and key -openssl genrsa -out mycert1.key 4096 -openssl req -new -out mycert1.req -key mycert1.key -subj /CN="goswagger.local" -openssl x509 -req -in mycert1.req -out mycert1.crt -CAkey myCA.key -CA myCA.crt -days 365 -CAcreateserial -CAserial serial - -# generate client cert, key and bundle -openssl genrsa -out myclient.key 4096 -openssl req -new -key myclient.key -out myclient.csr -openssl x509 -req -days 730 -in myclient.csr -out myclient.crt -CAkey myCA.key -CA myCA.crt -days 365 -CAcreateserial -CAserial serial -openssl pkcs12 -export -clcerts -in myclient.crt -inkey myclient.key -out myclient.p12 diff --git a/vendor/github.com/go-openapi/runtime/headers.go b/vendor/github.com/go-openapi/runtime/headers.go deleted file mode 100644 index 4d111db4f..000000000 --- a/vendor/github.com/go-openapi/runtime/headers.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "mime" - "net/http" - - "github.com/go-openapi/errors" -) - -// ContentType parses a content type header -func ContentType(headers http.Header) (string, string, error) { - ct := headers.Get(HeaderContentType) - orig := ct - if ct == "" { - ct = DefaultMime - } - if ct == "" { - return "", "", nil - } - - mt, opts, err := mime.ParseMediaType(ct) - if err != nil { - return "", "", errors.NewParseError(HeaderContentType, "header", orig, err) - } - - if cs, ok := opts[charsetKey]; ok { - return mt, cs, nil - } - - return mt, "", nil -} diff --git a/vendor/github.com/go-openapi/runtime/headers_test.go b/vendor/github.com/go-openapi/runtime/headers_test.go deleted file mode 100644 index c9e334389..000000000 --- a/vendor/github.com/go-openapi/runtime/headers_test.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "mime" - "net/http" - "testing" - - "github.com/go-openapi/errors" - "github.com/stretchr/testify/assert" -) - -func TestParseContentType(t *testing.T) { - _, _, reason1 := mime.ParseMediaType("application(") - _, _, reason2 := mime.ParseMediaType("application/json;char*") - data := []struct { - hdr, mt, cs string - err *errors.ParseError - }{ - {"application/json", "application/json", "", nil}, - {"text/html; charset=utf-8", "text/html", "utf-8", nil}, - {"text/html;charset=utf-8", "text/html", "utf-8", nil}, - {"", "application/octet-stream", "", nil}, - {"text/html; charset=utf-8", "text/html", "utf-8", nil}, - {"application(", "", "", errors.NewParseError("Content-Type", "header", "application(", reason1)}, - {"application/json;char*", "", "", errors.NewParseError("Content-Type", "header", "application/json;char*", reason2)}, - } - - headers := http.Header(map[string][]string{}) - for _, v := range data { - if v.hdr != "" { - headers.Set("Content-Type", v.hdr) - } else { - headers.Del("Content-Type") - } - ct, cs, err := ContentType(headers) - if v.err == nil { - assert.NoError(t, err, "input: %q, err: %v", v.hdr, err) - } else { - assert.Error(t, err, "input: %q", v.hdr) - assert.IsType(t, &errors.ParseError{}, err, "input: %q", v.hdr) - assert.Equal(t, v.err.Error(), err.Error(), "input: %q", v.hdr) - } - assert.Equal(t, v.mt, ct, "input: %q", v.hdr) - assert.Equal(t, v.cs, cs, "input: %q", v.hdr) - } - -} diff --git a/vendor/github.com/go-openapi/runtime/interfaces.go b/vendor/github.com/go-openapi/runtime/interfaces.go deleted file mode 100644 index 5f2a472a8..000000000 --- a/vendor/github.com/go-openapi/runtime/interfaces.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "io" - "net/http" - - "github.com/go-openapi/strfmt" -) - -// OperationHandlerFunc an adapter for a function to the OperationHandler interface -type OperationHandlerFunc func(interface{}) (interface{}, error) - -// Handle implements the operation handler interface -func (s OperationHandlerFunc) Handle(data interface{}) (interface{}, error) { - return s(data) -} - -// OperationHandler a handler for a swagger operation -type OperationHandler interface { - Handle(interface{}) (interface{}, error) -} - -// ConsumerFunc represents a function that can be used as a consumer -type ConsumerFunc func(io.Reader, interface{}) error - -// Consume consumes the reader into the data parameter -func (fn ConsumerFunc) Consume(reader io.Reader, data interface{}) error { - return fn(reader, data) -} - -// Consumer implementations know how to bind the values on the provided interface to -// data provided by the request body -type Consumer interface { - // Consume performs the binding of request values - Consume(io.Reader, interface{}) error -} - -// ProducerFunc represents a function that can be used as a producer -type ProducerFunc func(io.Writer, interface{}) error - -// Produce produces the response for the provided data -func (f ProducerFunc) Produce(writer io.Writer, data interface{}) error { - return f(writer, data) -} - -// Producer implementations know how to turn the provided interface into a valid -// HTTP response -type Producer interface { - // Produce writes to the http response - Produce(io.Writer, interface{}) error -} - -// AuthenticatorFunc turns a function into an authenticator -type AuthenticatorFunc func(interface{}) (bool, interface{}, error) - -// Authenticate authenticates the request with the provided data -func (f AuthenticatorFunc) Authenticate(params interface{}) (bool, interface{}, error) { - return f(params) -} - -// Authenticator represents an authentication strategy -// implementations of Authenticator know how to authenticate the -// request data and translate that into a valid principal object or an error -type Authenticator interface { - Authenticate(interface{}) (bool, interface{}, error) -} - -// AuthorizerFunc turns a function into an authorizer -type AuthorizerFunc func(*http.Request, interface{}) error - -// Authorize authorizes the processing of the request for the principal -func (f AuthorizerFunc) Authorize(r *http.Request, principal interface{}) error { - return f(r, principal) -} - -// Authorizer represents an authorization strategy -// implementations of Authorizer know how to authorize the principal object -// using the request data and returns error if unauthorized -type Authorizer interface { - Authorize(*http.Request, interface{}) error -} - -// Validatable types implementing this interface allow customizing their validation -// this will be used instead of the reflective valditation based on the spec document. -// the implementations are assumed to have been generated by the swagger tool so they should -// contain all the validations obtained from the spec -type Validatable interface { - Validate(strfmt.Registry) error -} diff --git a/vendor/github.com/go-openapi/runtime/internal/testing/data.go b/vendor/github.com/go-openapi/runtime/internal/testing/data.go deleted file mode 100644 index ff7a7a496..000000000 --- a/vendor/github.com/go-openapi/runtime/internal/testing/data.go +++ /dev/null @@ -1,805 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package testing - -import ( - "encoding/json" -) - -// PetStore20YAML yaml doc for swagger 2.0 pet store -const PetStore20YAML = `swagger: '2.0' -info: - version: '1.0.0' - title: Swagger Petstore - description: A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification - termsOfService: http://helloreverb.com/terms/ - contact: - name: Swagger API team - email: foo@example.com - url: http://swagger.io - license: - name: MIT - url: http://opensource.org/licenses/MIT -host: petstore.swagger.wordnik.com -basePath: /api -schemes: - - http -consumes: - - application/json -produces: - - application/json -paths: - /pets: - get: - description: Returns all pets from the system that the user has access to - operationId: findPets - produces: - - application/json - - application/xml - - text/xml - - text/html - parameters: - - name: tags - in: query - description: tags to filter by - required: false - type: array - items: - type: string - collectionFormat: csv - - name: limit - in: query - description: maximum number of results to return - required: false - type: integer - format: int32 - responses: - '200': - description: pet response - schema: - type: array - items: - $ref: '#/definitions/pet' - default: - description: unexpected error - schema: - $ref: '#/definitions/errorModel' - post: - description: Creates a new pet in the store. Duplicates are allowed - operationId: addPet - produces: - - application/json - parameters: - - name: pet - in: body - description: Pet to add to the store - required: true - schema: - $ref: '#/definitions/newPet' - responses: - '200': - description: pet response - schema: - $ref: '#/definitions/pet' - default: - description: unexpected error - schema: - $ref: '#/definitions/errorModel' - /pets/{id}: - get: - description: Returns a user based on a single ID, if the user does not have access to the pet - operationId: findPetById - produces: - - application/json - - application/xml - - text/xml - - text/html - parameters: - - name: id - in: path - description: ID of pet to fetch - required: true - type: integer - format: int64 - responses: - '200': - description: pet response - schema: - $ref: '#/definitions/pet' - default: - description: unexpected error - schema: - $ref: '#/definitions/errorModel' - delete: - description: deletes a single pet based on the ID supplied - operationId: deletePet - parameters: - - name: id - in: path - description: ID of pet to delete - required: true - type: integer - format: int64 - responses: - '204': - description: pet deleted - default: - description: unexpected error - schema: - $ref: '#/definitions/errorModel' -definitions: - pet: - required: - - id - - name - properties: - id: - type: integer - format: int64 - name: - type: string - tag: - type: string - newPet: - allOf: - - $ref: '#/definitions/pet' - - required: - - name - properties: - id: - type: integer - format: int64 - name: - type: string - errorModel: - required: - - code - - message - properties: - code: - type: integer - format: int32 - message: - type: string -` - -// PetStore20 json doc for swagger 2.0 pet store -const PetStore20 = `{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "Swagger Petstore", - "contact": { - "name": "Wordnik API Team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "petstore.swagger.wordnik.com", - "basePath": "/api", - "schemes": [ - "http" - ], - "paths": { - "/pets": { - "get": { - "security": [ - { - "basic": [] - } - ], - "tags": [ "Pet Operations" ], - "operationId": "getAllPets", - "parameters": [ - { - "name": "status", - "in": "query", - "description": "The status to filter by", - "type": "string" - }, - { - "name": "limit", - "in": "query", - "description": "The maximum number of results to return", - "type": "integer", - "format": "int64" - } - ], - "summary": "Finds all pets in the system", - "responses": { - "200": { - "description": "Pet response", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/Pet" - } - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "post": { - "security": [ - { - "basic": [] - } - ], - "tags": [ "Pet Operations" ], - "operationId": "createPet", - "summary": "Creates a new pet", - "consumes": ["application/x-yaml"], - "produces": ["application/x-yaml"], - "parameters": [ - { - "name": "pet", - "in": "body", - "description": "The Pet to create", - "required": true, - "schema": { - "$ref": "#/definitions/newPet" - } - } - ], - "responses": { - "200": { - "description": "Created Pet response", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - } - }, - "/pets/{id}": { - "delete": { - "security": [ - { - "apiKey": [] - } - ], - "description": "Deletes the Pet by id", - "operationId": "deletePet", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to delete", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "204": { - "description": "pet deleted" - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "get": { - "tags": [ "Pet Operations" ], - "operationId": "getPetById", - "summary": "Finds the pet by id", - "responses": { - "200": { - "description": "Pet response", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet", - "required": true, - "type": "integer", - "format": "int64" - } - ] - } - }, - "definitions": { - "Category": { - "properties": { - "id": { - "format": "int64", - "type": "integer" - }, - "name": { - "type": "string" - } - } - }, - "Pet": { - "properties": { - "category": { - "$ref": "#/definitions/Category" - }, - "id": { - "description": "unique identifier for the pet", - "format": "int64", - "maximum": 100.0, - "minimum": 0.0, - "type": "integer" - }, - "name": { - "type": "string" - }, - "photoUrls": { - "items": { - "type": "string" - }, - "type": "array" - }, - "status": { - "description": "pet status in the store", - "enum": [ - "available", - "pending", - "sold" - ], - "type": "string" - }, - "tags": { - "items": { - "$ref": "#/definitions/Tag" - }, - "type": "array" - } - }, - "required": [ - "id", - "name" - ] - }, - "newPet": { - "anyOf": [ - { - "$ref": "#/definitions/Pet" - }, - { - "required": [ - "name" - ] - } - ] - }, - "Tag": { - "properties": { - "id": { - "format": "int64", - "type": "integer" - }, - "name": { - "type": "string" - } - } - }, - "Error": { - "required": [ - "code", - "message" - ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - }, - "consumes": [ - "application/json", - "application/xml" - ], - "produces": [ - "application/json", - "application/xml", - "text/plain", - "text/html" - ], - "securityDefinitions": { - "basic": { - "type": "basic" - }, - "apiKey": { - "type": "apiKey", - "in": "header", - "name": "X-API-KEY" - } - } -} -` - -// RootPetStore20 json doc for swagger 2.0 pet store at / -const RootPetStore20 = `{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "Swagger Petstore", - "contact": { - "name": "Wordnik API Team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "petstore.swagger.wordnik.com", - "basePath": "/", - "schemes": [ - "http" - ], - "paths": { - "/pets": { - "get": { - "security": [ - { - "basic": [] - } - ], - "tags": [ "Pet Operations" ], - "operationId": "getAllPets", - "parameters": [ - { - "name": "status", - "in": "query", - "description": "The status to filter by", - "type": "string" - } - ], - "summary": "Finds all pets in the system", - "responses": { - "200": { - "description": "Pet response", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/Pet" - } - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "post": { - "security": [ - { - "basic": [] - } - ], - "tags": [ "Pet Operations" ], - "operationId": "createPet", - "summary": "Creates a new pet", - "consumes": ["application/x-yaml"], - "produces": ["application/x-yaml"], - "parameters": [ - { - "name": "pet", - "in": "body", - "description": "The Pet to create", - "required": true, - "schema": { - "$ref": "#/definitions/newPet" - } - } - ], - "responses": { - "200": { - "description": "Created Pet response", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - } - }, - "/pets/{id}": { - "delete": { - "security": [ - { - "apiKey": [] - } - ], - "description": "Deletes the Pet by id", - "operationId": "deletePet", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to delete", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "204": { - "description": "pet deleted" - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "get": { - "tags": [ "Pet Operations" ], - "operationId": "getPetById", - "summary": "Finds the pet by id", - "responses": { - "200": { - "description": "Pet response", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet", - "required": true, - "type": "integer", - "format": "int64" - } - ] - } - }, - "definitions": { - "Category": { - "properties": { - "id": { - "format": "int64", - "type": "integer" - }, - "name": { - "type": "string" - } - } - }, - "Pet": { - "properties": { - "category": { - "$ref": "#/definitions/Category" - }, - "id": { - "description": "unique identifier for the pet", - "format": "int64", - "maximum": 100.0, - "minimum": 0.0, - "type": "integer" - }, - "name": { - "type": "string" - }, - "photoUrls": { - "items": { - "type": "string" - }, - "type": "array" - }, - "status": { - "description": "pet status in the store", - "enum": [ - "available", - "pending", - "sold" - ], - "type": "string" - }, - "tags": { - "items": { - "$ref": "#/definitions/Tag" - }, - "type": "array" - } - }, - "required": [ - "id", - "name" - ] - }, - "newPet": { - "anyOf": [ - { - "$ref": "#/definitions/Pet" - }, - { - "required": [ - "name" - ] - } - ] - }, - "Tag": { - "properties": { - "id": { - "format": "int64", - "type": "integer" - }, - "name": { - "type": "string" - } - } - }, - "Error": { - "required": [ - "code", - "message" - ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - }, - "consumes": [ - "application/json", - "application/xml" - ], - "produces": [ - "application/json", - "application/xml", - "text/plain", - "text/html" - ], - "securityDefinitions": { - "basic": { - "type": "basic" - }, - "apiKey": { - "type": "apiKey", - "in": "header", - "name": "X-API-KEY" - } - } -} -` - -// PetStoreJSONMessage json raw message for Petstore20 -var PetStoreJSONMessage = json.RawMessage([]byte(PetStore20)) - -// RootPetStoreJSONMessage json raw message for Petstore20 -var RootPetStoreJSONMessage = json.RawMessage([]byte(RootPetStore20)) - -// InvalidJSON invalid swagger 2.0 spec in JSON -const InvalidJSON = `{ - "apiVersion": "1.0.0", - "apis": [ - { - "description": "Operations about pets", - "path": "/pet" - }, - { - "description": "Operations about user", - "path": "/user" - }, - { - "description": "Operations about store", - "path": "/store" - } - ], - "authorizations": { - "oauth2": { - "grantTypes": { - "authorization_code": { - "tokenEndpoint": { - "tokenName": "auth_code", - "url": "http://petstore.swagger.wordnik.com/oauth/token" - }, - "tokenRequestEndpoint": { - "clientIdName": "client_id", - "clientSecretName": "client_secret", - "url": "http://petstore.swagger.wordnik.com/oauth/requestToken" - } - }, - "implicit": { - "loginEndpoint": { - "url": "http://petstore.swagger.wordnik.com/oauth/dialog" - }, - "tokenName": "access_token" - } - }, - "scopes": [ - { - "description": "Modify pets in your account", - "scope": "write:pets" - }, - { - "description": "Read your pets", - "scope": "read:pets" - }, - { - "description": "Anything (testing)", - "scope": "test:anything" - } - ], - "type": "oauth2" - } - }, - "info": { - "contact": "apiteam@wordnik.com", - "description": "This is a sample server Petstore server. You can find out more about Swagger \n at http://swagger.wordnik.com or on irc.freenode.net, #swagger. For this sample,\n you can use the api key \"special-key\" to test the authorization filters", - "license": "Apache 2.0", - "licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0.html", - "termsOfServiceUrl": "http://helloreverb.com/terms/", - "title": "Swagger Sample App" - }, - "swaggerVersion": "1.2" -} -` - -// InvalidJSONMessage json raw message for invalid json -var InvalidJSONMessage = json.RawMessage([]byte(InvalidJSON)) diff --git a/vendor/github.com/go-openapi/runtime/internal/testing/petstore/api.go b/vendor/github.com/go-openapi/runtime/internal/testing/petstore/api.go deleted file mode 100644 index 2a066cee1..000000000 --- a/vendor/github.com/go-openapi/runtime/internal/testing/petstore/api.go +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package petstore - -import ( - goerrors "errors" - "io" - "net/http" - "strings" - gotest "testing" - - "github.com/go-openapi/errors" - "github.com/go-openapi/loads" - "github.com/go-openapi/runtime" - testingutil "github.com/go-openapi/runtime/internal/testing" - "github.com/go-openapi/runtime/middleware/untyped" - "github.com/go-openapi/runtime/security" - "github.com/go-openapi/runtime/yamlpc" - "github.com/stretchr/testify/assert" -) - -// NewAPI registers a stub api for the pet store -func NewAPI(t gotest.TB) (*loads.Document, *untyped.API) { - spec, err := loads.Analyzed(testingutil.PetStoreJSONMessage, "") - assert.NoError(t, err) - api := untyped.NewAPI(spec) - - api.RegisterConsumer("application/json", runtime.JSONConsumer()) - api.RegisterProducer("application/json", runtime.JSONProducer()) - api.RegisterConsumer("application/xml", new(stubConsumer)) - api.RegisterProducer("application/xml", new(stubProducer)) - api.RegisterProducer("text/plain", new(stubProducer)) - api.RegisterProducer("text/html", new(stubProducer)) - api.RegisterConsumer("application/x-yaml", yamlpc.YAMLConsumer()) - api.RegisterProducer("application/x-yaml", yamlpc.YAMLProducer()) - - api.RegisterAuth("basic", security.BasicAuth(func(username, password string) (interface{}, error) { - if username == "admin" && password == "admin" { - return "admin", nil - } else if username == "topuser" && password == "topuser" { - return "topuser", nil - } - return nil, errors.Unauthenticated("basic") - })) - api.RegisterAuth("apiKey", security.APIKeyAuth("X-API-KEY", "header", func(token string) (interface{}, error) { - if token == "token123" { - return "admin", nil - } - return nil, errors.Unauthenticated("token") - })) - api.RegisterAuthorizer(runtime.AuthorizerFunc(func(r *http.Request, user interface{}) error { - if r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/api/pets") && user.(string) != "admin" { - return goerrors.New("unauthorized") - } - return nil - })) - api.RegisterOperation("get", "/pets", new(stubOperationHandler)) - api.RegisterOperation("post", "/pets", new(stubOperationHandler)) - api.RegisterOperation("delete", "/pets/{id}", new(stubOperationHandler)) - api.RegisterOperation("get", "/pets/{id}", new(stubOperationHandler)) - - api.Models["pet"] = func() interface{} { return new(Pet) } - api.Models["newPet"] = func() interface{} { return new(Pet) } - api.Models["tag"] = func() interface{} { return new(Tag) } - - return spec, api -} - -// NewRootAPI registers a stub api for the pet store -func NewRootAPI(t gotest.TB) (*loads.Document, *untyped.API) { - spec, err := loads.Analyzed(testingutil.RootPetStoreJSONMessage, "") - assert.NoError(t, err) - api := untyped.NewAPI(spec) - - api.RegisterConsumer("application/json", runtime.JSONConsumer()) - api.RegisterProducer("application/json", runtime.JSONProducer()) - api.RegisterConsumer("application/xml", new(stubConsumer)) - api.RegisterProducer("application/xml", new(stubProducer)) - api.RegisterProducer("text/plain", new(stubProducer)) - api.RegisterProducer("text/html", new(stubProducer)) - api.RegisterConsumer("application/x-yaml", yamlpc.YAMLConsumer()) - api.RegisterProducer("application/x-yaml", yamlpc.YAMLProducer()) - - api.RegisterAuth("basic", security.BasicAuth(func(username, password string) (interface{}, error) { - if username == "admin" && password == "admin" { - return "admin", nil - } - return nil, errors.Unauthenticated("basic") - })) - api.RegisterAuth("apiKey", security.APIKeyAuth("X-API-KEY", "header", func(token string) (interface{}, error) { - if token == "token123" { - return "admin", nil - } - return nil, errors.Unauthenticated("token") - })) - api.RegisterAuthorizer(security.Authorized()) - api.RegisterOperation("get", "/pets", new(stubOperationHandler)) - api.RegisterOperation("post", "/pets", new(stubOperationHandler)) - api.RegisterOperation("delete", "/pets/{id}", new(stubOperationHandler)) - api.RegisterOperation("get", "/pets/{id}", new(stubOperationHandler)) - - api.Models["pet"] = func() interface{} { return new(Pet) } - api.Models["newPet"] = func() interface{} { return new(Pet) } - api.Models["tag"] = func() interface{} { return new(Tag) } - - return spec, api -} - -// Tag the tag model -type Tag struct { - ID int64 - Name string -} - -// Pet the pet model -type Pet struct { - ID int64 - Name string - PhotoURLs []string - Status string - Tags []Tag -} - -type stubConsumer struct { -} - -func (s *stubConsumer) Consume(_ io.Reader, _ interface{}) error { - return nil -} - -type stubProducer struct { -} - -func (s *stubProducer) Produce(_ io.Writer, _ interface{}) error { - return nil -} - -type stubOperationHandler struct { -} - -func (s *stubOperationHandler) ParameterModel() interface{} { - return nil -} - -func (s *stubOperationHandler) Handle(params interface{}) (interface{}, error) { - return nil, nil -} diff --git a/vendor/github.com/go-openapi/runtime/internal/testing/simplepetstore/api.go b/vendor/github.com/go-openapi/runtime/internal/testing/simplepetstore/api.go deleted file mode 100644 index 150542005..000000000 --- a/vendor/github.com/go-openapi/runtime/internal/testing/simplepetstore/api.go +++ /dev/null @@ -1,351 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package simplepetstore - -import ( - "encoding/json" - "net/http" - "sync" - "sync/atomic" - - "github.com/go-openapi/errors" - "github.com/go-openapi/loads" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" - "github.com/go-openapi/runtime/middleware/untyped" -) - -// NewPetstore creates a new petstore api handler -func NewPetstore() (http.Handler, error) { - spec, err := loads.Analyzed(json.RawMessage([]byte(swaggerJSON)), "") - if err != nil { - return nil, err - } - api := untyped.NewAPI(spec) - - api.RegisterOperation("get", "/pets", getAllPets) - api.RegisterOperation("post", "/pets", createPet) - api.RegisterOperation("delete", "/pets/{id}", deletePet) - api.RegisterOperation("get", "/pets/{id}", getPetByID) - - return middleware.Serve(spec, api), nil -} - -var getAllPets = runtime.OperationHandlerFunc(func(data interface{}) (interface{}, error) { - return pets, nil -}) - -var createPet = runtime.OperationHandlerFunc(func(data interface{}) (interface{}, error) { - body := data.(map[string]interface{})["pet"].(map[string]interface{}) - return addPet(Pet{ - Name: body["name"].(string), - Status: body["status"].(string), - }), nil -}) - -var deletePet = runtime.OperationHandlerFunc(func(data interface{}) (interface{}, error) { - id := data.(map[string]interface{})["id"].(int64) - removePet(id) - return nil, nil -}) - -var getPetByID = runtime.OperationHandlerFunc(func(data interface{}) (interface{}, error) { - id := data.(map[string]interface{})["id"].(int64) - return petByID(id) -}) - -// Tag the tag model -type Tag struct { - ID int64 - Name string -} - -// Pet the pet model -type Pet struct { - ID int64 `json:"id"` - Name string `json:"name"` - PhotoURLs []string `json:"photoUrls,omitempty"` - Status string `json:"status,omitempty"` - Tags []Tag `json:"tags,omitempty"` -} - -var pets = []Pet{ - {1, "Dog", []string{}, "available", nil}, - {2, "Cat", []string{}, "pending", nil}, -} - -var petsLock = &sync.Mutex{} -var lastPetID int64 = 2 - -func newPetID() int64 { - return atomic.AddInt64(&lastPetID, 1) -} - -func addPet(pet Pet) Pet { - petsLock.Lock() - defer petsLock.Unlock() - pet.ID = newPetID() - pets = append(pets, pet) - return pet -} - -func removePet(id int64) { - petsLock.Lock() - defer petsLock.Unlock() - var newPets []Pet - for _, pet := range pets { - if pet.ID != id { - newPets = append(newPets, pet) - } - } - pets = newPets -} - -func petByID(id int64) (*Pet, error) { - for _, pet := range pets { - if pet.ID == id { - return &pet, nil - } - } - return nil, errors.NotFound("not found: pet %d", id) -} - -var swaggerJSON = `{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "Swagger Petstore", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "Wordnik API Team" - }, - "license": { - "name": "MIT" - } - }, - "host": "localhost:8344", - "basePath": "/api", - "schemes": [ - "http" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "paths": { - "/pets": { - "get": { - "description": "Returns all pets from the system that the user has access to", - "operationId": "findPets", - "produces": [ - "application/json", - "application/xml", - "text/xml", - "text/html" - ], - "parameters": [ - { - "name": "tags", - "in": "query", - "description": "tags to filter by", - "required": false, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - }, - { - "name": "limit", - "in": "query", - "description": "maximum number of results to return", - "required": false, - "type": "integer", - "format": "int32" - } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/pet" - } - } - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - }, - "post": { - "description": "Creates a new pet in the store. Duplicates are allowed", - "operationId": "addPet", - "produces": [ - "application/json" - ], - "parameters": [ - { - "name": "pet", - "in": "body", - "description": "Pet to add to the store", - "required": true, - "schema": { - "$ref": "#/definitions/petInput" - } - } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "$ref": "#/definitions/pet" - } - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - } - }, - "/pets/{id}": { - "get": { - "description": "Returns a user based on a single ID, if the user does not have access to the pet", - "operationId": "findPetById", - "produces": [ - "application/json", - "application/xml", - "text/xml", - "text/html" - ], - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to fetch", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "$ref": "#/definitions/pet" - } - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - }, - "delete": { - "description": "deletes a single pet based on the ID supplied", - "operationId": "deletePet", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to delete", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "204": { - "description": "pet deleted" - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - } - } - }, - "definitions": { - "pet": { - "required": [ - "name", - "status" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "status": { - "type": "string" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - } - } - } - }, - "petInput": { - "allOf": [ - { - "$ref": "#/definitions/pet" - }, - { - "properties": { - "id": { - "type": "integer", - "format": "int64" - } - } - } - ] - }, - "errorModel": { - "required": [ - "code", - "message" - ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -}` diff --git a/vendor/github.com/go-openapi/runtime/internal/testing/simplepetstore/api_test.go b/vendor/github.com/go-openapi/runtime/internal/testing/simplepetstore/api_test.go deleted file mode 100644 index 6681863d8..000000000 --- a/vendor/github.com/go-openapi/runtime/internal/testing/simplepetstore/api_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package simplepetstore - -import ( - "bytes" - "net/http/httptest" - "testing" - - "github.com/go-openapi/runtime" - "github.com/stretchr/testify/assert" -) - -func TestSimplePetstoreSpec(t *testing.T) { - handler, _ := NewPetstore() - // Serves swagger spec document - r, _ := runtime.JSONRequest("GET", "/swagger.json", nil) - rw := httptest.NewRecorder() - handler.ServeHTTP(rw, r) - assert.Equal(t, 200, rw.Code) - assert.Equal(t, swaggerJSON, rw.Body.String()) -} - -func TestSimplePetstoreAllPets(t *testing.T) { - handler, _ := NewPetstore() - // Serves swagger spec document - r, _ := runtime.JSONRequest("GET", "/api/pets", nil) - rw := httptest.NewRecorder() - handler.ServeHTTP(rw, r) - assert.Equal(t, 200, rw.Code) - assert.Equal(t, "[{\"id\":1,\"name\":\"Dog\",\"status\":\"available\"},{\"id\":2,\"name\":\"Cat\",\"status\":\"pending\"}]\n", rw.Body.String()) -} - -func TestSimplePetstorePetByID(t *testing.T) { - handler, _ := NewPetstore() - - // Serves swagger spec document - r, _ := runtime.JSONRequest("GET", "/api/pets/1", nil) - rw := httptest.NewRecorder() - handler.ServeHTTP(rw, r) - assert.Equal(t, 200, rw.Code) - assert.Equal(t, "{\"id\":1,\"name\":\"Dog\",\"status\":\"available\"}\n", rw.Body.String()) -} - -func TestSimplePetstoreAddPet(t *testing.T) { - handler, _ := NewPetstore() - // Serves swagger spec document - r, _ := runtime.JSONRequest("POST", "/api/pets", bytes.NewBuffer([]byte(`{"name": "Fish","status": "available"}`))) - rw := httptest.NewRecorder() - handler.ServeHTTP(rw, r) - assert.Equal(t, 200, rw.Code) - assert.Equal(t, "{\"id\":3,\"name\":\"Fish\",\"status\":\"available\"}\n", rw.Body.String()) -} - -func TestSimplePetstoreDeletePet(t *testing.T) { - handler, _ := NewPetstore() - // Serves swagger spec document - r, _ := runtime.JSONRequest("DELETE", "/api/pets/1", nil) - rw := httptest.NewRecorder() - handler.ServeHTTP(rw, r) - assert.Equal(t, 204, rw.Code) - assert.Equal(t, "", rw.Body.String()) - - r, _ = runtime.JSONRequest("GET", "/api/pets/1", nil) - rw = httptest.NewRecorder() - handler.ServeHTTP(rw, r) - assert.Equal(t, 404, rw.Code) - assert.Equal(t, "{\"code\":404,\"message\":\"not found: pet 1\"}", rw.Body.String()) -} diff --git a/vendor/github.com/go-openapi/runtime/json.go b/vendor/github.com/go-openapi/runtime/json.go deleted file mode 100644 index 81ee360b5..000000000 --- a/vendor/github.com/go-openapi/runtime/json.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "encoding/json" - "io" -) - -// JSONConsumer creates a new JSON consumer -func JSONConsumer() Consumer { - return ConsumerFunc(func(reader io.Reader, data interface{}) error { - dec := json.NewDecoder(reader) - dec.UseNumber() // preserve number formats - return dec.Decode(data) - }) -} - -// JSONProducer creates a new JSON producer -func JSONProducer() Producer { - return ProducerFunc(func(writer io.Writer, data interface{}) error { - enc := json.NewEncoder(writer) - return enc.Encode(data) - }) -} diff --git a/vendor/github.com/go-openapi/runtime/json_test.go b/vendor/github.com/go-openapi/runtime/json_test.go deleted file mode 100644 index 5e11d03ca..000000000 --- a/vendor/github.com/go-openapi/runtime/json_test.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "bytes" - "io" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" -) - -var consProdJSON = `{"name":"Somebody","id":1}` - -type eofRdr struct { -} - -func (r *eofRdr) Read(d []byte) (int, error) { - return 0, io.EOF -} - -func TestJSONConsumer(t *testing.T) { - cons := JSONConsumer() - var data struct { - Name string - ID int - } - err := cons.Consume(bytes.NewBuffer([]byte(consProdJSON)), &data) - if assert.NoError(t, err) { - assert.Equal(t, "Somebody", data.Name) - assert.Equal(t, 1, data.ID) - - err = cons.Consume(new(eofRdr), &data) - assert.Error(t, err) - } -} - -func TestJSONProducer(t *testing.T) { - prod := JSONProducer() - data := struct { - Name string `json:"name"` - ID int `json:"id"` - }{Name: "Somebody", ID: 1} - - rw := httptest.NewRecorder() - err := prod.Produce(rw, data) - assert.NoError(t, err) - assert.Equal(t, consProdJSON+"\n", rw.Body.String()) -} diff --git a/vendor/github.com/go-openapi/runtime/logger/logger.go b/vendor/github.com/go-openapi/runtime/logger/logger.go deleted file mode 100644 index d62c1f708..000000000 --- a/vendor/github.com/go-openapi/runtime/logger/logger.go +++ /dev/null @@ -1,12 +0,0 @@ -package logger - -import "os" - -type Logger interface { - Printf(format string, args ...interface{}) - Debugf(format string, args ...interface{}) -} - -func DebugEnabled() bool { - return os.Getenv("SWAGGER_DEBUG") != "" || os.Getenv("DEBUG") != "" -} diff --git a/vendor/github.com/go-openapi/runtime/logger/standard.go b/vendor/github.com/go-openapi/runtime/logger/standard.go deleted file mode 100644 index f7e67ebb9..000000000 --- a/vendor/github.com/go-openapi/runtime/logger/standard.go +++ /dev/null @@ -1,22 +0,0 @@ -package logger - -import ( - "fmt" - "os" -) - -type StandardLogger struct{} - -func (StandardLogger) Printf(format string, args ...interface{}) { - if len(format) == 0 || format[len(format)-1] != '\n' { - format += "\n" - } - fmt.Fprintf(os.Stderr, format, args...) -} - -func (StandardLogger) Debugf(format string, args ...interface{}) { - if len(format) == 0 || format[len(format)-1] != '\n' { - format += "\n" - } - fmt.Fprintf(os.Stderr, format, args...) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/body_test.go b/vendor/github.com/go-openapi/runtime/middleware/body_test.go deleted file mode 100644 index 7e8ad0f93..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/body_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package middleware - -import ( - "io" - "net/http" - "path" - "testing" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/internal/testing/petstore" - "github.com/stretchr/testify/assert" -) - -type eofReader struct { -} - -func (r *eofReader) Read(b []byte) (int, error) { - return 0, io.EOF -} - -func (r *eofReader) Close() error { - return nil -} - -type rbn func(*http.Request, *MatchedRoute) error - -func (b rbn) BindRequest(r *http.Request, rr *MatchedRoute) error { - return b(r, rr) -} - -func TestBindRequest_BodyValidation(t *testing.T) { - spec, api := petstore.NewAPI(t) - ctx := NewContext(spec, api, nil) - api.DefaultConsumes = runtime.JSONMime - ctx.router = DefaultRouter(spec, ctx.api) - - req, err := http.NewRequest("GET", path.Join(spec.BasePath(), "/pets"), new(eofReader)) - if assert.NoError(t, err) { - req.Header.Set("Content-Type", runtime.JSONMime) - - ri, rCtx, ok := ctx.RouteInfo(req) - if assert.True(t, ok) { - req = rCtx - err := ctx.BindValidRequest(req, ri, rbn(func(r *http.Request, rr *MatchedRoute) error { - defer r.Body.Close() - var data interface{} - err := runtime.JSONConsumer().Consume(r.Body, &data) - _ = data - return err - })) - - assert.Error(t, err) - assert.Equal(t, io.EOF, err) - } - } -} - -func TestBindRequest_DeleteNoBody(t *testing.T) { - spec, api := petstore.NewAPI(t) - ctx := NewContext(spec, api, nil) - api.DefaultConsumes = runtime.JSONMime - ctx.router = DefaultRouter(spec, ctx.api) - - req, err := http.NewRequest("DELETE", path.Join(spec.BasePath(), "/pets/123"), new(eofReader)) - if assert.NoError(t, err) { - req.Header.Set("Accept", "*/*") - - ri, rCtx, ok := ctx.RouteInfo(req) - if assert.True(t, ok) { - req = rCtx - bverr := ctx.BindValidRequest(req, ri, rbn(func(r *http.Request, rr *MatchedRoute) error { - return nil - })) - - assert.NoError(t, bverr) - //assert.Equal(t, io.EOF, bverr) - } - } - - req, err = http.NewRequest("DELETE", path.Join(spec.BasePath(), "/pets/123"), new(eofReader)) - if assert.NoError(t, err) { - req.Header.Set("Accept", "*/*") - req.Header.Set("Content-Type", runtime.JSONMime) - req.ContentLength = 1 - - ri, rCtx, ok := ctx.RouteInfo(req) - if assert.True(t, ok) { - req = rCtx - err := ctx.BindValidRequest(req, ri, rbn(func(r *http.Request, rr *MatchedRoute) error { - defer r.Body.Close() - var data interface{} - err := runtime.JSONConsumer().Consume(r.Body, &data) - _ = data - return err - })) - - assert.Error(t, err) - assert.Equal(t, io.EOF, err) - } - } -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/context.go b/vendor/github.com/go-openapi/runtime/middleware/context.go deleted file mode 100644 index ad6c91d3d..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/context.go +++ /dev/null @@ -1,559 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - stdContext "context" - "net/http" - "strings" - "sync" - - "github.com/go-openapi/analysis" - "github.com/go-openapi/errors" - "github.com/go-openapi/loads" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/logger" - "github.com/go-openapi/runtime/middleware/untyped" - "github.com/go-openapi/runtime/security" - "github.com/go-openapi/spec" - "github.com/go-openapi/strfmt" -) - -// Debug when true turns on verbose logging -var Debug = logger.DebugEnabled() -var Logger logger.Logger = logger.StandardLogger{} - -func debugLog(format string, args ...interface{}) { - if Debug { - Logger.Printf(format, args...) - } -} - -// A Builder can create middlewares -type Builder func(http.Handler) http.Handler - -// PassthroughBuilder returns the handler, aka the builder identity function -func PassthroughBuilder(handler http.Handler) http.Handler { return handler } - -// RequestBinder is an interface for types to implement -// when they want to be able to bind from a request -type RequestBinder interface { - BindRequest(*http.Request, *MatchedRoute) error -} - -// Responder is an interface for types to implement -// when they want to be considered for writing HTTP responses -type Responder interface { - WriteResponse(http.ResponseWriter, runtime.Producer) -} - -// ResponderFunc wraps a func as a Responder interface -type ResponderFunc func(http.ResponseWriter, runtime.Producer) - -// WriteResponse writes to the response -func (fn ResponderFunc) WriteResponse(rw http.ResponseWriter, pr runtime.Producer) { - fn(rw, pr) -} - -// Context is a type safe wrapper around an untyped request context -// used throughout to store request context with the standard context attached -// to the http.Request -type Context struct { - spec *loads.Document - analyzer *analysis.Spec - api RoutableAPI - router Router -} - -type routableUntypedAPI struct { - api *untyped.API - hlock *sync.Mutex - handlers map[string]map[string]http.Handler - defaultConsumes string - defaultProduces string -} - -func newRoutableUntypedAPI(spec *loads.Document, api *untyped.API, context *Context) *routableUntypedAPI { - var handlers map[string]map[string]http.Handler - if spec == nil || api == nil { - return nil - } - analyzer := analysis.New(spec.Spec()) - for method, hls := range analyzer.Operations() { - um := strings.ToUpper(method) - for path, op := range hls { - schemes := analyzer.SecurityDefinitionsFor(op) - - if oh, ok := api.OperationHandlerFor(method, path); ok { - if handlers == nil { - handlers = make(map[string]map[string]http.Handler) - } - if b, ok := handlers[um]; !ok || b == nil { - handlers[um] = make(map[string]http.Handler) - } - - var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // lookup route info in the context - route, rCtx, _ := context.RouteInfo(r) - if rCtx != nil { - r = rCtx - } - - // bind and validate the request using reflection - var bound interface{} - var validation error - bound, r, validation = context.BindAndValidate(r, route) - if validation != nil { - context.Respond(w, r, route.Produces, route, validation) - return - } - - // actually handle the request - result, err := oh.Handle(bound) - if err != nil { - // respond with failure - context.Respond(w, r, route.Produces, route, err) - return - } - - // respond with success - context.Respond(w, r, route.Produces, route, result) - }) - - if len(schemes) > 0 { - handler = newSecureAPI(context, handler) - } - handlers[um][path] = handler - } - } - } - - return &routableUntypedAPI{ - api: api, - hlock: new(sync.Mutex), - handlers: handlers, - defaultProduces: api.DefaultProduces, - defaultConsumes: api.DefaultConsumes, - } -} - -func (r *routableUntypedAPI) HandlerFor(method, path string) (http.Handler, bool) { - r.hlock.Lock() - paths, ok := r.handlers[strings.ToUpper(method)] - if !ok { - r.hlock.Unlock() - return nil, false - } - handler, ok := paths[path] - r.hlock.Unlock() - return handler, ok -} -func (r *routableUntypedAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) { - return r.api.ServeError -} -func (r *routableUntypedAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { - return r.api.ConsumersFor(mediaTypes) -} -func (r *routableUntypedAPI) ProducersFor(mediaTypes []string) map[string]runtime.Producer { - return r.api.ProducersFor(mediaTypes) -} -func (r *routableUntypedAPI) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { - return r.api.AuthenticatorsFor(schemes) -} -func (r *routableUntypedAPI) Authorizer() runtime.Authorizer { - return r.api.Authorizer() -} -func (r *routableUntypedAPI) Formats() strfmt.Registry { - return r.api.Formats() -} - -func (r *routableUntypedAPI) DefaultProduces() string { - return r.defaultProduces -} - -func (r *routableUntypedAPI) DefaultConsumes() string { - return r.defaultConsumes -} - -// NewRoutableContext creates a new context for a routable API -func NewRoutableContext(spec *loads.Document, routableAPI RoutableAPI, routes Router) *Context { - var an *analysis.Spec - if spec != nil { - an = analysis.New(spec.Spec()) - } - ctx := &Context{spec: spec, api: routableAPI, analyzer: an} - return ctx -} - -// NewContext creates a new context wrapper -func NewContext(spec *loads.Document, api *untyped.API, routes Router) *Context { - var an *analysis.Spec - if spec != nil { - an = analysis.New(spec.Spec()) - } - ctx := &Context{spec: spec, analyzer: an} - ctx.api = newRoutableUntypedAPI(spec, api, ctx) - return ctx -} - -// Serve serves the specified spec with the specified api registrations as a http.Handler -func Serve(spec *loads.Document, api *untyped.API) http.Handler { - return ServeWithBuilder(spec, api, PassthroughBuilder) -} - -// ServeWithBuilder serves the specified spec with the specified api registrations as a http.Handler that is decorated -// by the Builder -func ServeWithBuilder(spec *loads.Document, api *untyped.API, builder Builder) http.Handler { - context := NewContext(spec, api, nil) - return context.APIHandler(builder) -} - -type contextKey int8 - -const ( - _ contextKey = iota - ctxContentType - ctxResponseFormat - ctxMatchedRoute - ctxBoundParams - ctxSecurityPrincipal - ctxSecurityScopes -) - -type contentTypeValue struct { - MediaType string - Charset string -} - -// BasePath returns the base path for this API -func (c *Context) BasePath() string { - return c.spec.BasePath() -} - -// RequiredProduces returns the accepted content types for responses -func (c *Context) RequiredProduces() []string { - return c.analyzer.RequiredProduces() -} - -// BindValidRequest binds a params object to a request but only when the request is valid -// if the request is not valid an error will be returned -func (c *Context) BindValidRequest(request *http.Request, route *MatchedRoute, binder RequestBinder) error { - var res []error - - requestContentType := "*/*" - // check and validate content type, select consumer - if runtime.HasBody(request) { - ct, _, err := runtime.ContentType(request.Header) - if err != nil { - res = append(res, err) - } else { - if err := validateContentType(route.Consumes, ct); err != nil { - res = append(res, err) - } - if len(res) == 0 { - cons, ok := route.Consumers[ct] - if !ok { - res = append(res, errors.New(500, "no consumer registered for %s", ct)) - } else { - route.Consumer = cons - requestContentType = ct - } - } - } - } - - // check and validate the response format - if len(res) == 0 && runtime.HasBody(request) { - if str := NegotiateContentType(request, route.Produces, requestContentType); str == "" { - res = append(res, errors.InvalidResponseFormat(request.Header.Get(runtime.HeaderAccept), route.Produces)) - } - } - - // now bind the request with the provided binder - // it's assumed the binder will also validate the request and return an error if the - // request is invalid - if binder != nil && len(res) == 0 { - if err := binder.BindRequest(request, route); err != nil { - return err - } - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} - -// ContentType gets the parsed value of a content type -// Returns the media type, its charset and a shallow copy of the request -// when its context doesn't contain the content type value, otherwise it returns -// the same request -// Returns the error that runtime.ContentType may retunrs. -func (c *Context) ContentType(request *http.Request) (string, string, *http.Request, error) { - var rCtx = request.Context() - - if v, ok := rCtx.Value(ctxContentType).(*contentTypeValue); ok { - return v.MediaType, v.Charset, request, nil - } - - mt, cs, err := runtime.ContentType(request.Header) - if err != nil { - return "", "", nil, err - } - rCtx = stdContext.WithValue(rCtx, ctxContentType, &contentTypeValue{mt, cs}) - return mt, cs, request.WithContext(rCtx), nil -} - -// LookupRoute looks a route up and returns true when it is found -func (c *Context) LookupRoute(request *http.Request) (*MatchedRoute, bool) { - if route, ok := c.router.Lookup(request.Method, request.URL.EscapedPath()); ok { - return route, ok - } - return nil, false -} - -// RouteInfo tries to match a route for this request -// Returns the matched route, a shallow copy of the request if its context -// contains the matched router, otherwise the same request, and a bool to -// indicate if it the request matches one of the routes, if it doesn't -// then it returns false and nil for the other two return values -func (c *Context) RouteInfo(request *http.Request) (*MatchedRoute, *http.Request, bool) { - var rCtx = request.Context() - - if v, ok := rCtx.Value(ctxMatchedRoute).(*MatchedRoute); ok { - return v, request, ok - } - - if route, ok := c.LookupRoute(request); ok { - rCtx = stdContext.WithValue(rCtx, ctxMatchedRoute, route) - return route, request.WithContext(rCtx), ok - } - - return nil, nil, false -} - -// ResponseFormat negotiates the response content type -// Returns the response format and a shallow copy of the request if its context -// doesn't contain the response format, otherwise the same request -func (c *Context) ResponseFormat(r *http.Request, offers []string) (string, *http.Request) { - var rCtx = r.Context() - - if v, ok := rCtx.Value(ctxResponseFormat).(string); ok { - debugLog("[%s %s] found response format %q in context", r.Method, r.URL.Path, v) - return v, r - } - - format := NegotiateContentType(r, offers, "") - if format != "" { - debugLog("[%s %s] set response format %q in context", r.Method, r.URL.Path, format) - r = r.WithContext(stdContext.WithValue(rCtx, ctxResponseFormat, format)) - } - debugLog("[%s %s] negotiated response format %q", r.Method, r.URL.Path, format) - return format, r -} - -// AllowedMethods gets the allowed methods for the path of this request -func (c *Context) AllowedMethods(request *http.Request) []string { - return c.router.OtherMethods(request.Method, request.URL.EscapedPath()) -} - -// Authorize authorizes the request -// Returns the principal object and a shallow copy of the request when its -// context doesn't contain the principal, otherwise the same request or an error -// (the last) if one of the authenticators returns one or an Unauthenticated error -func (c *Context) Authorize(request *http.Request, route *MatchedRoute) (interface{}, *http.Request, error) { - if route == nil || len(route.Authenticators) == 0 { - return nil, nil, nil - } - - var rCtx = request.Context() - if v := rCtx.Value(ctxSecurityPrincipal); v != nil { - return v, request, nil - } - - var lastError error - for scheme, authenticator := range route.Authenticators { - applies, usr, err := authenticator.Authenticate(&security.ScopedAuthRequest{ - Request: request, - RequiredScopes: route.Scopes[scheme], - }) - if !applies || err != nil || usr == nil { - if err != nil { - lastError = err - } - continue - } - if route.Authorizer != nil { - if err := route.Authorizer.Authorize(request, usr); err != nil { - return nil, nil, errors.New(http.StatusForbidden, err.Error()) - } - } - rCtx = stdContext.WithValue(rCtx, ctxSecurityPrincipal, usr) - rCtx = stdContext.WithValue(rCtx, ctxSecurityScopes, route.Scopes[scheme]) - return usr, request.WithContext(rCtx), nil - } - - if lastError != nil { - return nil, nil, lastError - } - - return nil, nil, errors.Unauthenticated("invalid credentials") -} - -// BindAndValidate binds and validates the request -// Returns the validation map and a shallow copy of the request when its context -// doesn't contain the validation, otherwise it returns the same request or an -// CompositeValidationError error -func (c *Context) BindAndValidate(request *http.Request, matched *MatchedRoute) (interface{}, *http.Request, error) { - var rCtx = request.Context() - - if v, ok := rCtx.Value(ctxBoundParams).(*validation); ok { - debugLog("got cached validation (valid: %t)", len(v.result) == 0) - if len(v.result) > 0 { - return v.bound, request, errors.CompositeValidationError(v.result...) - } - return v.bound, request, nil - } - result := validateRequest(c, request, matched) - rCtx = stdContext.WithValue(rCtx, ctxBoundParams, result) - request = request.WithContext(rCtx) - if len(result.result) > 0 { - return result.bound, request, errors.CompositeValidationError(result.result...) - } - debugLog("no validation errors found") - return result.bound, request, nil -} - -// NotFound the default not found responder for when no route has been matched yet -func (c *Context) NotFound(rw http.ResponseWriter, r *http.Request) { - c.Respond(rw, r, []string{c.api.DefaultProduces()}, nil, errors.NotFound("not found")) -} - -// Respond renders the response after doing some content negotiation -func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []string, route *MatchedRoute, data interface{}) { - debugLog("responding to %s %s with produces: %v", r.Method, r.URL.Path, produces) - offers := []string{} - for _, mt := range produces { - if mt != c.api.DefaultProduces() { - offers = append(offers, mt) - } - } - // the default producer is last so more specific producers take precedence - offers = append(offers, c.api.DefaultProduces()) - debugLog("offers: %v", offers) - - var format string - format, r = c.ResponseFormat(r, offers) - rw.Header().Set(runtime.HeaderContentType, format) - - if resp, ok := data.(Responder); ok { - producers := route.Producers - prod, ok := producers[format] - if !ok { - prods := c.api.ProducersFor(normalizeOffers([]string{c.api.DefaultProduces()})) - pr, ok := prods[c.api.DefaultProduces()] - if !ok { - panic(errors.New(http.StatusInternalServerError, "can't find a producer for "+format)) - } - prod = pr - } - resp.WriteResponse(rw, prod) - return - } - - if err, ok := data.(error); ok { - if format == "" { - rw.Header().Set(runtime.HeaderContentType, runtime.JSONMime) - } - if route == nil || route.Operation == nil { - c.api.ServeErrorFor("")(rw, r, err) - return - } - c.api.ServeErrorFor(route.Operation.ID)(rw, r, err) - return - } - - if route == nil || route.Operation == nil { - rw.WriteHeader(200) - if r.Method == "HEAD" { - return - } - producers := c.api.ProducersFor(normalizeOffers(offers)) - prod, ok := producers[format] - if !ok { - panic(errors.New(http.StatusInternalServerError, "can't find a producer for "+format)) - } - if err := prod.Produce(rw, data); err != nil { - panic(err) // let the recovery middleware deal with this - } - return - } - - if _, code, ok := route.Operation.SuccessResponse(); ok { - rw.WriteHeader(code) - if code == 204 || r.Method == "HEAD" { - return - } - - producers := route.Producers - prod, ok := producers[format] - if !ok { - if !ok { - prods := c.api.ProducersFor(normalizeOffers([]string{c.api.DefaultProduces()})) - pr, ok := prods[c.api.DefaultProduces()] - if !ok { - panic(errors.New(http.StatusInternalServerError, "can't find a producer for "+format)) - } - prod = pr - } - } - if err := prod.Produce(rw, data); err != nil { - panic(err) // let the recovery middleware deal with this - } - return - } - - c.api.ServeErrorFor(route.Operation.ID)(rw, r, errors.New(http.StatusInternalServerError, "can't produce response")) -} - -// APIHandler returns a handler to serve the API, this includes a swagger spec, router and the contract defined in the swagger spec -func (c *Context) APIHandler(builder Builder) http.Handler { - b := builder - if b == nil { - b = PassthroughBuilder - } - - var title string - sp := c.spec.Spec() - if sp != nil && sp.Info != nil && sp.Info.Title != "" { - title = sp.Info.Title - } - - redocOpts := RedocOpts{ - BasePath: c.BasePath(), - Title: title, - } - - return Spec("", c.spec.Raw(), Redoc(redocOpts, c.RoutesHandler(b))) -} - -// RoutesHandler returns a handler to serve the API, just the routes and the contract defined in the swagger spec -func (c *Context) RoutesHandler(builder Builder) http.Handler { - b := builder - if b == nil { - b = PassthroughBuilder - } - return NewRouter(c, b(NewOperationExecutor(c))) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/context_test.go b/vendor/github.com/go-openapi/runtime/middleware/context_test.go deleted file mode 100644 index e236ece89..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/context_test.go +++ /dev/null @@ -1,434 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "errors" - "net/http" - "net/http/httptest" - "testing" - - "github.com/go-openapi/loads" - "github.com/go-openapi/loads/fmts" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/internal/testing/petstore" - "github.com/go-openapi/runtime/middleware/untyped" - "github.com/stretchr/testify/assert" -) - -type stubOperationHandler struct { -} - -func (s *stubOperationHandler) ParameterModel() interface{} { - return nil -} - -func (s *stubOperationHandler) Handle(params interface{}) (interface{}, error) { - return nil, nil -} - -func init() { - loads.AddLoader(fmts.YAMLMatcher, fmts.YAMLDoc) -} - -func TestContentType_Issue264(t *testing.T) { - swspec, err := loads.Spec("../fixtures/bugs/264/swagger.yml") - if assert.NoError(t, err) { - api := untyped.NewAPI(swspec) - api.RegisterConsumer("application/json", runtime.JSONConsumer()) - api.RegisterProducer("application/json", runtime.JSONProducer()) - api.RegisterOperation("delete", "/key/{id}", new(stubOperationHandler)) - - handler := Serve(swspec, api) - request, _ := http.NewRequest("DELETE", "/key/1", nil) - recorder := httptest.NewRecorder() - handler.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) - } -} - -func TestServe(t *testing.T) { - spec, api := petstore.NewAPI(t) - handler := Serve(spec, api) - - // serve spec document - request, _ := http.NewRequest("GET", "http://localhost:8080/swagger.json", nil) - request.Header.Add("Content-Type", runtime.JSONMime) - request.Header.Add("Accept", runtime.JSONMime) - recorder := httptest.NewRecorder() - - handler.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) - - request, _ = http.NewRequest("GET", "http://localhost:8080/swagger-ui", nil) - recorder = httptest.NewRecorder() - - handler.ServeHTTP(recorder, request) - assert.Equal(t, 404, recorder.Code) -} - -func TestContextAuthorize(t *testing.T) { - spec, api := petstore.NewAPI(t) - ctx := NewContext(spec, api, nil) - ctx.router = DefaultRouter(spec, ctx.api) - - request, _ := runtime.JSONRequest("GET", "/api/pets", nil) - - ri, reqWithCtx, ok := ctx.RouteInfo(request) - assert.True(t, ok) - assert.NotNil(t, reqWithCtx) - - request = reqWithCtx - - p, reqWithCtx, err := ctx.Authorize(request, ri) - assert.Error(t, err) - assert.Nil(t, p) - assert.Nil(t, reqWithCtx) - - v := request.Context().Value(ctxSecurityPrincipal) - assert.Nil(t, v) - - request.SetBasicAuth("wrong", "wrong") - p, reqWithCtx, err = ctx.Authorize(request, ri) - assert.Error(t, err) - assert.Nil(t, p) - assert.Nil(t, reqWithCtx) - - v = request.Context().Value(ctxSecurityPrincipal) - assert.Nil(t, v) - - request.SetBasicAuth("admin", "admin") - p, reqWithCtx, err = ctx.Authorize(request, ri) - assert.NoError(t, err) - assert.Equal(t, "admin", p) - assert.NotNil(t, reqWithCtx) - - // Assign the new returned request to follow with the test - request = reqWithCtx - - v, ok = request.Context().Value(ctxSecurityPrincipal).(string) - assert.True(t, ok) - assert.Equal(t, "admin", v) - - // Once the request context contains the principal the authentication - // isn't rechecked - request.SetBasicAuth("doesn't matter", "doesn't") - pp, reqCtx, rr := ctx.Authorize(request, ri) - assert.Equal(t, p, pp) - assert.Equal(t, err, rr) - assert.Equal(t, request, reqCtx) -} - -func TestContextAuthorize_WithAuthorizer(t *testing.T) { - spec, api := petstore.NewAPI(t) - ctx := NewContext(spec, api, nil) - ctx.router = DefaultRouter(spec, ctx.api) - - request, _ := runtime.JSONRequest("POST", "/api/pets", nil) - - ri, reqWithCtx, ok := ctx.RouteInfo(request) - assert.True(t, ok) - assert.NotNil(t, reqWithCtx) - - request = reqWithCtx - - request.SetBasicAuth("topuser", "topuser") - p, reqWithCtx, err := ctx.Authorize(request, ri) - assert.Error(t, err) - assert.Nil(t, p) - assert.Nil(t, reqWithCtx) - - request.SetBasicAuth("admin", "admin") - p, reqWithCtx, err = ctx.Authorize(request, ri) - assert.NoError(t, err) - assert.Equal(t, "admin", p) - assert.NotNil(t, reqWithCtx) -} - -func TestContextNegotiateContentType(t *testing.T) { - spec, api := petstore.NewAPI(t) - ctx := NewContext(spec, api, nil) - ctx.router = DefaultRouter(spec, ctx.api) - - request, _ := http.NewRequest("POST", "/api/pets", nil) - // request.Header.Add("Accept", "*/*") - request.Header.Add("content-type", "text/html") - - v := request.Context().Value(ctxBoundParams) - assert.Nil(t, v) - - ri, request, _ := ctx.RouteInfo(request) - - res := NegotiateContentType(request, ri.Produces, "text/plain") - assert.Equal(t, ri.Produces[0], res) -} - -func TestContextBindAndValidate(t *testing.T) { - spec, api := petstore.NewAPI(t) - ctx := NewContext(spec, api, nil) - ctx.router = DefaultRouter(spec, ctx.api) - - request, _ := http.NewRequest("POST", "/api/pets", nil) - request.Header.Add("Accept", "*/*") - request.Header.Add("content-type", "text/html") - request.ContentLength = 1 - - v := request.Context().Value(ctxBoundParams) - assert.Nil(t, v) - - ri, request, _ := ctx.RouteInfo(request) - data, request, result := ctx.BindAndValidate(request, ri) // this requires a much more thorough test - assert.NotNil(t, data) - assert.NotNil(t, result) - - v, ok := request.Context().Value(ctxBoundParams).(*validation) - assert.True(t, ok) - assert.NotNil(t, v) - - dd, rCtx, rr := ctx.BindAndValidate(request, ri) - assert.Equal(t, data, dd) - assert.Equal(t, result, rr) - assert.Equal(t, rCtx, request) -} - -func TestContextRender(t *testing.T) { - ct := runtime.JSONMime - spec, api := petstore.NewAPI(t) - - assert.NotNil(t, spec) - assert.NotNil(t, api) - ctx := NewContext(spec, api, nil) - ctx.router = DefaultRouter(spec, ctx.api) - - request, _ := http.NewRequest("GET", "/api/pets", nil) - request.Header.Set(runtime.HeaderAccept, ct) - ri, request, _ := ctx.RouteInfo(request) - - recorder := httptest.NewRecorder() - ctx.Respond(recorder, request, []string{ct}, ri, map[string]interface{}{"name": "hello"}) - assert.Equal(t, 200, recorder.Code) - assert.Equal(t, "{\"name\":\"hello\"}\n", recorder.Body.String()) - - recorder = httptest.NewRecorder() - ctx.Respond(recorder, request, []string{ct}, ri, errors.New("this went wrong")) - assert.Equal(t, 500, recorder.Code) - - // recorder = httptest.NewRecorder() - // assert.Panics(t, func() { ctx.Respond(recorder, request, []string{ct}, ri, map[int]interface{}{1: "hello"}) }) - - // Panic when route is nil and there is not a producer for the requested response format - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/api/pets", nil) - request.Header.Set(runtime.HeaderAccept, "text/xml") - assert.Panics(t, func() { ctx.Respond(recorder, request, []string{}, nil, map[string]interface{}{"name": "hello"}) }) - - request, _ = http.NewRequest("GET", "/api/pets", nil) - request.Header.Set(runtime.HeaderAccept, ct) - ri, request, _ = ctx.RouteInfo(request) - - recorder = httptest.NewRecorder() - ctx.Respond(recorder, request, []string{ct}, ri, map[string]interface{}{"name": "hello"}) - assert.Equal(t, 200, recorder.Code) - assert.Equal(t, "{\"name\":\"hello\"}\n", recorder.Body.String()) - - recorder = httptest.NewRecorder() - ctx.Respond(recorder, request, []string{ct}, ri, errors.New("this went wrong")) - assert.Equal(t, 500, recorder.Code) - - // recorder = httptest.NewRecorder() - // assert.Panics(t, func() { ctx.Respond(recorder, request, []string{ct}, ri, map[int]interface{}{1: "hello"}) }) - - // recorder = httptest.NewRecorder() - // request, _ = http.NewRequest("GET", "/pets", nil) - // assert.Panics(t, func() { ctx.Respond(recorder, request, []string{}, ri, map[string]interface{}{"name": "hello"}) }) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("DELETE", "/api/pets/1", nil) - ri, request, _ = ctx.RouteInfo(request) - ctx.Respond(recorder, request, ri.Produces, ri, nil) - assert.Equal(t, 204, recorder.Code) - -} - -func TestContextValidResponseFormat(t *testing.T) { - ct := "application/json" - spec, api := petstore.NewAPI(t) - ctx := NewContext(spec, api, nil) - ctx.router = DefaultRouter(spec, ctx.api) - - request, _ := http.NewRequest("GET", "http://localhost:8080", nil) - request.Header.Set(runtime.HeaderAccept, ct) - - // check there's nothing there - cached, ok := request.Context().Value(ctxResponseFormat).(string) - assert.False(t, ok) - assert.Empty(t, cached) - - // trigger the parse - mt, request := ctx.ResponseFormat(request, []string{ct}) - assert.Equal(t, ct, mt) - - // check it was cached - cached, ok = request.Context().Value(ctxResponseFormat).(string) - assert.True(t, ok) - assert.Equal(t, ct, cached) - - // check if the cast works and fetch from cache too - mt, _ = ctx.ResponseFormat(request, []string{ct}) - assert.Equal(t, ct, mt) -} - -func TestContextInvalidResponseFormat(t *testing.T) { - ct := "application/x-yaml" - other := "application/sgml" - spec, api := petstore.NewAPI(t) - ctx := NewContext(spec, api, nil) - ctx.router = DefaultRouter(spec, ctx.api) - - request, _ := http.NewRequest("GET", "http://localhost:8080", nil) - request.Header.Set(runtime.HeaderAccept, ct) - - // check there's nothing there - cached, ok := request.Context().Value(ctxResponseFormat).(string) - assert.False(t, ok) - assert.Empty(t, cached) - - // trigger the parse - mt, request := ctx.ResponseFormat(request, []string{other}) - assert.Empty(t, mt) - - // check it was cached - cached, ok = request.Context().Value(ctxResponseFormat).(string) - assert.False(t, ok) - assert.Empty(t, cached) - - // check if the cast works and fetch from cache too - mt, rCtx := ctx.ResponseFormat(request, []string{other}) - assert.Empty(t, mt) - assert.Equal(t, request, rCtx) -} - -func TestContextValidRoute(t *testing.T) { - spec, api := petstore.NewAPI(t) - ctx := NewContext(spec, api, nil) - ctx.router = DefaultRouter(spec, ctx.api) - - request, _ := http.NewRequest("GET", "/api/pets", nil) - - // check there's nothing there - cached := request.Context().Value(ctxMatchedRoute) - assert.Nil(t, cached) - - matched, rCtx, ok := ctx.RouteInfo(request) - assert.True(t, ok) - assert.NotNil(t, matched) - assert.NotNil(t, rCtx) - assert.NotEqual(t, request, rCtx) - - request = rCtx - - // check it was cached - _, ok = request.Context().Value(ctxMatchedRoute).(*MatchedRoute) - assert.True(t, ok) - - matched, rCtx, ok = ctx.RouteInfo(request) - assert.True(t, ok) - assert.NotNil(t, matched) - assert.Equal(t, request, rCtx) -} - -func TestContextInvalidRoute(t *testing.T) { - spec, api := petstore.NewAPI(t) - ctx := NewContext(spec, api, nil) - ctx.router = DefaultRouter(spec, ctx.api) - - request, _ := http.NewRequest("DELETE", "pets", nil) - - // check there's nothing there - cached := request.Context().Value(ctxMatchedRoute) - assert.Nil(t, cached) - - matched, rCtx, ok := ctx.RouteInfo(request) - assert.False(t, ok) - assert.Nil(t, matched) - assert.Nil(t, rCtx) - - // check it was not cached - cached = request.Context().Value(ctxMatchedRoute) - assert.Nil(t, cached) - - matched, rCtx, ok = ctx.RouteInfo(request) - assert.False(t, ok) - assert.Nil(t, matched) - assert.Nil(t, rCtx) -} - -func TestContextValidContentType(t *testing.T) { - ct := "application/json" - ctx := NewContext(nil, nil, nil) - - request, _ := http.NewRequest("GET", "http://localhost:8080", nil) - request.Header.Set(runtime.HeaderContentType, ct) - - // check there's nothing there - cached := request.Context().Value(ctxContentType) - assert.Nil(t, cached) - - // trigger the parse - mt, _, rCtx, err := ctx.ContentType(request) - assert.NoError(t, err) - assert.Equal(t, ct, mt) - assert.NotNil(t, rCtx) - assert.NotEqual(t, request, rCtx) - - request = rCtx - - // check it was cached - cached = request.Context().Value(ctxContentType) - assert.NotNil(t, cached) - - // check if the cast works and fetch from cache too - mt, _, rCtx, err = ctx.ContentType(request) - assert.NoError(t, err) - assert.Equal(t, ct, mt) - assert.Equal(t, request, rCtx) -} - -func TestContextInvalidContentType(t *testing.T) { - ct := "application(" - ctx := NewContext(nil, nil, nil) - - request, _ := http.NewRequest("GET", "http://localhost:8080", nil) - request.Header.Set(runtime.HeaderContentType, ct) - - // check there's nothing there - cached := request.Context().Value(ctxContentType) - assert.Nil(t, cached) - - // trigger the parse - mt, _, rCtx, err := ctx.ContentType(request) - assert.Error(t, err) - assert.Empty(t, mt) - assert.Nil(t, rCtx) - - // check it was not cached - cached = request.Context().Value(ctxContentType) - assert.Nil(t, cached) - - // check if the failure continues - _, _, rCtx, err = ctx.ContentType(request) - assert.Error(t, err) - assert.Nil(t, rCtx) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/LICENSE b/vendor/github.com/go-openapi/runtime/middleware/denco/LICENSE deleted file mode 100755 index e65039ad8..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2014 Naoya Inada - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/README.md b/vendor/github.com/go-openapi/runtime/middleware/denco/README.md deleted file mode 100755 index 30109e17d..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/README.md +++ /dev/null @@ -1,180 +0,0 @@ -# Denco [![Build Status](https://travis-ci.org/naoina/denco.png?branch=master)](https://travis-ci.org/naoina/denco) - -The fast and flexible HTTP request router for [Go](http://golang.org). - -Denco is based on Double-Array implementation of [Kocha-urlrouter](https://github.com/naoina/kocha-urlrouter). -However, Denco is optimized and some features added. - -## Features - -* Fast (See [go-http-routing-benchmark](https://github.com/naoina/go-http-routing-benchmark)) -* [URL patterns](#url-patterns) (`/foo/:bar` and `/foo/*wildcard`) -* Small (but enough) URL router API -* HTTP request multiplexer like `http.ServeMux` - -## Installation - - go get -u github.com/go-openapi/runtime/middleware/denco - -## Using as HTTP request multiplexer - -```go -package main - -import ( - "fmt" - "log" - "net/http" - - "github.com/go-openapi/runtime/middleware/denco" -) - -func Index(w http.ResponseWriter, r *http.Request, params denco.Params) { - fmt.Fprintf(w, "Welcome to Denco!\n") -} - -func User(w http.ResponseWriter, r *http.Request, params denco.Params) { - fmt.Fprintf(w, "Hello %s!\n", params.Get("name")) -} - -func main() { - mux := denco.NewMux() - handler, err := mux.Build([]denco.Handler{ - mux.GET("/", Index), - mux.GET("/user/:name", User), - mux.POST("/user/:name", User), - }) - if err != nil { - panic(err) - } - log.Fatal(http.ListenAndServe(":8080", handler)) -} -``` - -## Using as URL router - -```go -package main - -import ( - "fmt" - - "github.com/go-openapi/runtime/middleware/denco" -) - -type route struct { - name string -} - -func main() { - router := denco.New() - router.Build([]denco.Record{ - {"/", &route{"root"}}, - {"/user/:id", &route{"user"}}, - {"/user/:name/:id", &route{"username"}}, - {"/static/*filepath", &route{"static"}}, - }) - - data, params, found := router.Lookup("/") - // print `&main.route{name:"root"}, denco.Params(nil), true`. - fmt.Printf("%#v, %#v, %#v\n", data, params, found) - - data, params, found = router.Lookup("/user/hoge") - // print `&main.route{name:"user"}, denco.Params{denco.Param{Name:"id", Value:"hoge"}}, true`. - fmt.Printf("%#v, %#v, %#v\n", data, params, found) - - data, params, found = router.Lookup("/user/hoge/7") - // print `&main.route{name:"username"}, denco.Params{denco.Param{Name:"name", Value:"hoge"}, denco.Param{Name:"id", Value:"7"}}, true`. - fmt.Printf("%#v, %#v, %#v\n", data, params, found) - - data, params, found = router.Lookup("/static/path/to/file") - // print `&main.route{name:"static"}, denco.Params{denco.Param{Name:"filepath", Value:"path/to/file"}}, true`. - fmt.Printf("%#v, %#v, %#v\n", data, params, found) -} -``` - -See [Godoc](http://godoc.org/github.com/go-openapi/runtime/middleware/denco) for more details. - -## Getting the value of path parameter - -You can get the value of path parameter by 2 ways. - -1. Using [`denco.Params.Get`](http://godoc.org/github.com/go-openapi/runtime/middleware/denco#Params.Get) method -2. Find by loop - -```go -package main - -import ( - "fmt" - - "github.com/go-openapi/runtime/middleware/denco" -) - -func main() { - router := denco.New() - if err := router.Build([]denco.Record{ - {"/user/:name/:id", "route1"}, - }); err != nil { - panic(err) - } - - // 1. Using denco.Params.Get method. - _, params, _ := router.Lookup("/user/alice/1") - name := params.Get("name") - if name != "" { - fmt.Printf("Hello %s.\n", name) // prints "Hello alice.". - } - - // 2. Find by loop. - for _, param := range params { - if param.Name == "name" { - fmt.Printf("Hello %s.\n", name) // prints "Hello alice.". - } - } -} -``` - -## URL patterns - -Denco's route matching strategy is "most nearly matching". - -When routes `/:name` and `/alice` have been built, URI `/alice` matches the route `/alice`, not `/:name`. -Because URI `/alice` is more match with the route `/alice` than `/:name`. - -For more example, when routes below have been built: - -``` -/user/alice -/user/:name -/user/:name/:id -/user/alice/:id -/user/:id/bob -``` - -Routes matching are: - -``` -/user/alice => "/user/alice" (no match with "/user/:name") -/user/bob => "/user/:name" -/user/naoina/1 => "/user/:name/1" -/user/alice/1 => "/user/alice/:id" (no match with "/user/:name/:id") -/user/1/bob => "/user/:id/bob" (no match with "/user/:name/:id") -/user/alice/bob => "/user/alice/:id" (no match with "/user/:name/:id" and "/user/:id/bob") -``` - -## Limitation - -Denco has some limitations below. - -* Number of param records (such as `/:name`) must be less than 2^22 -* Number of elements of internal slice must be less than 2^22 - -## Benchmarks - - cd $GOPATH/github.com/go-openapi/runtime/middleware/denco - go test -bench . -benchmem - -## License - -Denco is licensed under the MIT License. diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/router.go b/vendor/github.com/go-openapi/runtime/middleware/denco/router.go deleted file mode 100755 index 73703fdde..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/router.go +++ /dev/null @@ -1,452 +0,0 @@ -// Package denco provides fast URL router. -package denco - -import ( - "fmt" - "sort" - "strings" -) - -const ( - // ParamCharacter is a special character for path parameter. - ParamCharacter = ':' - - // WildcardCharacter is a special character for wildcard path parameter. - WildcardCharacter = '*' - - // TerminationCharacter is a special character for end of path. - TerminationCharacter = '#' - - // MaxSize is max size of records and internal slice. - MaxSize = (1 << 22) - 1 -) - -// Router represents a URL router. -type Router struct { - // SizeHint expects the maximum number of path parameters in records to Build. - // SizeHint will be used to determine the capacity of the memory to allocate. - // By default, SizeHint will be determined from given records to Build. - SizeHint int - - static map[string]interface{} - param *doubleArray -} - -// New returns a new Router. -func New() *Router { - return &Router{ - SizeHint: -1, - static: make(map[string]interface{}), - param: newDoubleArray(), - } -} - -// Lookup returns data and path parameters that associated with path. -// params is a slice of the Param that arranged in the order in which parameters appeared. -// e.g. when built routing path is "/path/to/:id/:name" and given path is "/path/to/1/alice". params order is [{"id": "1"}, {"name": "alice"}], not [{"name": "alice"}, {"id": "1"}]. -func (rt *Router) Lookup(path string) (data interface{}, params Params, found bool) { - if data, found := rt.static[path]; found { - return data, nil, true - } - if len(rt.param.node) == 1 { - return nil, nil, false - } - nd, params, found := rt.param.lookup(path, make([]Param, 0, rt.SizeHint), 1) - if !found { - return nil, nil, false - } - for i := 0; i < len(params); i++ { - params[i].Name = nd.paramNames[i] - } - return nd.data, params, true -} - -// Build builds URL router from records. -func (rt *Router) Build(records []Record) error { - statics, params := makeRecords(records) - if len(params) > MaxSize { - return fmt.Errorf("denco: too many records") - } - if rt.SizeHint < 0 { - rt.SizeHint = 0 - for _, p := range params { - size := 0 - for _, k := range p.Key { - if k == ParamCharacter || k == WildcardCharacter { - size++ - } - } - if size > rt.SizeHint { - rt.SizeHint = size - } - } - } - for _, r := range statics { - rt.static[r.Key] = r.Value - } - if err := rt.param.build(params, 1, 0, make(map[int]struct{})); err != nil { - return err - } - return nil -} - -// Param represents name and value of path parameter. -type Param struct { - Name string - Value string -} - -// Params represents the name and value of path parameters. -type Params []Param - -// Get gets the first value associated with the given name. -// If there are no values associated with the key, Get returns "". -func (ps Params) Get(name string) string { - for _, p := range ps { - if p.Name == name { - return p.Value - } - } - return "" -} - -type doubleArray struct { - bc []baseCheck - node []*node -} - -func newDoubleArray() *doubleArray { - return &doubleArray{ - bc: []baseCheck{0}, - node: []*node{nil}, // A start index is adjusting to 1 because 0 will be used as a mark of non-existent node. - } -} - -// baseCheck contains BASE, CHECK and Extra flags. -// From the top, 22bits of BASE, 2bits of Extra flags and 8bits of CHECK. -// -// BASE (22bit) | Extra flags (2bit) | CHECK (8bit) -// |----------------------|--|--------| -// 32 10 8 0 -type baseCheck uint32 - -func (bc baseCheck) Base() int { - return int(bc >> 10) -} - -func (bc *baseCheck) SetBase(base int) { - *bc |= baseCheck(base) << 10 -} - -func (bc baseCheck) Check() byte { - return byte(bc) -} - -func (bc *baseCheck) SetCheck(check byte) { - *bc |= baseCheck(check) -} - -func (bc baseCheck) IsEmpty() bool { - return bc&0xfffffcff == 0 -} - -func (bc baseCheck) IsSingleParam() bool { - return bc¶mTypeSingle == paramTypeSingle -} - -func (bc baseCheck) IsWildcardParam() bool { - return bc¶mTypeWildcard == paramTypeWildcard -} - -func (bc baseCheck) IsAnyParam() bool { - return bc¶mTypeAny != 0 -} - -func (bc *baseCheck) SetSingleParam() { - *bc |= (1 << 8) -} - -func (bc *baseCheck) SetWildcardParam() { - *bc |= (1 << 9) -} - -const ( - paramTypeSingle = 0x0100 - paramTypeWildcard = 0x0200 - paramTypeAny = 0x0300 -) - -func (da *doubleArray) lookup(path string, params []Param, idx int) (*node, []Param, bool) { - indices := make([]uint64, 0, 1) - for i := 0; i < len(path); i++ { - if da.bc[idx].IsAnyParam() { - indices = append(indices, (uint64(i)<<32)|(uint64(idx)&0xffffffff)) - } - c := path[i] - if idx = nextIndex(da.bc[idx].Base(), c); idx >= len(da.bc) || da.bc[idx].Check() != c { - goto BACKTRACKING - } - } - if next := nextIndex(da.bc[idx].Base(), TerminationCharacter); next < len(da.bc) && da.bc[next].Check() == TerminationCharacter { - return da.node[da.bc[next].Base()], params, true - } -BACKTRACKING: - for j := len(indices) - 1; j >= 0; j-- { - i, idx := int(indices[j]>>32), int(indices[j]&0xffffffff) - if da.bc[idx].IsSingleParam() { - idx := nextIndex(da.bc[idx].Base(), ParamCharacter) - if idx >= len(da.bc) { - break - } - next := NextSeparator(path, i) - params := append(params, Param{Value: path[i:next]}) - if nd, params, found := da.lookup(path[next:], params, idx); found { - return nd, params, true - } - } - if da.bc[idx].IsWildcardParam() { - idx := nextIndex(da.bc[idx].Base(), WildcardCharacter) - params := append(params, Param{Value: path[i:]}) - return da.node[da.bc[idx].Base()], params, true - } - } - return nil, nil, false -} - -// build builds double-array from records. -func (da *doubleArray) build(srcs []*record, idx, depth int, usedBase map[int]struct{}) error { - sort.Stable(recordSlice(srcs)) - base, siblings, leaf, err := da.arrange(srcs, idx, depth, usedBase) - if err != nil { - return err - } - if leaf != nil { - nd, err := makeNode(leaf) - if err != nil { - return err - } - da.bc[idx].SetBase(len(da.node)) - da.node = append(da.node, nd) - } - for _, sib := range siblings { - da.setCheck(nextIndex(base, sib.c), sib.c) - } - for _, sib := range siblings { - records := srcs[sib.start:sib.end] - switch sib.c { - case ParamCharacter: - for _, r := range records { - next := NextSeparator(r.Key, depth+1) - name := r.Key[depth+1 : next] - r.paramNames = append(r.paramNames, name) - r.Key = r.Key[next:] - } - da.bc[idx].SetSingleParam() - if err := da.build(records, nextIndex(base, sib.c), 0, usedBase); err != nil { - return err - } - case WildcardCharacter: - r := records[0] - name := r.Key[depth+1 : len(r.Key)-1] - r.paramNames = append(r.paramNames, name) - r.Key = "" - da.bc[idx].SetWildcardParam() - if err := da.build(records, nextIndex(base, sib.c), 0, usedBase); err != nil { - return err - } - default: - if err := da.build(records, nextIndex(base, sib.c), depth+1, usedBase); err != nil { - return err - } - } - } - return nil -} - -// setBase sets BASE. -func (da *doubleArray) setBase(i, base int) { - da.bc[i].SetBase(base) -} - -// setCheck sets CHECK. -func (da *doubleArray) setCheck(i int, check byte) { - da.bc[i].SetCheck(check) -} - -// findEmptyIndex returns an index of unused BASE/CHECK node. -func (da *doubleArray) findEmptyIndex(start int) int { - i := start - for ; i < len(da.bc); i++ { - if da.bc[i].IsEmpty() { - break - } - } - return i -} - -// findBase returns good BASE. -func (da *doubleArray) findBase(siblings []sibling, start int, usedBase map[int]struct{}) (base int) { - for idx, firstChar := start+1, siblings[0].c; ; idx = da.findEmptyIndex(idx + 1) { - base = nextIndex(idx, firstChar) - if _, used := usedBase[base]; used { - continue - } - i := 0 - for ; i < len(siblings); i++ { - next := nextIndex(base, siblings[i].c) - if len(da.bc) <= next { - da.bc = append(da.bc, make([]baseCheck, next-len(da.bc)+1)...) - } - if !da.bc[next].IsEmpty() { - break - } - } - if i == len(siblings) { - break - } - } - usedBase[base] = struct{}{} - return base -} - -func (da *doubleArray) arrange(records []*record, idx, depth int, usedBase map[int]struct{}) (base int, siblings []sibling, leaf *record, err error) { - siblings, leaf, err = makeSiblings(records, depth) - if err != nil { - return -1, nil, nil, err - } - if len(siblings) < 1 { - return -1, nil, leaf, nil - } - base = da.findBase(siblings, idx, usedBase) - if base > MaxSize { - return -1, nil, nil, fmt.Errorf("denco: too many elements of internal slice") - } - da.setBase(idx, base) - return base, siblings, leaf, err -} - -// node represents a node of Double-Array. -type node struct { - data interface{} - - // Names of path parameters. - paramNames []string -} - -// makeNode returns a new node from record. -func makeNode(r *record) (*node, error) { - dups := make(map[string]bool) - for _, name := range r.paramNames { - if dups[name] { - return nil, fmt.Errorf("denco: path parameter `%v' is duplicated in the key `%v'", name, r.Key) - } - dups[name] = true - } - return &node{data: r.Value, paramNames: r.paramNames}, nil -} - -// sibling represents an intermediate data of build for Double-Array. -type sibling struct { - // An index of start of duplicated characters. - start int - - // An index of end of duplicated characters. - end int - - // A character of sibling. - c byte -} - -// nextIndex returns a next index of array of BASE/CHECK. -func nextIndex(base int, c byte) int { - return base ^ int(c) -} - -// makeSiblings returns slice of sibling. -func makeSiblings(records []*record, depth int) (sib []sibling, leaf *record, err error) { - var ( - pc byte - n int - ) - for i, r := range records { - if len(r.Key) <= depth { - leaf = r - continue - } - c := r.Key[depth] - switch { - case pc < c: - sib = append(sib, sibling{start: i, c: c}) - case pc == c: - continue - default: - return nil, nil, fmt.Errorf("denco: BUG: routing table hasn't been sorted") - } - if n > 0 { - sib[n-1].end = i - } - pc = c - n++ - } - if n == 0 { - return nil, leaf, nil - } - sib[n-1].end = len(records) - return sib, leaf, nil -} - -// Record represents a record data for router construction. -type Record struct { - // Key for router construction. - Key string - - // Result value for Key. - Value interface{} -} - -// NewRecord returns a new Record. -func NewRecord(key string, value interface{}) Record { - return Record{ - Key: key, - Value: value, - } -} - -// record represents a record that use to build the Double-Array. -type record struct { - Record - paramNames []string -} - -// makeRecords returns the records that use to build Double-Arrays. -func makeRecords(srcs []Record) (statics, params []*record) { - spChars := string([]byte{ParamCharacter, WildcardCharacter}) - termChar := string(TerminationCharacter) - for _, r := range srcs { - if strings.ContainsAny(r.Key, spChars) { - r.Key += termChar - params = append(params, &record{Record: r}) - } else { - statics = append(statics, &record{Record: r}) - } - } - return statics, params -} - -// recordSlice represents a slice of Record for sort and implements the sort.Interface. -type recordSlice []*record - -// Len implements the sort.Interface.Len. -func (rs recordSlice) Len() int { - return len(rs) -} - -// Less implements the sort.Interface.Less. -func (rs recordSlice) Less(i, j int) bool { - return rs[i].Key < rs[j].Key -} - -// Swap implements the sort.Interface.Swap. -func (rs recordSlice) Swap(i, j int) { - rs[i], rs[j] = rs[j], rs[i] -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/router_bench_test.go b/vendor/github.com/go-openapi/runtime/middleware/denco/router_bench_test.go deleted file mode 100755 index 312402cc2..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/router_bench_test.go +++ /dev/null @@ -1,178 +0,0 @@ -package denco_test - -import ( - "bytes" - "crypto/rand" - "fmt" - "math/big" - "testing" - - "github.com/go-openapi/runtime/middleware/denco" -) - -func BenchmarkRouterLookupStatic100(b *testing.B) { - benchmarkRouterLookupStatic(b, 100) -} - -func BenchmarkRouterLookupStatic300(b *testing.B) { - benchmarkRouterLookupStatic(b, 300) -} - -func BenchmarkRouterLookupStatic700(b *testing.B) { - benchmarkRouterLookupStatic(b, 700) -} - -func BenchmarkRouterLookupSingleParam100(b *testing.B) { - records := makeTestSingleParamRecords(100) - benchmarkRouterLookupSingleParam(b, records) -} - -func BenchmarkRouterLookupSingleParam300(b *testing.B) { - records := makeTestSingleParamRecords(300) - benchmarkRouterLookupSingleParam(b, records) -} - -func BenchmarkRouterLookupSingleParam700(b *testing.B) { - records := makeTestSingleParamRecords(700) - benchmarkRouterLookupSingleParam(b, records) -} - -func BenchmarkRouterLookupSingle2Param100(b *testing.B) { - records := makeTestSingle2ParamRecords(100) - benchmarkRouterLookupSingleParam(b, records) -} - -func BenchmarkRouterLookupSingle2Param300(b *testing.B) { - records := makeTestSingle2ParamRecords(300) - benchmarkRouterLookupSingleParam(b, records) -} - -func BenchmarkRouterLookupSingle2Param700(b *testing.B) { - records := makeTestSingle2ParamRecords(700) - benchmarkRouterLookupSingleParam(b, records) -} - -func BenchmarkRouterBuildStatic100(b *testing.B) { - records := makeTestStaticRecords(100) - benchmarkRouterBuild(b, records) -} - -func BenchmarkRouterBuildStatic300(b *testing.B) { - records := makeTestStaticRecords(300) - benchmarkRouterBuild(b, records) -} - -func BenchmarkRouterBuildStatic700(b *testing.B) { - records := makeTestStaticRecords(700) - benchmarkRouterBuild(b, records) -} - -func BenchmarkRouterBuildSingleParam100(b *testing.B) { - records := makeTestSingleParamRecords(100) - benchmarkRouterBuild(b, records) -} - -func BenchmarkRouterBuildSingleParam300(b *testing.B) { - records := makeTestSingleParamRecords(300) - benchmarkRouterBuild(b, records) -} - -func BenchmarkRouterBuildSingleParam700(b *testing.B) { - records := makeTestSingleParamRecords(700) - benchmarkRouterBuild(b, records) -} - -func BenchmarkRouterBuildSingle2Param100(b *testing.B) { - records := makeTestSingle2ParamRecords(100) - benchmarkRouterBuild(b, records) -} - -func BenchmarkRouterBuildSingle2Param300(b *testing.B) { - records := makeTestSingle2ParamRecords(300) - benchmarkRouterBuild(b, records) -} - -func BenchmarkRouterBuildSingle2Param700(b *testing.B) { - records := makeTestSingle2ParamRecords(700) - benchmarkRouterBuild(b, records) -} - -func benchmarkRouterLookupStatic(b *testing.B, n int) { - b.StopTimer() - router := denco.New() - records := makeTestStaticRecords(n) - if err := router.Build(records); err != nil { - b.Fatal(err) - } - record := pickTestRecord(records) - b.StartTimer() - for i := 0; i < b.N; i++ { - if r, _, _ := router.Lookup(record.Key); r != record.Value { - b.Fail() - } - } -} - -func benchmarkRouterLookupSingleParam(b *testing.B, records []denco.Record) { - router := denco.New() - if err := router.Build(records); err != nil { - b.Fatal(err) - } - record := pickTestRecord(records) - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, _, found := router.Lookup(record.Key); !found { - b.Fail() - } - } -} - -func benchmarkRouterBuild(b *testing.B, records []denco.Record) { - for i := 0; i < b.N; i++ { - router := denco.New() - if err := router.Build(records); err != nil { - b.Fatal(err) - } - } -} - -func makeTestStaticRecords(n int) []denco.Record { - records := make([]denco.Record, n) - for i := 0; i < n; i++ { - records[i] = denco.NewRecord("/"+randomString(50), fmt.Sprintf("testroute%d", i)) - } - return records -} - -func makeTestSingleParamRecords(n int) []denco.Record { - records := make([]denco.Record, n) - for i := 0; i < len(records); i++ { - records[i] = denco.NewRecord(fmt.Sprintf("/user%d/:name", i), fmt.Sprintf("testroute%d", i)) - } - return records -} - -func makeTestSingle2ParamRecords(n int) []denco.Record { - records := make([]denco.Record, n) - for i := 0; i < len(records); i++ { - records[i] = denco.NewRecord(fmt.Sprintf("/user%d/:name/comment/:id", i), fmt.Sprintf("testroute%d", i)) - } - return records -} - -func pickTestRecord(records []denco.Record) denco.Record { - return records[len(records)/2] -} - -func randomString(n int) string { - const srcStrings = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/" - var buf bytes.Buffer - for i := 0; i < n; i++ { - num, err := rand.Int(rand.Reader, big.NewInt(int64(len(srcStrings)-1))) - if err != nil { - panic(err) - } - buf.WriteByte(srcStrings[num.Int64()]) - } - return buf.String() -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/router_test.go b/vendor/github.com/go-openapi/runtime/middleware/denco/router_test.go deleted file mode 100755 index c0bd1cb40..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/router_test.go +++ /dev/null @@ -1,526 +0,0 @@ -package denco_test - -import ( - "fmt" - "math/rand" - "reflect" - "testing" - "time" - - "github.com/go-openapi/runtime/middleware/denco" -) - -func routes() []denco.Record { - return []denco.Record{ - {"/", "testroute0"}, - {"/path/to/route", "testroute1"}, - {"/path/to/other", "testroute2"}, - {"/path/to/route/a", "testroute3"}, - {"/path/to/:param", "testroute4"}, - {"/gists/:param1/foo/:param2", "testroute12"}, - {"/gists/:param1/foo/bar", "testroute11"}, - {"/:param1/:param2/foo/:param3", "testroute13"}, - {"/path/to/wildcard/*routepath", "testroute5"}, - {"/path/to/:param1/:param2", "testroute6"}, - {"/path/to/:param1/sep/:param2", "testroute7"}, - {"/:year/:month/:day", "testroute8"}, - {"/user/:id", "testroute9"}, - {"/a/to/b/:param/*routepath", "testroute10"}, - } -} - -var realURIs = []denco.Record{ - {"/authorizations", "/authorizations"}, - {"/authorizations/:id", "/authorizations/:id"}, - {"/applications/:client_id/tokens/:access_token", "/applications/:client_id/tokens/:access_token"}, - {"/events", "/events"}, - {"/repos/:owner/:repo/events", "/repos/:owner/:repo/events"}, - {"/networks/:owner/:repo/events", "/networks/:owner/:repo/events"}, - {"/orgs/:org/events", "/orgs/:org/events"}, - {"/users/:user/received_events", "/users/:user/received_events"}, - {"/users/:user/received_events/public", "/users/:user/received_events/public"}, - {"/users/:user/events", "/users/:user/events"}, - {"/users/:user/events/public", "/users/:user/events/public"}, - {"/users/:user/events/orgs/:org", "/users/:user/events/orgs/:org"}, - {"/feeds", "/feeds"}, - {"/notifications", "/notifications"}, - {"/repos/:owner/:repo/notifications", "/repos/:owner/:repo/notifications"}, - {"/notifications/threads/:id", "/notifications/threads/:id"}, - {"/notifications/threads/:id/subscription", "/notifications/threads/:id/subscription"}, - {"/repos/:owner/:repo/stargazers", "/repos/:owner/:repo/stargazers"}, - {"/users/:user/starred", "/users/:user/starred"}, - {"/user/starred", "/user/starred"}, - {"/user/starred/:owner/:repo", "/user/starred/:owner/:repo"}, - {"/repos/:owner/:repo/subscribers", "/repos/:owner/:repo/subscribers"}, - {"/users/:user/subscriptions", "/users/:user/subscriptions"}, - {"/user/subscriptions", "/user/subscriptions"}, - {"/repos/:owner/:repo/subscription", "/repos/:owner/:repo/subscription"}, - {"/user/subscriptions/:owner/:repo", "/user/subscriptions/:owner/:repo"}, - {"/users/:user/gists", "/users/:user/gists"}, - {"/gists", "/gists"}, - {"/gists/:id", "/gists/:id"}, - {"/gists/:id/star", "/gists/:id/star"}, - {"/repos/:owner/:repo/git/blobs/:sha", "/repos/:owner/:repo/git/blobs/:sha"}, - {"/repos/:owner/:repo/git/commits/:sha", "/repos/:owner/:repo/git/commits/:sha"}, - {"/repos/:owner/:repo/git/refs", "/repos/:owner/:repo/git/refs"}, - {"/repos/:owner/:repo/git/tags/:sha", "/repos/:owner/:repo/git/tags/:sha"}, - {"/repos/:owner/:repo/git/trees/:sha", "/repos/:owner/:repo/git/trees/:sha"}, - {"/issues", "/issues"}, - {"/user/issues", "/user/issues"}, - {"/orgs/:org/issues", "/orgs/:org/issues"}, - {"/repos/:owner/:repo/issues", "/repos/:owner/:repo/issues"}, - {"/repos/:owner/:repo/issues/:number", "/repos/:owner/:repo/issues/:number"}, - {"/repos/:owner/:repo/assignees", "/repos/:owner/:repo/assignees"}, - {"/repos/:owner/:repo/assignees/:assignee", "/repos/:owner/:repo/assignees/:assignee"}, - {"/repos/:owner/:repo/issues/:number/comments", "/repos/:owner/:repo/issues/:number/comments"}, - {"/repos/:owner/:repo/issues/:number/events", "/repos/:owner/:repo/issues/:number/events"}, - {"/repos/:owner/:repo/labels", "/repos/:owner/:repo/labels"}, - {"/repos/:owner/:repo/labels/:name", "/repos/:owner/:repo/labels/:name"}, - {"/repos/:owner/:repo/issues/:number/labels", "/repos/:owner/:repo/issues/:number/labels"}, - {"/repos/:owner/:repo/milestones/:number/labels", "/repos/:owner/:repo/milestones/:number/labels"}, - {"/repos/:owner/:repo/milestones", "/repos/:owner/:repo/milestones"}, - {"/repos/:owner/:repo/milestones/:number", "/repos/:owner/:repo/milestones/:number"}, - {"/emojis", "/emojis"}, - {"/gitignore/templates", "/gitignore/templates"}, - {"/gitignore/templates/:name", "/gitignore/templates/:name"}, - {"/meta", "/meta"}, - {"/rate_limit", "/rate_limit"}, - {"/users/:user/orgs", "/users/:user/orgs"}, - {"/user/orgs", "/user/orgs"}, - {"/orgs/:org", "/orgs/:org"}, - {"/orgs/:org/members", "/orgs/:org/members"}, - {"/orgs/:org/members/:user", "/orgs/:org/members/:user"}, - {"/orgs/:org/public_members", "/orgs/:org/public_members"}, - {"/orgs/:org/public_members/:user", "/orgs/:org/public_members/:user"}, - {"/orgs/:org/teams", "/orgs/:org/teams"}, - {"/teams/:id", "/teams/:id"}, - {"/teams/:id/members", "/teams/:id/members"}, - {"/teams/:id/members/:user", "/teams/:id/members/:user"}, - {"/teams/:id/repos", "/teams/:id/repos"}, - {"/teams/:id/repos/:owner/:repo", "/teams/:id/repos/:owner/:repo"}, - {"/user/teams", "/user/teams"}, - {"/repos/:owner/:repo/pulls", "/repos/:owner/:repo/pulls"}, - {"/repos/:owner/:repo/pulls/:number", "/repos/:owner/:repo/pulls/:number"}, - {"/repos/:owner/:repo/pulls/:number/commits", "/repos/:owner/:repo/pulls/:number/commits"}, - {"/repos/:owner/:repo/pulls/:number/files", "/repos/:owner/:repo/pulls/:number/files"}, - {"/repos/:owner/:repo/pulls/:number/merge", "/repos/:owner/:repo/pulls/:number/merge"}, - {"/repos/:owner/:repo/pulls/:number/comments", "/repos/:owner/:repo/pulls/:number/comments"}, - {"/user/repos", "/user/repos"}, - {"/users/:user/repos", "/users/:user/repos"}, - {"/orgs/:org/repos", "/orgs/:org/repos"}, - {"/repositories", "/repositories"}, - {"/repos/:owner/:repo", "/repos/:owner/:repo"}, - {"/repos/:owner/:repo/contributors", "/repos/:owner/:repo/contributors"}, - {"/repos/:owner/:repo/languages", "/repos/:owner/:repo/languages"}, - {"/repos/:owner/:repo/teams", "/repos/:owner/:repo/teams"}, - {"/repos/:owner/:repo/tags", "/repos/:owner/:repo/tags"}, - {"/repos/:owner/:repo/branches", "/repos/:owner/:repo/branches"}, - {"/repos/:owner/:repo/branches/:branch", "/repos/:owner/:repo/branches/:branch"}, - {"/repos/:owner/:repo/collaborators", "/repos/:owner/:repo/collaborators"}, - {"/repos/:owner/:repo/collaborators/:user", "/repos/:owner/:repo/collaborators/:user"}, - {"/repos/:owner/:repo/comments", "/repos/:owner/:repo/comments"}, - {"/repos/:owner/:repo/commits/:sha/comments", "/repos/:owner/:repo/commits/:sha/comments"}, - {"/repos/:owner/:repo/comments/:id", "/repos/:owner/:repo/comments/:id"}, - {"/repos/:owner/:repo/commits", "/repos/:owner/:repo/commits"}, - {"/repos/:owner/:repo/commits/:sha", "/repos/:owner/:repo/commits/:sha"}, - {"/repos/:owner/:repo/readme", "/repos/:owner/:repo/readme"}, - {"/repos/:owner/:repo/keys", "/repos/:owner/:repo/keys"}, - {"/repos/:owner/:repo/keys/:id", "/repos/:owner/:repo/keys/:id"}, - {"/repos/:owner/:repo/downloads", "/repos/:owner/:repo/downloads"}, - {"/repos/:owner/:repo/downloads/:id", "/repos/:owner/:repo/downloads/:id"}, - {"/repos/:owner/:repo/forks", "/repos/:owner/:repo/forks"}, - {"/repos/:owner/:repo/hooks", "/repos/:owner/:repo/hooks"}, - {"/repos/:owner/:repo/hooks/:id", "/repos/:owner/:repo/hooks/:id"}, - {"/repos/:owner/:repo/releases", "/repos/:owner/:repo/releases"}, - {"/repos/:owner/:repo/releases/:id", "/repos/:owner/:repo/releases/:id"}, - {"/repos/:owner/:repo/releases/:id/assets", "/repos/:owner/:repo/releases/:id/assets"}, - {"/repos/:owner/:repo/stats/contributors", "/repos/:owner/:repo/stats/contributors"}, - {"/repos/:owner/:repo/stats/commit_activity", "/repos/:owner/:repo/stats/commit_activity"}, - {"/repos/:owner/:repo/stats/code_frequency", "/repos/:owner/:repo/stats/code_frequency"}, - {"/repos/:owner/:repo/stats/participation", "/repos/:owner/:repo/stats/participation"}, - {"/repos/:owner/:repo/stats/punch_card", "/repos/:owner/:repo/stats/punch_card"}, - {"/repos/:owner/:repo/statuses/:ref", "/repos/:owner/:repo/statuses/:ref"}, - {"/search/repositories", "/search/repositories"}, - {"/search/code", "/search/code"}, - {"/search/issues", "/search/issues"}, - {"/search/users", "/search/users"}, - {"/legacy/issues/search/:owner/:repository/:state/:keyword", "/legacy/issues/search/:owner/:repository/:state/:keyword"}, - {"/legacy/repos/search/:keyword", "/legacy/repos/search/:keyword"}, - {"/legacy/user/search/:keyword", "/legacy/user/search/:keyword"}, - {"/legacy/user/email/:email", "/legacy/user/email/:email"}, - {"/users/:user", "/users/:user"}, - {"/user", "/user"}, - {"/users", "/users"}, - {"/user/emails", "/user/emails"}, - {"/users/:user/followers", "/users/:user/followers"}, - {"/user/followers", "/user/followers"}, - {"/users/:user/following", "/users/:user/following"}, - {"/user/following", "/user/following"}, - {"/user/following/:user", "/user/following/:user"}, - {"/users/:user/following/:target_user", "/users/:user/following/:target_user"}, - {"/users/:user/keys", "/users/:user/keys"}, - {"/user/keys", "/user/keys"}, - {"/user/keys/:id", "/user/keys/:id"}, - {"/people/:userId", "/people/:userId"}, - {"/people", "/people"}, - {"/activities/:activityId/people/:collection", "/activities/:activityId/people/:collection"}, - {"/people/:userId/people/:collection", "/people/:userId/people/:collection"}, - {"/people/:userId/openIdConnect", "/people/:userId/openIdConnect"}, - {"/people/:userId/activities/:collection", "/people/:userId/activities/:collection"}, - {"/activities/:activityId", "/activities/:activityId"}, - {"/activities", "/activities"}, - {"/activities/:activityId/comments", "/activities/:activityId/comments"}, - {"/comments/:commentId", "/comments/:commentId"}, - {"/people/:userId/moments/:collection", "/people/:userId/moments/:collection"}, -} - -type testcase struct { - path string - value interface{} - params []denco.Param - found bool -} - -func runLookupTest(t *testing.T, records []denco.Record, testcases []testcase) { - r := denco.New() - if err := r.Build(records); err != nil { - t.Fatal(err) - } - for _, testcase := range testcases { - data, params, found := r.Lookup(testcase.path) - if !reflect.DeepEqual(data, testcase.value) || !reflect.DeepEqual(params, denco.Params(testcase.params)) || !reflect.DeepEqual(found, testcase.found) { - t.Errorf("Router.Lookup(%q) => (%#v, %#v, %#v), want (%#v, %#v, %#v)", testcase.path, data, params, found, testcase.value, denco.Params(testcase.params), testcase.found) - } - } -} - -func TestRouter_Lookup(t *testing.T) { - testcases := []testcase{ - {"/", "testroute0", nil, true}, - {"/gists/1323/foo/bar", "testroute11", []denco.Param{{"param1", "1323"}}, true}, - {"/gists/1323/foo/133", "testroute12", []denco.Param{{"param1", "1323"}, {"param2", "133"}}, true}, - {"/234/1323/foo/133", "testroute13", []denco.Param{{"param1", "234"}, {"param2", "1323"}, {"param3", "133"}}, true}, - {"/path/to/route", "testroute1", nil, true}, - {"/path/to/other", "testroute2", nil, true}, - {"/path/to/route/a", "testroute3", nil, true}, - {"/path/to/hoge", "testroute4", []denco.Param{{"param", "hoge"}}, true}, - {"/path/to/wildcard/some/params", "testroute5", []denco.Param{{"routepath", "some/params"}}, true}, - {"/path/to/o1/o2", "testroute6", []denco.Param{{"param1", "o1"}, {"param2", "o2"}}, true}, - {"/path/to/p1/sep/p2", "testroute7", []denco.Param{{"param1", "p1"}, {"param2", "p2"}}, true}, - {"/2014/01/06", "testroute8", []denco.Param{{"year", "2014"}, {"month", "01"}, {"day", "06"}}, true}, - {"/user/777", "testroute9", []denco.Param{{"id", "777"}}, true}, - {"/a/to/b/p1/some/wildcard/params", "testroute10", []denco.Param{{"param", "p1"}, {"routepath", "some/wildcard/params"}}, true}, - {"/missing", nil, nil, false}, - } - runLookupTest(t, routes(), testcases) - - records := []denco.Record{ - {"/", "testroute0"}, - {"/:b", "testroute1"}, - {"/*wildcard", "testroute2"}, - } - testcases = []testcase{ - {"/", "testroute0", nil, true}, - {"/true", "testroute1", []denco.Param{{"b", "true"}}, true}, - {"/foo/bar", "testroute2", []denco.Param{{"wildcard", "foo/bar"}}, true}, - } - runLookupTest(t, records, testcases) - - records = []denco.Record{ - {"/networks/:owner/:repo/events", "testroute0"}, - {"/orgs/:org/events", "testroute1"}, - {"/notifications/threads/:id", "testroute2"}, - {"/mypathisgreat/:thing-id", "testroute3"}, - } - testcases = []testcase{ - {"/networks/:owner/:repo/events", "testroute0", []denco.Param{{"owner", ":owner"}, {"repo", ":repo"}}, true}, - {"/orgs/:org/events", "testroute1", []denco.Param{{"org", ":org"}}, true}, - {"/notifications/threads/:id", "testroute2", []denco.Param{{"id", ":id"}}, true}, - {"/mypathisgreat/:thing-id", "testroute3", []denco.Param{{"thing-id", ":thing-id"}}, true}, - } - runLookupTest(t, records, testcases) - - runLookupTest(t, []denco.Record{ - {"/", "route2"}, - }, []testcase{ - {"/user/alice", nil, nil, false}, - }) - - runLookupTest(t, []denco.Record{ - {"/user/:name", "route1"}, - }, []testcase{ - {"/", nil, nil, false}, - }) - - runLookupTest(t, []denco.Record{ - {"/*wildcard", "testroute0"}, - {"/a/:b", "testroute1"}, - }, []testcase{ - {"/a", "testroute0", []denco.Param{{"wildcard", "a"}}, true}, - }) -} - -func TestRouter_Lookup_withManyRoutes(t *testing.T) { - n := 1000 - rand.Seed(time.Now().UnixNano()) - records := make([]denco.Record, n) - for i := 0; i < n; i++ { - records[i] = denco.Record{Key: "/" + randomString(rand.Intn(50)+10), Value: fmt.Sprintf("route%d", i)} - } - router := denco.New() - if err := router.Build(records); err != nil { - t.Fatal(err) - } - for _, r := range records { - data, params, found := router.Lookup(r.Key) - if !reflect.DeepEqual(data, r.Value) || len(params) != 0 || !reflect.DeepEqual(found, true) { - t.Errorf("Router.Lookup(%q) => (%#v, %#v, %#v), want (%#v, %#v, %#v)", r.Key, data, len(params), found, r.Value, 0, true) - } - } -} - -func TestRouter_Lookup_realURIs(t *testing.T) { - testcases := []testcase{ - {"/authorizations", "/authorizations", nil, true}, - {"/authorizations/1", "/authorizations/:id", []denco.Param{{"id", "1"}}, true}, - {"/applications/1/tokens/zohRoo7e", "/applications/:client_id/tokens/:access_token", []denco.Param{{"client_id", "1"}, {"access_token", "zohRoo7e"}}, true}, - {"/events", "/events", nil, true}, - {"/repos/naoina/denco/events", "/repos/:owner/:repo/events", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/networks/naoina/denco/events", "/networks/:owner/:repo/events", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/orgs/something/events", "/orgs/:org/events", []denco.Param{{"org", "something"}}, true}, - {"/users/naoina/received_events", "/users/:user/received_events", []denco.Param{{"user", "naoina"}}, true}, - {"/users/naoina/received_events/public", "/users/:user/received_events/public", []denco.Param{{"user", "naoina"}}, true}, - {"/users/naoina/events", "/users/:user/events", []denco.Param{{"user", "naoina"}}, true}, - {"/users/naoina/events/public", "/users/:user/events/public", []denco.Param{{"user", "naoina"}}, true}, - {"/users/naoina/events/orgs/something", "/users/:user/events/orgs/:org", []denco.Param{{"user", "naoina"}, {"org", "something"}}, true}, - {"/feeds", "/feeds", nil, true}, - {"/notifications", "/notifications", nil, true}, - {"/repos/naoina/denco/notifications", "/repos/:owner/:repo/notifications", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/notifications/threads/1", "/notifications/threads/:id", []denco.Param{{"id", "1"}}, true}, - {"/notifications/threads/2/subscription", "/notifications/threads/:id/subscription", []denco.Param{{"id", "2"}}, true}, - {"/repos/naoina/denco/stargazers", "/repos/:owner/:repo/stargazers", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/users/naoina/starred", "/users/:user/starred", []denco.Param{{"user", "naoina"}}, true}, - {"/user/starred", "/user/starred", nil, true}, - {"/user/starred/naoina/denco", "/user/starred/:owner/:repo", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/subscribers", "/repos/:owner/:repo/subscribers", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/users/naoina/subscriptions", "/users/:user/subscriptions", []denco.Param{{"user", "naoina"}}, true}, - {"/user/subscriptions", "/user/subscriptions", nil, true}, - {"/repos/naoina/denco/subscription", "/repos/:owner/:repo/subscription", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/user/subscriptions/naoina/denco", "/user/subscriptions/:owner/:repo", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/users/naoina/gists", "/users/:user/gists", []denco.Param{{"user", "naoina"}}, true}, - {"/gists", "/gists", nil, true}, - {"/gists/1", "/gists/:id", []denco.Param{{"id", "1"}}, true}, - {"/gists/2/star", "/gists/:id/star", []denco.Param{{"id", "2"}}, true}, - {"/repos/naoina/denco/git/blobs/03c3bbc7f0d12268b9ca53d4fbfd8dc5ae5697b9", "/repos/:owner/:repo/git/blobs/:sha", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"sha", "03c3bbc7f0d12268b9ca53d4fbfd8dc5ae5697b9"}}, true}, - {"/repos/naoina/denco/git/commits/03c3bbc7f0d12268b9ca53d4fbfd8dc5ae5697b9", "/repos/:owner/:repo/git/commits/:sha", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"sha", "03c3bbc7f0d12268b9ca53d4fbfd8dc5ae5697b9"}}, true}, - {"/repos/naoina/denco/git/refs", "/repos/:owner/:repo/git/refs", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/git/tags/03c3bbc7f0d12268b9ca53d4fbfd8dc5ae5697b9", "/repos/:owner/:repo/git/tags/:sha", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"sha", "03c3bbc7f0d12268b9ca53d4fbfd8dc5ae5697b9"}}, true}, - {"/repos/naoina/denco/git/trees/03c3bbc7f0d12268b9ca53d4fbfd8dc5ae5697b9", "/repos/:owner/:repo/git/trees/:sha", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"sha", "03c3bbc7f0d12268b9ca53d4fbfd8dc5ae5697b9"}}, true}, - {"/issues", "/issues", nil, true}, - {"/user/issues", "/user/issues", nil, true}, - {"/orgs/something/issues", "/orgs/:org/issues", []denco.Param{{"org", "something"}}, true}, - {"/repos/naoina/denco/issues", "/repos/:owner/:repo/issues", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/issues/1", "/repos/:owner/:repo/issues/:number", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"number", "1"}}, true}, - {"/repos/naoina/denco/assignees", "/repos/:owner/:repo/assignees", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/assignees/foo", "/repos/:owner/:repo/assignees/:assignee", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"assignee", "foo"}}, true}, - {"/repos/naoina/denco/issues/1/comments", "/repos/:owner/:repo/issues/:number/comments", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"number", "1"}}, true}, - {"/repos/naoina/denco/issues/1/events", "/repos/:owner/:repo/issues/:number/events", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"number", "1"}}, true}, - {"/repos/naoina/denco/labels", "/repos/:owner/:repo/labels", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/labels/bug", "/repos/:owner/:repo/labels/:name", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"name", "bug"}}, true}, - {"/repos/naoina/denco/issues/1/labels", "/repos/:owner/:repo/issues/:number/labels", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"number", "1"}}, true}, - {"/repos/naoina/denco/milestones/1/labels", "/repos/:owner/:repo/milestones/:number/labels", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"number", "1"}}, true}, - {"/repos/naoina/denco/milestones", "/repos/:owner/:repo/milestones", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/milestones/1", "/repos/:owner/:repo/milestones/:number", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"number", "1"}}, true}, - {"/emojis", "/emojis", nil, true}, - {"/gitignore/templates", "/gitignore/templates", nil, true}, - {"/gitignore/templates/Go", "/gitignore/templates/:name", []denco.Param{{"name", "Go"}}, true}, - {"/meta", "/meta", nil, true}, - {"/rate_limit", "/rate_limit", nil, true}, - {"/users/naoina/orgs", "/users/:user/orgs", []denco.Param{{"user", "naoina"}}, true}, - {"/user/orgs", "/user/orgs", nil, true}, - {"/orgs/something", "/orgs/:org", []denco.Param{{"org", "something"}}, true}, - {"/orgs/something/members", "/orgs/:org/members", []denco.Param{{"org", "something"}}, true}, - {"/orgs/something/members/naoina", "/orgs/:org/members/:user", []denco.Param{{"org", "something"}, {"user", "naoina"}}, true}, - {"/orgs/something/public_members", "/orgs/:org/public_members", []denco.Param{{"org", "something"}}, true}, - {"/orgs/something/public_members/naoina", "/orgs/:org/public_members/:user", []denco.Param{{"org", "something"}, {"user", "naoina"}}, true}, - {"/orgs/something/teams", "/orgs/:org/teams", []denco.Param{{"org", "something"}}, true}, - {"/teams/1", "/teams/:id", []denco.Param{{"id", "1"}}, true}, - {"/teams/2/members", "/teams/:id/members", []denco.Param{{"id", "2"}}, true}, - {"/teams/3/members/naoina", "/teams/:id/members/:user", []denco.Param{{"id", "3"}, {"user", "naoina"}}, true}, - {"/teams/4/repos", "/teams/:id/repos", []denco.Param{{"id", "4"}}, true}, - {"/teams/5/repos/naoina/denco", "/teams/:id/repos/:owner/:repo", []denco.Param{{"id", "5"}, {"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/user/teams", "/user/teams", nil, true}, - {"/repos/naoina/denco/pulls", "/repos/:owner/:repo/pulls", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/pulls/1", "/repos/:owner/:repo/pulls/:number", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"number", "1"}}, true}, - {"/repos/naoina/denco/pulls/1/commits", "/repos/:owner/:repo/pulls/:number/commits", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"number", "1"}}, true}, - {"/repos/naoina/denco/pulls/1/files", "/repos/:owner/:repo/pulls/:number/files", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"number", "1"}}, true}, - {"/repos/naoina/denco/pulls/1/merge", "/repos/:owner/:repo/pulls/:number/merge", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"number", "1"}}, true}, - {"/repos/naoina/denco/pulls/1/comments", "/repos/:owner/:repo/pulls/:number/comments", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"number", "1"}}, true}, - {"/user/repos", "/user/repos", nil, true}, - {"/users/naoina/repos", "/users/:user/repos", []denco.Param{{"user", "naoina"}}, true}, - {"/orgs/something/repos", "/orgs/:org/repos", []denco.Param{{"org", "something"}}, true}, - {"/repositories", "/repositories", nil, true}, - {"/repos/naoina/denco", "/repos/:owner/:repo", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/contributors", "/repos/:owner/:repo/contributors", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/languages", "/repos/:owner/:repo/languages", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/teams", "/repos/:owner/:repo/teams", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/tags", "/repos/:owner/:repo/tags", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/branches", "/repos/:owner/:repo/branches", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/branches/master", "/repos/:owner/:repo/branches/:branch", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"branch", "master"}}, true}, - {"/repos/naoina/denco/collaborators", "/repos/:owner/:repo/collaborators", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/collaborators/something", "/repos/:owner/:repo/collaborators/:user", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"user", "something"}}, true}, - {"/repos/naoina/denco/comments", "/repos/:owner/:repo/comments", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/commits/03c3bbc7f0d12268b9ca53d4fbfd8dc5ae5697b9/comments", "/repos/:owner/:repo/commits/:sha/comments", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"sha", "03c3bbc7f0d12268b9ca53d4fbfd8dc5ae5697b9"}}, true}, - {"/repos/naoina/denco/comments/1", "/repos/:owner/:repo/comments/:id", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"id", "1"}}, true}, - {"/repos/naoina/denco/commits", "/repos/:owner/:repo/commits", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/commits/03c3bbc7f0d12268b9ca53d4fbfd8dc5ae5697b9", "/repos/:owner/:repo/commits/:sha", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"sha", "03c3bbc7f0d12268b9ca53d4fbfd8dc5ae5697b9"}}, true}, - {"/repos/naoina/denco/readme", "/repos/:owner/:repo/readme", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/keys", "/repos/:owner/:repo/keys", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/keys/1", "/repos/:owner/:repo/keys/:id", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"id", "1"}}, true}, - {"/repos/naoina/denco/downloads", "/repos/:owner/:repo/downloads", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/downloads/2", "/repos/:owner/:repo/downloads/:id", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"id", "2"}}, true}, - {"/repos/naoina/denco/forks", "/repos/:owner/:repo/forks", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/hooks", "/repos/:owner/:repo/hooks", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/hooks/2", "/repos/:owner/:repo/hooks/:id", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"id", "2"}}, true}, - {"/repos/naoina/denco/releases", "/repos/:owner/:repo/releases", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/releases/1", "/repos/:owner/:repo/releases/:id", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"id", "1"}}, true}, - {"/repos/naoina/denco/releases/1/assets", "/repos/:owner/:repo/releases/:id/assets", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"id", "1"}}, true}, - {"/repos/naoina/denco/stats/contributors", "/repos/:owner/:repo/stats/contributors", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/stats/commit_activity", "/repos/:owner/:repo/stats/commit_activity", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/stats/code_frequency", "/repos/:owner/:repo/stats/code_frequency", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/stats/participation", "/repos/:owner/:repo/stats/participation", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/stats/punch_card", "/repos/:owner/:repo/stats/punch_card", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}}, true}, - {"/repos/naoina/denco/statuses/master", "/repos/:owner/:repo/statuses/:ref", []denco.Param{{"owner", "naoina"}, {"repo", "denco"}, {"ref", "master"}}, true}, - {"/search/repositories", "/search/repositories", nil, true}, - {"/search/code", "/search/code", nil, true}, - {"/search/issues", "/search/issues", nil, true}, - {"/search/users", "/search/users", nil, true}, - {"/legacy/issues/search/naoina/denco/closed/test", "/legacy/issues/search/:owner/:repository/:state/:keyword", []denco.Param{{"owner", "naoina"}, {"repository", "denco"}, {"state", "closed"}, {"keyword", "test"}}, true}, - {"/legacy/repos/search/test", "/legacy/repos/search/:keyword", []denco.Param{{"keyword", "test"}}, true}, - {"/legacy/user/search/test", "/legacy/user/search/:keyword", []denco.Param{{"keyword", "test"}}, true}, - {"/legacy/user/email/naoina@kuune.org", "/legacy/user/email/:email", []denco.Param{{"email", "naoina@kuune.org"}}, true}, - {"/users/naoina", "/users/:user", []denco.Param{{"user", "naoina"}}, true}, - {"/user", "/user", nil, true}, - {"/users", "/users", nil, true}, - {"/user/emails", "/user/emails", nil, true}, - {"/users/naoina/followers", "/users/:user/followers", []denco.Param{{"user", "naoina"}}, true}, - {"/user/followers", "/user/followers", nil, true}, - {"/users/naoina/following", "/users/:user/following", []denco.Param{{"user", "naoina"}}, true}, - {"/user/following", "/user/following", nil, true}, - {"/user/following/naoina", "/user/following/:user", []denco.Param{{"user", "naoina"}}, true}, - {"/users/naoina/following/target", "/users/:user/following/:target_user", []denco.Param{{"user", "naoina"}, {"target_user", "target"}}, true}, - {"/users/naoina/keys", "/users/:user/keys", []denco.Param{{"user", "naoina"}}, true}, - {"/user/keys", "/user/keys", nil, true}, - {"/user/keys/1", "/user/keys/:id", []denco.Param{{"id", "1"}}, true}, - {"/people/me", "/people/:userId", []denco.Param{{"userId", "me"}}, true}, - {"/people", "/people", nil, true}, - {"/activities/foo/people/vault", "/activities/:activityId/people/:collection", []denco.Param{{"activityId", "foo"}, {"collection", "vault"}}, true}, - {"/people/me/people/vault", "/people/:userId/people/:collection", []denco.Param{{"userId", "me"}, {"collection", "vault"}}, true}, - {"/people/me/openIdConnect", "/people/:userId/openIdConnect", []denco.Param{{"userId", "me"}}, true}, - {"/people/me/activities/vault", "/people/:userId/activities/:collection", []denco.Param{{"userId", "me"}, {"collection", "vault"}}, true}, - {"/activities/foo", "/activities/:activityId", []denco.Param{{"activityId", "foo"}}, true}, - {"/activities", "/activities", nil, true}, - {"/activities/foo/comments", "/activities/:activityId/comments", []denco.Param{{"activityId", "foo"}}, true}, - {"/comments/hoge", "/comments/:commentId", []denco.Param{{"commentId", "hoge"}}, true}, - {"/people/me/moments/vault", "/people/:userId/moments/:collection", []denco.Param{{"userId", "me"}, {"collection", "vault"}}, true}, - } - runLookupTest(t, realURIs, testcases) -} - -func TestRouter_Build(t *testing.T) { - // test for duplicate name of path parameters. - func() { - r := denco.New() - if err := r.Build([]denco.Record{ - {"/:user/:id/:id", "testroute0"}, - {"/:user/:user/:id", "testroute0"}, - }); err == nil { - t.Errorf("no error returned by duplicate name of path parameters") - } - }() -} - -func TestRouter_Build_withoutSizeHint(t *testing.T) { - for _, v := range []struct { - keys []string - sizeHint int - }{ - {[]string{"/user"}, 0}, - {[]string{"/user/:id"}, 1}, - {[]string{"/user/:id/post"}, 1}, - {[]string{"/user/:id/:group"}, 2}, - {[]string{"/user/:id/post/:cid"}, 2}, - {[]string{"/user/:id/post/:cid", "/admin/:id/post/:cid"}, 2}, - {[]string{"/user/:id", "/admin/:id/post/:cid"}, 2}, - {[]string{"/user/:id/post/:cid", "/admin/:id/post/:cid/:type"}, 3}, - } { - r := denco.New() - actual := r.SizeHint - expect := -1 - if !reflect.DeepEqual(actual, expect) { - t.Errorf(`before Build; Router.SizeHint => (%[1]T=%#[1]v); want (%[2]T=%#[2]v)`, actual, expect) - } - records := make([]denco.Record, len(v.keys)) - for i, k := range v.keys { - records[i] = denco.Record{Key: k, Value: "value"} - } - if err := r.Build(records); err != nil { - t.Fatal(err) - } - actual = r.SizeHint - expect = v.sizeHint - if !reflect.DeepEqual(actual, expect) { - t.Errorf(`Router.Build(%#v); Router.SizeHint => (%[2]T=%#[2]v); want (%[3]T=%#[3]v)`, records, actual, expect) - } - } -} - -func TestRouter_Build_withSizeHint(t *testing.T) { - for _, v := range []struct { - key string - sizeHint int - expect int - }{ - {"/user", 0, 0}, - {"/user", 1, 1}, - {"/user", 2, 2}, - {"/user/:id", 3, 3}, - {"/user/:id/:group", 0, 0}, - {"/user/:id/:group", 1, 1}, - } { - r := denco.New() - r.SizeHint = v.sizeHint - records := []denco.Record{ - {v.key, "value"}, - } - if err := r.Build(records); err != nil { - t.Fatal(err) - } - actual := r.SizeHint - expect := v.expect - if !reflect.DeepEqual(actual, expect) { - t.Errorf(`Router.Build(%#v); Router.SizeHint => (%[2]T=%#[2]v); want (%[3]T=%#[3]v)`, records, actual, expect) - } - } -} - -func TestParams_Get(t *testing.T) { - params := denco.Params([]denco.Param{ - {"name1", "value1"}, - {"name2", "value2"}, - {"name3", "value3"}, - {"name1", "value4"}, - }) - for _, v := range []struct{ value, expected string }{ - {"name1", "value1"}, - {"name2", "value2"}, - {"name3", "value3"}, - {"name4", ""}, - } { - actual := params.Get(v.value) - expected := v.expected - if !reflect.DeepEqual(actual, expected) { - t.Errorf("Params.Get(%q) => %#v, want %#v", v.value, actual, expected) - } - } -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/server.go b/vendor/github.com/go-openapi/runtime/middleware/denco/server.go deleted file mode 100755 index 0886713c1..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/server.go +++ /dev/null @@ -1,106 +0,0 @@ -package denco - -import ( - "net/http" -) - -// Mux represents a multiplexer for HTTP request. -type Mux struct{} - -// NewMux returns a new Mux. -func NewMux() *Mux { - return &Mux{} -} - -// GET is shorthand of Mux.Handler("GET", path, handler). -func (m *Mux) GET(path string, handler HandlerFunc) Handler { - return m.Handler("GET", path, handler) -} - -// POST is shorthand of Mux.Handler("POST", path, handler). -func (m *Mux) POST(path string, handler HandlerFunc) Handler { - return m.Handler("POST", path, handler) -} - -// PUT is shorthand of Mux.Handler("PUT", path, handler). -func (m *Mux) PUT(path string, handler HandlerFunc) Handler { - return m.Handler("PUT", path, handler) -} - -// HEAD is shorthand of Mux.Handler("HEAD", path, handler). -func (m *Mux) HEAD(path string, handler HandlerFunc) Handler { - return m.Handler("HEAD", path, handler) -} - -// Handler returns a handler for HTTP method. -func (m *Mux) Handler(method, path string, handler HandlerFunc) Handler { - return Handler{ - Method: method, - Path: path, - Func: handler, - } -} - -// Build builds a http.Handler. -func (m *Mux) Build(handlers []Handler) (http.Handler, error) { - recordMap := make(map[string][]Record) - for _, h := range handlers { - recordMap[h.Method] = append(recordMap[h.Method], NewRecord(h.Path, h.Func)) - } - mux := newServeMux() - for m, records := range recordMap { - router := New() - if err := router.Build(records); err != nil { - return nil, err - } - mux.routers[m] = router - } - return mux, nil -} - -// Handler represents a handler of HTTP request. -type Handler struct { - // Method is an HTTP method. - Method string - - // Path is a routing path for handler. - Path string - - // Func is a function of handler of HTTP request. - Func HandlerFunc -} - -// The HandlerFunc type is aliased to type of handler function. -type HandlerFunc func(w http.ResponseWriter, r *http.Request, params Params) - -type serveMux struct { - routers map[string]*Router -} - -func newServeMux() *serveMux { - return &serveMux{ - routers: make(map[string]*Router), - } -} - -// ServeHTTP implements http.Handler interface. -func (mux *serveMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { - handler, params := mux.handler(r.Method, r.URL.Path) - handler(w, r, params) -} - -func (mux *serveMux) handler(method, path string) (HandlerFunc, []Param) { - if router, found := mux.routers[method]; found { - if handler, params, found := router.Lookup(path); found { - return handler.(HandlerFunc), params - } - } - return NotFound, nil -} - -// NotFound replies to the request with an HTTP 404 not found error. -// NotFound is called when unknown HTTP method or a handler not found. -// If you want to use the your own NotFound handler, please overwrite this variable. -var NotFound = func(w http.ResponseWriter, r *http.Request, _ Params) { - http.NotFound(w, r) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/server_test.go b/vendor/github.com/go-openapi/runtime/middleware/denco/server_test.go deleted file mode 100755 index 27c4f0033..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/server_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package denco_test - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - - "github.com/go-openapi/runtime/middleware/denco" -) - -func testHandlerFunc(w http.ResponseWriter, r *http.Request, params denco.Params) { - fmt.Fprintf(w, "method: %s, path: %s, params: %v", r.Method, r.URL.Path, params) -} - -func TestMux(t *testing.T) { - mux := denco.NewMux() - handler, err := mux.Build([]denco.Handler{ - mux.GET("/", testHandlerFunc), - mux.GET("/user/:name", testHandlerFunc), - mux.POST("/user/:name", testHandlerFunc), - mux.HEAD("/user/:name", testHandlerFunc), - mux.PUT("/user/:name", testHandlerFunc), - mux.Handler("GET", "/user/handler", testHandlerFunc), - mux.Handler("POST", "/user/handler", testHandlerFunc), - {"PUT", "/user/inference", testHandlerFunc}, - }) - if err != nil { - t.Fatal(err) - } - server := httptest.NewServer(handler) - defer server.Close() - - for _, v := range []struct { - status int - method, path, expected string - }{ - {200, "GET", "/", "method: GET, path: /, params: []"}, - {200, "GET", "/user/alice", "method: GET, path: /user/alice, params: [{name alice}]"}, - {200, "POST", "/user/bob", "method: POST, path: /user/bob, params: [{name bob}]"}, - {200, "HEAD", "/user/alice", ""}, - {200, "PUT", "/user/bob", "method: PUT, path: /user/bob, params: [{name bob}]"}, - {404, "POST", "/", "404 page not found\n"}, - {404, "GET", "/unknown", "404 page not found\n"}, - {404, "POST", "/user/alice/1", "404 page not found\n"}, - {200, "GET", "/user/handler", "method: GET, path: /user/handler, params: []"}, - {200, "POST", "/user/handler", "method: POST, path: /user/handler, params: []"}, - {200, "PUT", "/user/inference", "method: PUT, path: /user/inference, params: []"}, - } { - req, err := http.NewRequest(v.method, server.URL+v.path, nil) - if err != nil { - t.Error(err) - continue - } - res, err := http.DefaultClient.Do(req) - if err != nil { - t.Error(err) - continue - } - defer res.Body.Close() - body, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Error(err) - continue - } - actual := string(body) - expected := v.expected - if res.StatusCode != v.status || actual != expected { - t.Errorf(`%s "%s" => %#v %#v, want %#v %#v`, v.method, v.path, res.StatusCode, actual, v.status, expected) - } - } -} - -func TestNotFound(t *testing.T) { - mux := denco.NewMux() - handler, err := mux.Build([]denco.Handler{}) - if err != nil { - t.Fatal(err) - } - server := httptest.NewServer(handler) - defer server.Close() - - origNotFound := denco.NotFound - defer func() { - denco.NotFound = origNotFound - }() - denco.NotFound = func(w http.ResponseWriter, r *http.Request, params denco.Params) { - w.WriteHeader(http.StatusServiceUnavailable) - fmt.Fprintf(w, "method: %s, path: %s, params: %v", r.Method, r.URL.Path, params) - } - res, err := http.Get(server.URL) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - body, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatal(err) - } - actual := string(body) - expected := "method: GET, path: /, params: []" - if res.StatusCode != http.StatusServiceUnavailable || actual != expected { - t.Errorf(`GET "/" => %#v %#v, want %#v %#v`, res.StatusCode, actual, http.StatusServiceUnavailable, expected) - } -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/util.go b/vendor/github.com/go-openapi/runtime/middleware/denco/util.go deleted file mode 100755 index edc1f6ab8..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/util.go +++ /dev/null @@ -1,12 +0,0 @@ -package denco - -// NextSeparator returns an index of next separator in path. -func NextSeparator(path string, start int) int { - for start < len(path) { - if c := path[start]; c == '/' || c == TerminationCharacter { - break - } - start++ - } - return start -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/denco/util_test.go b/vendor/github.com/go-openapi/runtime/middleware/denco/util_test.go deleted file mode 100755 index c7241bec8..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/denco/util_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package denco_test - -import ( - "reflect" - "testing" - - "github.com/go-openapi/runtime/middleware/denco" -) - -func TestNextSeparator(t *testing.T) { - for _, testcase := range []struct { - path string - start int - expected interface{} - }{ - {"/path/to/route", 0, 0}, - {"/path/to/route", 1, 5}, - {"/path/to/route", 9, 14}, - {"/path.html", 1, 10}, - {"/foo/bar.html", 1, 4}, - {"/foo/bar.html/baz.png", 5, 13}, - {"/foo/bar.html/baz.png", 14, 21}, - {"path#", 0, 4}, - } { - actual := denco.NextSeparator(testcase.path, testcase.start) - expected := testcase.expected - if !reflect.DeepEqual(actual, expected) { - t.Errorf("path = %q, start = %v expect %v, but %v", testcase.path, testcase.start, expected, actual) - } - } -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/doc.go b/vendor/github.com/go-openapi/runtime/middleware/doc.go deleted file mode 100644 index c0f963a7e..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/doc.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/*Package middleware provides the library with helper functions for serving swagger APIs. - -Pseudo middleware handler - - import ( - "net/http" - - "github.com/go-openapi/errors" - ) - - func newCompleteMiddleware(ctx *Context) http.Handler { - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - // use context to lookup routes - if matched, ok := ctx.RouteInfo(r); ok { - - if len(matched.Authenticators) > 0 { - if _, err := ctx.Authorize(r, matched); err != nil { - ctx.Respond(rw, r, matched.Produces, matched, err) - return - } - } - - bound, validation := ctx.BindAndValidate(r, matched) - if validation != nil { - ctx.Respond(rw, r, matched.Produces, matched, validation) - return - } - - result, err := matched.Handler.Handle(bound) - if err != nil { - ctx.Respond(rw, r, matched.Produces, matched, err) - return - } - - ctx.Respond(rw, r, matched.Produces, matched, result) - return - } - - // Not found, check if it exists in the other methods first - if others := ctx.AllowedMethods(r); len(others) > 0 { - ctx.Respond(rw, r, ctx.spec.RequiredProduces(), nil, errors.MethodNotAllowed(r.Method, others)) - return - } - ctx.Respond(rw, r, ctx.spec.RequiredProduces(), nil, errors.NotFound("path %s was not found", r.URL.Path)) - }) - } -*/ -package middleware diff --git a/vendor/github.com/go-openapi/runtime/middleware/go18.go b/vendor/github.com/go-openapi/runtime/middleware/go18.go deleted file mode 100644 index 75c762c09..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/go18.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build go1.8 - -package middleware - -import "net/url" - -func pathUnescape(path string) (string, error) { - return url.PathUnescape(path) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/header/header.go b/vendor/github.com/go-openapi/runtime/middleware/header/header.go deleted file mode 100644 index 3e342258b..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/header/header.go +++ /dev/null @@ -1,326 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file or at -// https://developers.google.com/open-source/licenses/bsd. - -// this file was taken from the github.com/golang/gddo repository - -// Package header provides functions for parsing HTTP headers. -package header - -import ( - "net/http" - "strings" - "time" -) - -// Octet types from RFC 2616. -var octetTypes [256]octetType - -type octetType byte - -const ( - isToken octetType = 1 << iota - isSpace -) - -func init() { - // OCTET = - // CHAR = - // CTL = - // CR = - // LF = - // SP = - // HT = - // <"> = - // CRLF = CR LF - // LWS = [CRLF] 1*( SP | HT ) - // TEXT = - // separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> - // | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT - // token = 1* - // qdtext = > - - for c := 0; c < 256; c++ { - var t octetType - isCtl := c <= 31 || c == 127 - isChar := 0 <= c && c <= 127 - isSeparator := strings.ContainsRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) - if strings.ContainsRune(" \t\r\n", rune(c)) { - t |= isSpace - } - if isChar && !isCtl && !isSeparator { - t |= isToken - } - octetTypes[c] = t - } -} - -// Copy returns a shallow copy of the header. -func Copy(header http.Header) http.Header { - h := make(http.Header) - for k, vs := range header { - h[k] = vs - } - return h -} - -var timeLayouts = []string{"Mon, 02 Jan 2006 15:04:05 GMT", time.RFC850, time.ANSIC} - -// ParseTime parses the header as time. The zero value is returned if the -// header is not present or there is an error parsing the -// header. -func ParseTime(header http.Header, key string) time.Time { - if s := header.Get(key); s != "" { - for _, layout := range timeLayouts { - if t, err := time.Parse(layout, s); err == nil { - return t.UTC() - } - } - } - return time.Time{} -} - -// ParseList parses a comma separated list of values. Commas are ignored in -// quoted strings. Quoted values are not unescaped or unquoted. Whitespace is -// trimmed. -func ParseList(header http.Header, key string) []string { - var result []string - for _, s := range header[http.CanonicalHeaderKey(key)] { - begin := 0 - end := 0 - escape := false - quote := false - for i := 0; i < len(s); i++ { - b := s[i] - switch { - case escape: - escape = false - end = i + 1 - case quote: - switch b { - case '\\': - escape = true - case '"': - quote = false - } - end = i + 1 - case b == '"': - quote = true - end = i + 1 - case octetTypes[b]&isSpace != 0: - if begin == end { - begin = i + 1 - end = begin - } - case b == ',': - if begin < end { - result = append(result, s[begin:end]) - } - begin = i + 1 - end = begin - default: - end = i + 1 - } - } - if begin < end { - result = append(result, s[begin:end]) - } - } - return result -} - -// ParseValueAndParams parses a comma separated list of values with optional -// semicolon separated name-value pairs. Content-Type and Content-Disposition -// headers are in this format. -func ParseValueAndParams(header http.Header, key string) (string, map[string]string) { - return parseValueAndParams(header.Get(key)) -} - -func parseValueAndParams(s string) (value string, params map[string]string) { - params = make(map[string]string) - value, s = expectTokenSlash(s) - if value == "" { - return - } - value = strings.ToLower(value) - s = skipSpace(s) - for strings.HasPrefix(s, ";") { - var pkey string - pkey, s = expectToken(skipSpace(s[1:])) - if pkey == "" { - return - } - if !strings.HasPrefix(s, "=") { - return - } - var pvalue string - pvalue, s = expectTokenOrQuoted(s[1:]) - if pvalue == "" { - return - } - pkey = strings.ToLower(pkey) - params[pkey] = pvalue - s = skipSpace(s) - } - return -} - -// AcceptSpec ... -type AcceptSpec struct { - Value string - Q float64 -} - -// ParseAccept2 ... -func ParseAccept2(header http.Header, key string) (specs []AcceptSpec) { - for _, en := range ParseList(header, key) { - v, p := parseValueAndParams(en) - var spec AcceptSpec - spec.Value = v - spec.Q = 1.0 - if p != nil { - if q, ok := p["q"]; ok { - spec.Q, _ = expectQuality(q) - } - } - if spec.Q < 0.0 { - continue - } - specs = append(specs, spec) - } - - return -} - -// ParseAccept parses Accept* headers. -func ParseAccept(header http.Header, key string) (specs []AcceptSpec) { -loop: - for _, s := range header[key] { - for { - var spec AcceptSpec - spec.Value, s = expectTokenSlash(s) - if spec.Value == "" { - continue loop - } - spec.Q = 1.0 - s = skipSpace(s) - if strings.HasPrefix(s, ";") { - s = skipSpace(s[1:]) - for !strings.HasPrefix(s, "q=") && s != "" && !strings.HasPrefix(s, ",") { - s = skipSpace(s[1:]) - } - if strings.HasPrefix(s, "q=") { - spec.Q, s = expectQuality(s[2:]) - if spec.Q < 0.0 { - continue loop - } - } - } - specs = append(specs, spec) - s = skipSpace(s) - if !strings.HasPrefix(s, ",") { - continue loop - } - s = skipSpace(s[1:]) - } - } - return -} - -func skipSpace(s string) (rest string) { - i := 0 - for ; i < len(s); i++ { - if octetTypes[s[i]]&isSpace == 0 { - break - } - } - return s[i:] -} - -func expectToken(s string) (token, rest string) { - i := 0 - for ; i < len(s); i++ { - if octetTypes[s[i]]&isToken == 0 { - break - } - } - return s[:i], s[i:] -} - -func expectTokenSlash(s string) (token, rest string) { - i := 0 - for ; i < len(s); i++ { - b := s[i] - if (octetTypes[b]&isToken == 0) && b != '/' { - break - } - } - return s[:i], s[i:] -} - -func expectQuality(s string) (q float64, rest string) { - switch { - case len(s) == 0: - return -1, "" - case s[0] == '0': - q = 0 - case s[0] == '1': - q = 1 - default: - return -1, "" - } - s = s[1:] - if !strings.HasPrefix(s, ".") { - return q, s - } - s = s[1:] - i := 0 - n := 0 - d := 1 - for ; i < len(s); i++ { - b := s[i] - if b < '0' || b > '9' { - break - } - n = n*10 + int(b) - '0' - d *= 10 - } - return q + float64(n)/float64(d), s[i:] -} - -func expectTokenOrQuoted(s string) (value string, rest string) { - if !strings.HasPrefix(s, "\"") { - return expectToken(s) - } - s = s[1:] - for i := 0; i < len(s); i++ { - switch s[i] { - case '"': - return s[:i], s[i+1:] - case '\\': - p := make([]byte, len(s)-1) - j := copy(p, s[:i]) - escape := true - for i = i + 1; i < len(s); i++ { - b := s[i] - switch { - case escape: - escape = false - p[j] = b - j++ - case b == '\\': - escape = true - case b == '"': - return string(p[:j]), s[i+1:] - default: - p[j] = b - j++ - } - } - return "", "" - } - } - return "", "" -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/negotiate.go b/vendor/github.com/go-openapi/runtime/middleware/negotiate.go deleted file mode 100644 index a9b6f27d3..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/negotiate.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file or at -// https://developers.google.com/open-source/licenses/bsd. - -// this file was taken from the github.com/golang/gddo repository - -package middleware - -import ( - "net/http" - "strings" - - "github.com/go-openapi/runtime/middleware/header" -) - -// NegotiateContentEncoding returns the best offered content encoding for the -// request's Accept-Encoding header. If two offers match with equal weight and -// then the offer earlier in the list is preferred. If no offers are -// acceptable, then "" is returned. -func NegotiateContentEncoding(r *http.Request, offers []string) string { - bestOffer := "identity" - bestQ := -1.0 - specs := header.ParseAccept(r.Header, "Accept-Encoding") - for _, offer := range offers { - for _, spec := range specs { - if spec.Q > bestQ && - (spec.Value == "*" || spec.Value == offer) { - bestQ = spec.Q - bestOffer = offer - } - } - } - if bestQ == 0 { - bestOffer = "" - } - return bestOffer -} - -// NegotiateContentType returns the best offered content type for the request's -// Accept header. If two offers match with equal weight, then the more specific -// offer is preferred. For example, text/* trumps */*. If two offers match -// with equal weight and specificity, then the offer earlier in the list is -// preferred. If no offers match, then defaultOffer is returned. -func NegotiateContentType(r *http.Request, offers []string, defaultOffer string) string { - bestOffer := defaultOffer - bestQ := -1.0 - bestWild := 3 - specs := header.ParseAccept(r.Header, "Accept") - for _, rawOffer := range offers { - offer := normalizeOffer(rawOffer) - // No Accept header: just return the first offer. - if len(specs) == 0 { - return rawOffer - } - for _, spec := range specs { - switch { - case spec.Q == 0.0: - // ignore - case spec.Q < bestQ: - // better match found - case spec.Value == "*/*": - if spec.Q > bestQ || bestWild > 2 { - bestQ = spec.Q - bestWild = 2 - 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 = rawOffer - } - default: - if spec.Value == offer && - (spec.Q > bestQ || bestWild > 0) { - bestQ = spec.Q - bestWild = 0 - bestOffer = rawOffer - } - } - } - } - return bestOffer -} - -func normalizeOffers(orig []string) (norm []string) { - for _, o := range orig { - 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/runtime/middleware/negotiate_test.go b/vendor/github.com/go-openapi/runtime/middleware/negotiate_test.go deleted file mode 100644 index ca8d70a8e..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/negotiate_test.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file or at -// https://developers.google.com/open-source/licenses/bsd. - -package middleware - -import ( - "net/http" - "testing" -) - -var negotiateContentEncodingTests = []struct { - s string - offers []string - expect string -}{ - {"", []string{"identity", "gzip"}, "identity"}, - {"*;q=0", []string{"identity", "gzip"}, ""}, - {"gzip", []string{"identity", "gzip"}, "gzip"}, -} - -func TestNegotiateContentEnoding(t *testing.T) { - for _, tt := range negotiateContentEncodingTests { - r := &http.Request{Header: http.Header{"Accept-Encoding": {tt.s}}} - actual := NegotiateContentEncoding(r, tt.offers) - if actual != tt.expect { - t.Errorf("NegotiateContentEncoding(%q, %#v)=%q, want %q", tt.s, tt.offers, actual, tt.expect) - } - } -} - -var negotiateContentTypeTests = []struct { - s string - offers []string - defaultOffer string - expect string -}{ - {"text/html, */*;q=0", []string{"x/y"}, "", ""}, - {"text/html, */*", []string{"x/y"}, "", "x/y"}, - {"text/html, image/png", []string{"text/html", "image/png"}, "", "text/html"}, - {"text/html, image/png", []string{"image/png", "text/html"}, "", "image/png"}, - {"text/html, image/png; q=0.5", []string{"image/png"}, "", "image/png"}, - {"text/html, image/png; q=0.5", []string{"text/html"}, "", "text/html"}, - {"text/html, image/png; q=0.5", []string{"foo/bar"}, "", ""}, - {"text/html, image/png; q=0.5", []string{"image/png", "text/html"}, "", "text/html"}, - {"text/html, image/png; q=0.5", []string{"text/html", "image/png"}, "", "text/html"}, - {"text/html;q=0.5, image/png", []string{"image/png"}, "", "image/png"}, - {"text/html;q=0.5, image/png", []string{"text/html"}, "", "text/html"}, - {"text/html;q=0.5, image/png", []string{"image/png", "text/html"}, "", "image/png"}, - {"text/html;q=0.5, image/png", []string{"text/html", "image/png"}, "", "image/png"}, - {"text/html;q=0.5, image/png", []string{"text/html", "image/png"}, "", "image/png"}, - {"image/png, image/*;q=0.5", []string{"image/jpg", "image/png"}, "", "image/png"}, - {"image/png, image/*;q=0.5", []string{"image/jpg"}, "", "image/jpg"}, - {"image/png, image/*;q=0.5", []string{"image/jpg", "image/gif"}, "", "image/jpg"}, - {"image/png, image/*", []string{"image/jpg", "image/gif"}, "", "image/jpg"}, - {"image/png, image/*", []string{"image/gif", "image/jpg"}, "", "image/gif"}, - {"image/png, image/*", []string{"image/gif", "image/png"}, "", "image/png"}, - {"image/png, image/*", []string{"image/png", "image/gif"}, "", "image/png"}, - {"application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.7,text/plain;version=0.0.4;q=0.3", []string{"text/plain"}, "", "text/plain"}, - {"application/json", []string{"application/json; charset=utf-8", "image/png"}, "", "application/json; charset=utf-8"}, - {"application/json; charset=utf-8", []string{"application/json; charset=utf-8", "image/png"}, "", "application/json; charset=utf-8"}, -} - -func TestNegotiateContentType(t *testing.T) { - for _, tt := range negotiateContentTypeTests { - r := &http.Request{Header: http.Header{"Accept": {tt.s}}} - actual := NegotiateContentType(r, tt.offers, tt.defaultOffer) - if actual != tt.expect { - t.Errorf("NegotiateContentType(%q, %#v, %q)=%q, want %q", tt.s, tt.offers, tt.defaultOffer, actual, tt.expect) - } - } -} - -func TestNegotiateContentTypeNoAcceptHeader(t *testing.T) { - r := &http.Request{Header: http.Header{}} - offers := []string{"application/json", "text/xml"} - actual := NegotiateContentType(r, offers, "") - if actual != "application/json" { - t.Errorf("NegotiateContentType(empty, %#v, empty)=%q, want %q", offers, actual, "application/json") - } -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/not_implemented.go b/vendor/github.com/go-openapi/runtime/middleware/not_implemented.go deleted file mode 100644 index 466f553db..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/not_implemented.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "net/http" - - "github.com/go-openapi/runtime" -) - -type errorResp struct { - code int - response interface{} - headers http.Header -} - -func (e *errorResp) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - for k, v := range e.headers { - for _, val := range v { - rw.Header().Add(k, val) - } - } - if e.code > 0 { - rw.WriteHeader(e.code) - } else { - rw.WriteHeader(http.StatusInternalServerError) - } - if err := producer.Produce(rw, e.response); err != nil { - panic(err) - } -} - -// NotImplemented the error response when the response is not implemented -func NotImplemented(message string) Responder { - return &errorResp{http.StatusNotImplemented, message, make(http.Header)} -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/operation.go b/vendor/github.com/go-openapi/runtime/middleware/operation.go deleted file mode 100644 index 1175a63cf..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/operation.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import "net/http" - -// NewOperationExecutor creates a context aware middleware that handles the operations after routing -func NewOperationExecutor(ctx *Context) http.Handler { - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - // use context to lookup routes - route, rCtx, _ := ctx.RouteInfo(r) - if rCtx != nil { - r = rCtx - } - - route.Handler.ServeHTTP(rw, r) - }) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/operation_test.go b/vendor/github.com/go-openapi/runtime/middleware/operation_test.go deleted file mode 100644 index 90ea0618d..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/operation_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/internal/testing/petstore" - "github.com/stretchr/testify/assert" -) - -func TestOperationExecutor(t *testing.T) { - spec, api := petstore.NewAPI(t) - api.RegisterOperation("get", "/pets", runtime.OperationHandlerFunc(func(params interface{}) (interface{}, error) { - return []interface{}{ - map[string]interface{}{"id": 1, "name": "a dog"}, - }, nil - })) - - context := NewContext(spec, api, nil) - context.router = DefaultRouter(spec, context.api) - mw := NewOperationExecutor(context) - - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/api/pets", nil) - request.Header.Add("Accept", "application/json") - request.SetBasicAuth("admin", "admin") - mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) - assert.Equal(t, `[{"id":1,"name":"a dog"}]`+"\n", recorder.Body.String()) - - spec, api = petstore.NewAPI(t) - api.RegisterOperation("get", "/pets", runtime.OperationHandlerFunc(func(params interface{}) (interface{}, error) { - return nil, errors.New(422, "expected") - })) - - context = NewContext(spec, api, nil) - context.router = DefaultRouter(spec, context.api) - mw = NewOperationExecutor(context) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/api/pets", nil) - request.Header.Add("Accept", "application/json") - request.SetBasicAuth("admin", "admin") - mw.ServeHTTP(recorder, request) - assert.Equal(t, 422, recorder.Code) - assert.Equal(t, `{"code":422,"message":"expected"}`, recorder.Body.String()) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/parameter.go b/vendor/github.com/go-openapi/runtime/middleware/parameter.go deleted file mode 100644 index 8975b6e1c..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/parameter.go +++ /dev/null @@ -1,480 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "encoding" - "encoding/base64" - "fmt" - "io" - "net/http" - "reflect" - "strconv" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/spec" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/go-openapi/validate" -) - -const defaultMaxMemory = 32 << 20 - -var textUnmarshalType = reflect.TypeOf(new(encoding.TextUnmarshaler)).Elem() - -func newUntypedParamBinder(param spec.Parameter, spec *spec.Swagger, formats strfmt.Registry) *untypedParamBinder { - binder := new(untypedParamBinder) - binder.Name = param.Name - binder.parameter = ¶m - binder.formats = formats - if param.In != "body" { - binder.validator = validate.NewParamValidator(¶m, formats) - } else { - binder.validator = validate.NewSchemaValidator(param.Schema, spec, param.Name, formats) - } - - return binder -} - -type untypedParamBinder struct { - parameter *spec.Parameter - formats strfmt.Registry - Name string - validator validate.EntityValidator -} - -func (p *untypedParamBinder) Type() reflect.Type { - return p.typeForSchema(p.parameter.Type, p.parameter.Format, p.parameter.Items) -} - -func (p *untypedParamBinder) typeForSchema(tpe, format string, items *spec.Items) reflect.Type { - switch tpe { - case "boolean": - return reflect.TypeOf(true) - - case "string": - if tt, ok := p.formats.GetType(format); ok { - return tt - } - return reflect.TypeOf("") - - case "integer": - switch format { - case "int8": - return reflect.TypeOf(int8(0)) - case "int16": - return reflect.TypeOf(int16(0)) - case "int32": - return reflect.TypeOf(int32(0)) - case "int64": - return reflect.TypeOf(int64(0)) - default: - return reflect.TypeOf(int64(0)) - } - - case "number": - switch format { - case "float": - return reflect.TypeOf(float32(0)) - case "double": - return reflect.TypeOf(float64(0)) - } - - case "array": - if items == nil { - return nil - } - itemsType := p.typeForSchema(items.Type, items.Format, items.Items) - if itemsType == nil { - return nil - } - return reflect.MakeSlice(reflect.SliceOf(itemsType), 0, 0).Type() - - case "file": - return reflect.TypeOf(&runtime.File{}).Elem() - - case "object": - return reflect.TypeOf(map[string]interface{}{}) - } - return nil -} - -func (p *untypedParamBinder) allowsMulti() bool { - return p.parameter.In == "query" || p.parameter.In == "formData" -} - -func (p *untypedParamBinder) readValue(values runtime.Gettable, target reflect.Value) ([]string, bool, bool, error) { - name, in, cf, tpe := p.parameter.Name, p.parameter.In, p.parameter.CollectionFormat, p.parameter.Type - if tpe == "array" { - if cf == "multi" { - if !p.allowsMulti() { - return nil, false, false, errors.InvalidCollectionFormat(name, in, cf) - } - vv, hasKey, _ := values.GetOK(name) - return vv, false, hasKey, nil - } - - v, hk, hv := values.GetOK(name) - if !hv { - return nil, false, hk, nil - } - d, c, e := p.readFormattedSliceFieldValue(v[len(v)-1], target) - return d, c, hk, e - } - - vv, hk, _ := values.GetOK(name) - return vv, false, hk, nil -} - -func (p *untypedParamBinder) Bind(request *http.Request, routeParams RouteParams, consumer runtime.Consumer, target reflect.Value) error { - // fmt.Println("binding", p.name, "as", p.Type()) - switch p.parameter.In { - case "query": - data, custom, hasKey, err := p.readValue(runtime.Values(request.URL.Query()), target) - if err != nil { - return err - } - if custom { - return nil - } - - return p.bindValue(data, hasKey, target) - - case "header": - data, custom, hasKey, err := p.readValue(runtime.Values(request.Header), target) - if err != nil { - return err - } - if custom { - return nil - } - return p.bindValue(data, hasKey, target) - - case "path": - data, custom, hasKey, err := p.readValue(routeParams, target) - if err != nil { - return err - } - if custom { - return nil - } - return p.bindValue(data, hasKey, target) - - case "formData": - var err error - var mt string - - mt, _, e := runtime.ContentType(request.Header) - if e != nil { - // because of the interface conversion go thinks the error is not nil - // so we first check for nil and then set the err var if it's not nil - err = e - } - - if err != nil { - return errors.InvalidContentType("", []string{"multipart/form-data", "application/x-www-form-urlencoded"}) - } - - if mt != "multipart/form-data" && mt != "application/x-www-form-urlencoded" { - return errors.InvalidContentType(mt, []string{"multipart/form-data", "application/x-www-form-urlencoded"}) - } - - if mt == "multipart/form-data" { - if err = request.ParseMultipartForm(defaultMaxMemory); err != nil { - return errors.NewParseError(p.Name, p.parameter.In, "", err) - } - } - - if err = request.ParseForm(); err != nil { - return errors.NewParseError(p.Name, p.parameter.In, "", err) - } - - if p.parameter.Type == "file" { - file, header, ffErr := request.FormFile(p.parameter.Name) - if ffErr != nil { - return errors.NewParseError(p.Name, p.parameter.In, "", ffErr) - } - target.Set(reflect.ValueOf(runtime.File{Data: file, Header: header})) - return nil - } - - if request.MultipartForm != nil { - data, custom, hasKey, rvErr := p.readValue(runtime.Values(request.MultipartForm.Value), target) - if rvErr != nil { - return rvErr - } - if custom { - return nil - } - return p.bindValue(data, hasKey, target) - } - data, custom, hasKey, err := p.readValue(runtime.Values(request.PostForm), target) - if err != nil { - return err - } - if custom { - return nil - } - return p.bindValue(data, hasKey, target) - - case "body": - newValue := reflect.New(target.Type()) - if !runtime.HasBody(request) { - if p.parameter.Default != nil { - target.Set(reflect.ValueOf(p.parameter.Default)) - } - - return nil - } - if err := consumer.Consume(request.Body, newValue.Interface()); err != nil { - if err == io.EOF && p.parameter.Default != nil { - target.Set(reflect.ValueOf(p.parameter.Default)) - return nil - } - tpe := p.parameter.Type - if p.parameter.Format != "" { - tpe = p.parameter.Format - } - return errors.InvalidType(p.Name, p.parameter.In, tpe, nil) - } - target.Set(reflect.Indirect(newValue)) - return nil - default: - return errors.New(500, fmt.Sprintf("invalid parameter location %q", p.parameter.In)) - } -} - -func (p *untypedParamBinder) bindValue(data []string, hasKey bool, target reflect.Value) error { - if p.parameter.Type == "array" { - return p.setSliceFieldValue(target, p.parameter.Default, data, hasKey) - } - var d string - if len(data) > 0 { - d = data[len(data)-1] - } - return p.setFieldValue(target, p.parameter.Default, d, hasKey) -} - -func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue interface{}, data string, hasKey bool) error { - tpe := p.parameter.Type - if p.parameter.Format != "" { - tpe = p.parameter.Format - } - - if (!hasKey || (!p.parameter.AllowEmptyValue && data == "")) && p.parameter.Required && p.parameter.Default == nil { - return errors.Required(p.Name, p.parameter.In) - } - - ok, err := p.tryUnmarshaler(target, defaultValue, data) - if err != nil { - return errors.InvalidType(p.Name, p.parameter.In, tpe, data) - } - if ok { - return nil - } - - defVal := reflect.Zero(target.Type()) - if defaultValue != nil { - defVal = reflect.ValueOf(defaultValue) - } - - if tpe == "byte" { - if data == "" { - if target.CanSet() { - target.SetBytes(defVal.Bytes()) - } - return nil - } - - b, err := base64.StdEncoding.DecodeString(data) - if err != nil { - b, err = base64.URLEncoding.DecodeString(data) - if err != nil { - return errors.InvalidType(p.Name, p.parameter.In, tpe, data) - } - } - if target.CanSet() { - target.SetBytes(b) - } - return nil - } - - switch target.Kind() { - case reflect.Bool: - if data == "" { - if target.CanSet() { - target.SetBool(defVal.Bool()) - } - return nil - } - b, err := swag.ConvertBool(data) - if err != nil { - return err - } - if target.CanSet() { - target.SetBool(b) - } - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - if data == "" { - if target.CanSet() { - rd := defVal.Convert(reflect.TypeOf(int64(0))) - target.SetInt(rd.Int()) - } - return nil - } - i, err := strconv.ParseInt(data, 10, 64) - if err != nil { - return errors.InvalidType(p.Name, p.parameter.In, tpe, data) - } - if target.OverflowInt(i) { - return errors.InvalidType(p.Name, p.parameter.In, tpe, data) - } - if target.CanSet() { - target.SetInt(i) - } - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - if data == "" { - if target.CanSet() { - rd := defVal.Convert(reflect.TypeOf(uint64(0))) - target.SetUint(rd.Uint()) - } - return nil - } - u, err := strconv.ParseUint(data, 10, 64) - if err != nil { - return errors.InvalidType(p.Name, p.parameter.In, tpe, data) - } - if target.OverflowUint(u) { - return errors.InvalidType(p.Name, p.parameter.In, tpe, data) - } - if target.CanSet() { - target.SetUint(u) - } - - case reflect.Float32, reflect.Float64: - if data == "" { - if target.CanSet() { - rd := defVal.Convert(reflect.TypeOf(float64(0))) - target.SetFloat(rd.Float()) - } - return nil - } - f, err := strconv.ParseFloat(data, 64) - if err != nil { - return errors.InvalidType(p.Name, p.parameter.In, tpe, data) - } - if target.OverflowFloat(f) { - return errors.InvalidType(p.Name, p.parameter.In, tpe, data) - } - if target.CanSet() { - target.SetFloat(f) - } - - case reflect.String: - value := data - if value == "" { - value = defVal.String() - } - // validate string - if target.CanSet() { - target.SetString(value) - } - - case reflect.Ptr: - if data == "" && defVal.Kind() == reflect.Ptr { - if target.CanSet() { - target.Set(defVal) - } - return nil - } - newVal := reflect.New(target.Type().Elem()) - if err := p.setFieldValue(reflect.Indirect(newVal), defVal, data, hasKey); err != nil { - return err - } - if target.CanSet() { - target.Set(newVal) - } - - default: - return errors.InvalidType(p.Name, p.parameter.In, tpe, data) - } - return nil -} - -func (p *untypedParamBinder) tryUnmarshaler(target reflect.Value, defaultValue interface{}, data string) (bool, error) { - if !target.CanSet() { - return false, nil - } - // When a type implements encoding.TextUnmarshaler we'll use that instead of reflecting some more - if reflect.PtrTo(target.Type()).Implements(textUnmarshalType) { - if defaultValue != nil && len(data) == 0 { - target.Set(reflect.ValueOf(defaultValue)) - return true, nil - } - value := reflect.New(target.Type()) - if err := value.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(data)); err != nil { - return true, err - } - target.Set(reflect.Indirect(value)) - return true, nil - } - return false, nil -} - -func (p *untypedParamBinder) readFormattedSliceFieldValue(data string, target reflect.Value) ([]string, bool, error) { - ok, err := p.tryUnmarshaler(target, p.parameter.Default, data) - if err != nil { - return nil, true, err - } - if ok { - return nil, true, nil - } - - return swag.SplitByFormat(data, p.parameter.CollectionFormat), false, nil -} - -func (p *untypedParamBinder) setSliceFieldValue(target reflect.Value, defaultValue interface{}, data []string, hasKey bool) error { - sz := len(data) - if (!hasKey || (!p.parameter.AllowEmptyValue && (sz == 0 || (sz == 1 && data[0] == "")))) && p.parameter.Required && defaultValue == nil { - return errors.Required(p.Name, p.parameter.In) - } - - defVal := reflect.Zero(target.Type()) - if defaultValue != nil { - defVal = reflect.ValueOf(defaultValue) - } - - if !target.CanSet() { - return nil - } - if sz == 0 { - target.Set(defVal) - return nil - } - - value := reflect.MakeSlice(reflect.SliceOf(target.Type().Elem()), sz, sz) - - for i := 0; i < sz; i++ { - if err := p.setFieldValue(value.Index(i), nil, data[i], hasKey); err != nil { - return err - } - } - - target.Set(value) - - return nil -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/parameter_test.go b/vendor/github.com/go-openapi/runtime/middleware/parameter_test.go deleted file mode 100644 index d0524ab9a..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/parameter_test.go +++ /dev/null @@ -1,340 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "math" - "net/url" - "reflect" - "strconv" - "testing" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/spec" - "github.com/go-openapi/strfmt" - "github.com/stretchr/testify/assert" -) - -// type email struct { -// Address string -// } - -type paramFactory func(string) *spec.Parameter - -var paramFactories = []paramFactory{ - spec.QueryParam, - spec.HeaderParam, - spec.PathParam, - spec.FormDataParam, -} - -func np(param *spec.Parameter) *untypedParamBinder { - return newUntypedParamBinder(*param, new(spec.Swagger), strfmt.Default) -} - -var stringItems = new(spec.Items) - -func init() { - stringItems.Type = "string" -} - -func testCollectionFormat(t *testing.T, param *spec.Parameter, valid bool) { - binder := &untypedParamBinder{ - parameter: param, - } - _, _, _, err := binder.readValue(runtime.Values(nil), reflect.ValueOf(nil)) - if valid { - assert.NoError(t, err) - } else { - assert.Error(t, err) - assert.Equal(t, errors.InvalidCollectionFormat(param.Name, param.In, param.CollectionFormat), err) - } -} - -func requiredError(param *spec.Parameter) *errors.Validation { - return errors.Required(param.Name, param.In) -} - -func validateRequiredTest(t *testing.T, param *spec.Parameter, value reflect.Value) { - - binder := np(param) - err := binder.bindValue([]string{}, true, value) - assert.Error(t, err) - assert.NotNil(t, param) - assert.EqualError(t, requiredError(param), err.Error()) - err = binder.bindValue([]string{""}, true, value) - if assert.Error(t, err) { - assert.EqualError(t, requiredError(param), err.Error()) - } - - // should be impossible data, but let's go with it - err = binder.bindValue([]string{"a"}, false, value) - assert.Error(t, err) - assert.EqualError(t, requiredError(param), err.Error()) - err = binder.bindValue([]string{""}, false, value) - assert.Error(t, err) - assert.EqualError(t, requiredError(param), err.Error()) -} - -func validateRequiredAllowEmptyTest(t *testing.T, param *spec.Parameter, value reflect.Value) { - param.AllowEmptyValue = true - binder := np(param) - err := binder.bindValue([]string{}, true, value) - assert.NoError(t, err) - if assert.NotNil(t, param) { - err = binder.bindValue([]string{""}, true, value) - assert.NoError(t, err) - err = binder.bindValue([]string{"1"}, false, value) - assert.Error(t, err) - assert.EqualError(t, requiredError(param), err.Error()) - err = binder.bindValue([]string{""}, false, value) - assert.Error(t, err) - assert.EqualError(t, requiredError(param), err.Error()) - } -} - -func TestRequiredValidation(t *testing.T) { - strParam := spec.QueryParam("name").Typed("string", "").AsRequired() - validateRequiredTest(t, strParam, reflect.ValueOf("")) - validateRequiredAllowEmptyTest(t, strParam, reflect.ValueOf("")) - - intParam := spec.QueryParam("id").Typed("integer", "int32").AsRequired() - validateRequiredTest(t, intParam, reflect.ValueOf(int32(0))) - validateRequiredAllowEmptyTest(t, intParam, reflect.ValueOf(int32(0))) - longParam := spec.QueryParam("id").Typed("integer", "int64").AsRequired() - validateRequiredTest(t, longParam, reflect.ValueOf(int64(0))) - validateRequiredAllowEmptyTest(t, longParam, reflect.ValueOf(int64(0))) - - floatParam := spec.QueryParam("score").Typed("number", "float").AsRequired() - validateRequiredTest(t, floatParam, reflect.ValueOf(float32(0))) - validateRequiredAllowEmptyTest(t, floatParam, reflect.ValueOf(float32(0))) - doubleParam := spec.QueryParam("score").Typed("number", "double").AsRequired() - validateRequiredTest(t, doubleParam, reflect.ValueOf(float64(0))) - validateRequiredAllowEmptyTest(t, doubleParam, reflect.ValueOf(float64(0))) - - dateTimeParam := spec.QueryParam("registered").Typed("string", "date-time").AsRequired() - validateRequiredTest(t, dateTimeParam, reflect.ValueOf(strfmt.DateTime{})) - // validateRequiredAllowEmptyTest(t, dateTimeParam, reflect.ValueOf(strfmt.DateTime{})) - - dateParam := spec.QueryParam("registered").Typed("string", "date").AsRequired() - validateRequiredTest(t, dateParam, reflect.ValueOf(strfmt.Date{})) - // validateRequiredAllowEmptyTest(t, dateParam, reflect.ValueOf(strfmt.DateTime{})) - - sliceParam := spec.QueryParam("tags").CollectionOf(stringItems, "").AsRequired() - validateRequiredTest(t, sliceParam, reflect.MakeSlice(reflect.TypeOf([]string{}), 0, 0)) - validateRequiredAllowEmptyTest(t, sliceParam, reflect.MakeSlice(reflect.TypeOf([]string{}), 0, 0)) -} - -func TestInvalidCollectionFormat(t *testing.T) { - validCf1 := spec.QueryParam("validFmt").CollectionOf(stringItems, "multi") - validCf2 := spec.FormDataParam("validFmt2").CollectionOf(stringItems, "multi") - invalidCf1 := spec.HeaderParam("invalidHdr").CollectionOf(stringItems, "multi") - invalidCf2 := spec.PathParam("invalidPath").CollectionOf(stringItems, "multi") - - testCollectionFormat(t, validCf1, true) - testCollectionFormat(t, validCf2, true) - testCollectionFormat(t, invalidCf1, false) - testCollectionFormat(t, invalidCf2, false) -} - -func invalidTypeError(param *spec.Parameter, data interface{}) *errors.Validation { - tpe := param.Type - if param.Format != "" { - tpe = param.Format - } - return errors.InvalidType(param.Name, param.In, tpe, data) -} - -func TestTypeValidation(t *testing.T) { - for _, newParam := range paramFactories { - intParam := newParam("badInt").Typed("integer", "int32") - value := reflect.ValueOf(int32(0)) - binder := np(intParam) - err := binder.bindValue([]string{"yada"}, true, value) - // fails for invalid string - assert.Error(t, err) - assert.Equal(t, invalidTypeError(intParam, "yada"), err) - // fails for overflow - val := int64(math.MaxInt32) - str := strconv.FormatInt(val, 10) + "0" - v := int32(0) - value = reflect.ValueOf(&v).Elem() - binder = np(intParam) - err = binder.bindValue([]string{str}, true, value) - assert.Error(t, err) - assert.Equal(t, invalidTypeError(intParam, str), err) - - longParam := newParam("badLong").Typed("integer", "int64") - value = reflect.ValueOf(int64(0)) - binder = np(longParam) - err = binder.bindValue([]string{"yada"}, true, value) - // fails for invalid string - assert.Error(t, err) - assert.Equal(t, invalidTypeError(longParam, "yada"), err) - // fails for overflow - str2 := strconv.FormatInt(math.MaxInt64, 10) + "0" - v2 := int64(0) - vv2 := reflect.ValueOf(&v2).Elem() - binder = np(longParam) - err = binder.bindValue([]string{str2}, true, vv2) - assert.Error(t, err) - assert.Equal(t, invalidTypeError(longParam, str2), err) - - floatParam := newParam("badFloat").Typed("number", "float") - value = reflect.ValueOf(float64(0)) - binder = np(floatParam) - err = binder.bindValue([]string{"yada"}, true, value) - // fails for invalid string - assert.Error(t, err) - assert.Equal(t, invalidTypeError(floatParam, "yada"), err) - // fails for overflow - str3 := strconv.FormatFloat(math.MaxFloat64, 'f', 5, 64) - v3 := reflect.TypeOf(float32(0)) - value = reflect.New(v3).Elem() - binder = np(floatParam) - err = binder.bindValue([]string{str3}, true, value) - assert.Error(t, err) - assert.Equal(t, invalidTypeError(floatParam, str3), err) - - doubleParam := newParam("badDouble").Typed("number", "double") - value = reflect.ValueOf(float64(0)) - binder = np(doubleParam) - err = binder.bindValue([]string{"yada"}, true, value) - // fails for invalid string - assert.Error(t, err) - assert.Equal(t, invalidTypeError(doubleParam, "yada"), err) - // fails for overflow - str4 := "9" + strconv.FormatFloat(math.MaxFloat64, 'f', 5, 64) - v4 := reflect.TypeOf(float64(0)) - value = reflect.New(v4).Elem() - binder = np(doubleParam) - err = binder.bindValue([]string{str4}, true, value) - assert.Error(t, err) - assert.Equal(t, invalidTypeError(doubleParam, str4), err) - - dateParam := newParam("badDate").Typed("string", "date") - value = reflect.ValueOf(strfmt.Date{}) - binder = np(dateParam) - err = binder.bindValue([]string{"yada"}, true, value) - // fails for invalid string - assert.Error(t, err) - assert.Equal(t, invalidTypeError(dateParam, "yada"), err) - - dateTimeParam := newParam("badDateTime").Typed("string", "date-time") - value = reflect.ValueOf(strfmt.DateTime{}) - binder = np(dateTimeParam) - err = binder.bindValue([]string{"yada"}, true, value) - // fails for invalid string - assert.Error(t, err) - assert.Equal(t, invalidTypeError(dateTimeParam, "yada"), err) - - byteParam := newParam("badByte").Typed("string", "byte") - values := url.Values(map[string][]string{}) - values.Add("badByte", "yaüda") - v5 := []byte{} - value = reflect.ValueOf(&v5).Elem() - binder = np(byteParam) - err = binder.bindValue([]string{"yaüda"}, true, value) - // fails for invalid string - assert.Error(t, err) - assert.Equal(t, invalidTypeError(byteParam, "yaüda"), err) - } -} - -func TestTypeDetectionInvalidItems(t *testing.T) { - withoutItems := spec.QueryParam("without").CollectionOf(nil, "") - binder := &untypedParamBinder{ - Name: "without", - parameter: withoutItems, - } - assert.Nil(t, binder.Type()) - - items := new(spec.Items) - items.Type = "array" - withInvalidItems := spec.QueryParam("invalidItems").CollectionOf(items, "") - binder = &untypedParamBinder{ - Name: "invalidItems", - parameter: withInvalidItems, - } - assert.Nil(t, binder.Type()) - - noType := spec.QueryParam("invalidType") - noType.Type = "invalid" - binder = &untypedParamBinder{ - Name: "invalidType", - parameter: noType, - } - assert.Nil(t, binder.Type()) -} - -// type emailStrFmt struct { -// name string -// tpe reflect.Type -// validator FormatValidator -// } -// -// func (e *emailStrFmt) Name() string { -// return e.name -// } -// -// func (e *emailStrFmt) Type() reflect.Type { -// return e.tpe -// } -// -// func (e *emailStrFmt) Matches(str string) bool { -// return e.validator(str) -// } -// -// func TestTypeDetectionValid(t *testing.T) { -// // emlFmt := &emailStrFmt{ -// // name: "email", -// // tpe: reflect.TypeOf(email{}), -// // } -// // formats := []StringFormat{emlFmt} -// -// expected := map[string]reflect.Type{ -// "name": reflect.TypeOf(""), -// "id": reflect.TypeOf(int64(0)), -// "age": reflect.TypeOf(int32(0)), -// "score": reflect.TypeOf(float32(0)), -// "factor": reflect.TypeOf(float64(0)), -// "friend": reflect.TypeOf(map[string]interface{}{}), -// "X-Request-Id": reflect.TypeOf(int64(0)), -// "tags": reflect.TypeOf([]string{}), -// "confirmed": reflect.TypeOf(true), -// "planned": reflect.TypeOf(swagger.Date{}), -// "delivered": reflect.TypeOf(swagger.DateTime{}), -// "email": reflect.TypeOf(email{}), -// "picture": reflect.TypeOf([]byte{}), -// "file": reflect.TypeOf(&swagger.File{}).Elem(), -// } -// -// params := parametersForAllTypes("") -// emailParam := spec.QueryParam("email").Typed("string", "email") -// params["email"] = *emailParam -// -// fileParam := spec.FileParam("file") -// params["file"] = *fileParam -// -// for _, v := range params { -// binder := ¶mBinder{ -// formats: formats, -// name: v.Name, -// parameter: &v, -// } -// assert.Equal(t, expected[v.Name], binder.Type(), "name: %s", v.Name) -// } -// } diff --git a/vendor/github.com/go-openapi/runtime/middleware/pre_go18.go b/vendor/github.com/go-openapi/runtime/middleware/pre_go18.go deleted file mode 100644 index 03385251e..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/pre_go18.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build !go1.8 - -package middleware - -import "net/url" - -func pathUnescape(path string) (string, error) { - return url.QueryUnescape(path) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/redoc.go b/vendor/github.com/go-openapi/runtime/middleware/redoc.go deleted file mode 100644 index 21277948c..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/redoc.go +++ /dev/null @@ -1,101 +0,0 @@ -package middleware - -import ( - "bytes" - "fmt" - "html/template" - "net/http" - "path" -) - -// RedocOpts configures the Redoc middlewares -type RedocOpts struct { - // BasePath for the UI path, defaults to: / - BasePath string - // Path combines with BasePath for the full UI path, defaults to: docs - Path string - // SpecURL the url to find the spec for - SpecURL string - // RedocURL for the js that generates the redoc site, defaults to: https://rebilly.github.io/ReDoc/releases/latest/redoc.min.js - RedocURL string - // Title for the documentation site, default to: API documentation - Title string -} - -// EnsureDefaults in case some options are missing -func (r *RedocOpts) EnsureDefaults() { - if r.BasePath == "" { - r.BasePath = "/" - } - if r.Path == "" { - r.Path = "docs" - } - if r.SpecURL == "" { - r.SpecURL = "/swagger.json" - } - if r.RedocURL == "" { - r.RedocURL = redocLatest - } - if r.Title == "" { - r.Title = "API documentation" - } -} - -// Redoc creates a middleware to serve a documentation site for a swagger spec. -// This allows for altering the spec before starting the http listener. -// -func Redoc(opts RedocOpts, next http.Handler) http.Handler { - opts.EnsureDefaults() - - pth := path.Join(opts.BasePath, opts.Path) - tmpl := template.Must(template.New("redoc").Parse(redocTemplate)) - - buf := bytes.NewBuffer(nil) - _ = tmpl.Execute(buf, opts) - b := buf.Bytes() - - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - if r.URL.Path == pth { - rw.Header().Set("Content-Type", "text/html; charset=utf-8") - rw.WriteHeader(http.StatusOK) - - _, _ = rw.Write(b) - return - } - - if next == nil { - rw.Header().Set("Content-Type", "text/plain") - rw.WriteHeader(http.StatusNotFound) - _, _ = rw.Write([]byte(fmt.Sprintf("%q not found", pth))) - return - } - next.ServeHTTP(rw, r) - }) -} - -const ( - redocLatest = "https://rebilly.github.io/ReDoc/releases/latest/redoc.min.js" - redocTemplate = ` - - - {{ .Title }} - - - - - - - - - - - -` -) diff --git a/vendor/github.com/go-openapi/runtime/middleware/redoc_test.go b/vendor/github.com/go-openapi/runtime/middleware/redoc_test.go deleted file mode 100644 index cf13da93c..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/redoc_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package middleware - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestRedocMiddleware(t *testing.T) { - redoc := Redoc(RedocOpts{}, nil) - - req, _ := http.NewRequest("GET", "/docs", nil) - recorder := httptest.NewRecorder() - redoc.ServeHTTP(recorder, req) - assert.Equal(t, 200, recorder.Code) - assert.Equal(t, "text/html; charset=utf-8", recorder.Header().Get("Content-Type")) - assert.Contains(t, recorder.Body.String(), "API documentation") - assert.Contains(t, recorder.Body.String(), "") - assert.Contains(t, recorder.Body.String(), redocLatest) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/request.go b/vendor/github.com/go-openapi/runtime/middleware/request.go deleted file mode 100644 index ee725f587..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/request.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "net/http" - "reflect" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/spec" - "github.com/go-openapi/strfmt" -) - -// RequestBinder binds and validates the data from a http request -type untypedRequestBinder struct { - Spec *spec.Swagger - Parameters map[string]spec.Parameter - Formats strfmt.Registry - paramBinders map[string]*untypedParamBinder -} - -// NewRequestBinder creates a new binder for reading a request. -func newUntypedRequestBinder(parameters map[string]spec.Parameter, spec *spec.Swagger, formats strfmt.Registry) *untypedRequestBinder { - binders := make(map[string]*untypedParamBinder) - for fieldName, param := range parameters { - binders[fieldName] = newUntypedParamBinder(param, spec, formats) - } - return &untypedRequestBinder{ - Parameters: parameters, - paramBinders: binders, - Spec: spec, - Formats: formats, - } -} - -// Bind perform the databinding and validation -func (o *untypedRequestBinder) Bind(request *http.Request, routeParams RouteParams, consumer runtime.Consumer, data interface{}) error { - val := reflect.Indirect(reflect.ValueOf(data)) - isMap := val.Kind() == reflect.Map - var result []error - debugLog("binding %d parameters for %s %s", len(o.Parameters), request.Method, request.URL.EscapedPath()) - for fieldName, param := range o.Parameters { - binder := o.paramBinders[fieldName] - debugLog("binding parameter %s for %s %s", fieldName, request.Method, request.URL.EscapedPath()) - var target reflect.Value - if !isMap { - binder.Name = fieldName - target = val.FieldByName(fieldName) - } - - if isMap { - tpe := binder.Type() - if tpe == nil { - if param.Schema.Type.Contains("array") { - tpe = reflect.TypeOf([]interface{}{}) - } else { - tpe = reflect.TypeOf(map[string]interface{}{}) - } - } - target = reflect.Indirect(reflect.New(tpe)) - - } - - if !target.IsValid() { - result = append(result, errors.New(500, "parameter name %q is an unknown field", binder.Name)) - continue - } - - if err := binder.Bind(request, routeParams, consumer, target); err != nil { - result = append(result, err) - continue - } - - if binder.validator != nil { - rr := binder.validator.Validate(target.Interface()) - if rr != nil && rr.HasErrors() { - result = append(result, rr.AsError()) - } - } - - if isMap { - val.SetMapIndex(reflect.ValueOf(param.Name), target) - } - } - - if len(result) > 0 { - return errors.CompositeValidationError(result...) - } - - return nil -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/request_test.go b/vendor/github.com/go-openapi/runtime/middleware/request_test.go deleted file mode 100644 index 395065b80..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/request_test.go +++ /dev/null @@ -1,466 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "bytes" - "io" - "io/ioutil" - "mime/multipart" - "net/http" - "net/url" - "strings" - "testing" - "time" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/spec" - "github.com/go-openapi/strfmt" - "github.com/stretchr/testify/assert" -) - -type stubConsumer struct { -} - -func (s *stubConsumer) Consume(_ io.Reader, _ interface{}) error { - return nil -} - -type friend struct { - Name string `json:"name"` - Age int `json:"age"` -} - -type jsonRequestParams struct { - ID int64 // path - Name string // query - Friend friend // body - RequestID int64 // header - Tags []string // csv -} - -type jsonRequestPtr struct { - ID int64 // path - Name string // query - RequestID int64 // header - Tags []string // csv - Friend *friend -} - -type jsonRequestSlice struct { - ID int64 // path - Name string // query - RequestID int64 // header - Tags []string // csv - Friend []friend -} - -func parametersForAllTypes(fmt string) map[string]spec.Parameter { - if fmt == "" { - fmt = "csv" - } - nameParam := spec.QueryParam("name").Typed("string", "") - idParam := spec.PathParam("id").Typed("integer", "int64") - ageParam := spec.QueryParam("age").Typed("integer", "int32") - scoreParam := spec.QueryParam("score").Typed("number", "float") - factorParam := spec.QueryParam("factor").Typed("number", "double") - - friendSchema := new(spec.Schema).Typed("object", "") - friendParam := spec.BodyParam("friend", friendSchema) - - requestIDParam := spec.HeaderParam("X-Request-Id").Typed("integer", "int64") - requestIDParam.Extensions = spec.Extensions(map[string]interface{}{}) - requestIDParam.Extensions.Add("go-name", "RequestID") - - items := new(spec.Items) - items.Type = "string" - tagsParam := spec.QueryParam("tags").CollectionOf(items, fmt) - - confirmedParam := spec.QueryParam("confirmed").Typed("boolean", "") - plannedParam := spec.QueryParam("planned").Typed("string", "date") - deliveredParam := spec.QueryParam("delivered").Typed("string", "date-time") - pictureParam := spec.QueryParam("picture").Typed("string", "byte") // base64 encoded during transport - - return map[string]spec.Parameter{ - "ID": *idParam, - "Name": *nameParam, - "RequestID": *requestIDParam, - "Friend": *friendParam, - "Tags": *tagsParam, - "Age": *ageParam, - "Score": *scoreParam, - "Factor": *factorParam, - "Confirmed": *confirmedParam, - "Planned": *plannedParam, - "Delivered": *deliveredParam, - "Picture": *pictureParam, - } -} - -func parametersForJSONRequestParams(fmt string) map[string]spec.Parameter { - if fmt == "" { - fmt = "csv" - } - nameParam := spec.QueryParam("name").Typed("string", "") - idParam := spec.PathParam("id").Typed("integer", "int64") - - friendSchema := new(spec.Schema).Typed("object", "") - friendParam := spec.BodyParam("friend", friendSchema) - - requestIDParam := spec.HeaderParam("X-Request-Id").Typed("integer", "int64") - requestIDParam.Extensions = spec.Extensions(map[string]interface{}{}) - requestIDParam.Extensions.Add("go-name", "RequestID") - - items := new(spec.Items) - items.Type = "string" - tagsParam := spec.QueryParam("tags").CollectionOf(items, fmt) - - return map[string]spec.Parameter{ - "ID": *idParam, - "Name": *nameParam, - "RequestID": *requestIDParam, - "Friend": *friendParam, - "Tags": *tagsParam, - } -} -func parametersForJSONRequestSliceParams(fmt string) map[string]spec.Parameter { - if fmt == "" { - fmt = "csv" - } - nameParam := spec.QueryParam("name").Typed("string", "") - idParam := spec.PathParam("id").Typed("integer", "int64") - - friendSchema := new(spec.Schema).Typed("object", "") - friendParam := spec.BodyParam("friend", spec.ArrayProperty(friendSchema)) - - requestIDParam := spec.HeaderParam("X-Request-Id").Typed("integer", "int64") - requestIDParam.Extensions = spec.Extensions(map[string]interface{}{}) - requestIDParam.Extensions.Add("go-name", "RequestID") - - items := new(spec.Items) - items.Type = "string" - tagsParam := spec.QueryParam("tags").CollectionOf(items, fmt) - - return map[string]spec.Parameter{ - "ID": *idParam, - "Name": *nameParam, - "RequestID": *requestIDParam, - "Friend": *friendParam, - "Tags": *tagsParam, - } -} - -func TestRequestBindingDefaultValue(t *testing.T) { - confirmed := true - name := "thomas" - friend := map[string]interface{}{"name": "toby", "age": float64(32)} - id, age, score, factor := int64(7575), int32(348), float32(5.309), float64(37.403) - requestID := 19394858 - tags := []string{"one", "two", "three"} - dt1 := time.Date(2014, 8, 9, 0, 0, 0, 0, time.UTC) - planned := strfmt.Date(dt1) - dt2 := time.Date(2014, 10, 12, 8, 5, 5, 0, time.UTC) - delivered := strfmt.DateTime(dt2) - uri, _ := url.Parse("http://localhost:8002/hello") - defaults := map[string]interface{}{ - "id": id, - "age": age, - "score": score, - "factor": factor, - "name": name, - "friend": friend, - "X-Request-Id": requestID, - "tags": tags, - "confirmed": confirmed, - "planned": planned, - "delivered": delivered, - "picture": []byte("hello"), - } - op2 := parametersForAllTypes("") - op3 := make(map[string]spec.Parameter) - for k, p := range op2 { - p.Default = defaults[p.Name] - op3[k] = p - } - - req, _ := http.NewRequest("POST", uri.String(), bytes.NewBuffer(nil)) - req.Header.Set("Content-Type", "application/json") - binder := newUntypedRequestBinder(op3, new(spec.Swagger), strfmt.Default) - - data := make(map[string]interface{}) - err := binder.Bind(req, RouteParams(nil), runtime.JSONConsumer(), &data) - assert.NoError(t, err) - assert.Equal(t, defaults["id"], data["id"]) - assert.Equal(t, name, data["name"]) - assert.Equal(t, friend, data["friend"]) - assert.EqualValues(t, requestID, data["X-Request-Id"]) - assert.Equal(t, tags, data["tags"]) - assert.Equal(t, planned, data["planned"]) - assert.Equal(t, delivered, data["delivered"]) - assert.Equal(t, confirmed, data["confirmed"]) - assert.Equal(t, age, data["age"]) - assert.Equal(t, factor, data["factor"]) - assert.Equal(t, score, data["score"]) - assert.Equal(t, "hello", string(data["picture"].(strfmt.Base64))) -} - -func TestRequestBindingForInvalid(t *testing.T) { - - invalidParam := spec.QueryParam("some") - - op1 := map[string]spec.Parameter{"Some": *invalidParam} - - binder := newUntypedRequestBinder(op1, new(spec.Swagger), strfmt.Default) - req, _ := http.NewRequest("GET", "http://localhost:8002/hello?name=the-name", nil) - - err := binder.Bind(req, nil, new(stubConsumer), new(jsonRequestParams)) - assert.Error(t, err) - - op2 := parametersForJSONRequestParams("") - binder = newUntypedRequestBinder(op2, new(spec.Swagger), strfmt.Default) - - req, _ = http.NewRequest("POST", "http://localhost:8002/hello/1?name=the-name", bytes.NewBuffer([]byte(`{"name":"toby","age":32}`))) - req.Header.Set("Content-Type", "application(") - data := jsonRequestParams{} - err = binder.Bind(req, RouteParams([]RouteParam{{"id", "1"}}), runtime.JSONConsumer(), &data) - assert.Error(t, err) - - req, _ = http.NewRequest("POST", "http://localhost:8002/hello/1?name=the-name", bytes.NewBuffer([]byte(`{]`))) - req.Header.Set("Content-Type", "application/json") - data = jsonRequestParams{} - err = binder.Bind(req, RouteParams([]RouteParam{{"id", "1"}}), runtime.JSONConsumer(), &data) - assert.Error(t, err) - - invalidMultiParam := spec.HeaderParam("tags").CollectionOf(new(spec.Items), "multi") - op3 := map[string]spec.Parameter{"Tags": *invalidMultiParam} - binder = newUntypedRequestBinder(op3, new(spec.Swagger), strfmt.Default) - - req, _ = http.NewRequest("POST", "http://localhost:8002/hello/1?name=the-name", bytes.NewBuffer([]byte(`{}`))) - req.Header.Set("Content-Type", "application/json") - data = jsonRequestParams{} - err = binder.Bind(req, RouteParams([]RouteParam{{"id", "1"}}), runtime.JSONConsumer(), &data) - assert.Error(t, err) - - invalidMultiParam = spec.PathParam("").CollectionOf(new(spec.Items), "multi") - - op4 := map[string]spec.Parameter{"Tags": *invalidMultiParam} - binder = newUntypedRequestBinder(op4, new(spec.Swagger), strfmt.Default) - - req, _ = http.NewRequest("POST", "http://localhost:8002/hello/1?name=the-name", bytes.NewBuffer([]byte(`{}`))) - req.Header.Set("Content-Type", "application/json") - data = jsonRequestParams{} - err = binder.Bind(req, RouteParams([]RouteParam{{"id", "1"}}), runtime.JSONConsumer(), &data) - assert.Error(t, err) - - invalidInParam := spec.HeaderParam("tags").Typed("string", "") - invalidInParam.In = "invalid" - op5 := map[string]spec.Parameter{"Tags": *invalidInParam} - binder = newUntypedRequestBinder(op5, new(spec.Swagger), strfmt.Default) - - req, _ = http.NewRequest("POST", "http://localhost:8002/hello/1?name=the-name", bytes.NewBuffer([]byte(`{}`))) - req.Header.Set("Content-Type", "application/json") - data = jsonRequestParams{} - err = binder.Bind(req, RouteParams([]RouteParam{{"id", "1"}}), runtime.JSONConsumer(), &data) - assert.Error(t, err) -} - -func TestRequestBindingForValid(t *testing.T) { - - for _, fmt := range []string{"csv", "pipes", "tsv", "ssv", "multi"} { - op1 := parametersForJSONRequestParams(fmt) - - binder := newUntypedRequestBinder(op1, new(spec.Swagger), strfmt.Default) - - lval := []string{"one", "two", "three"} - var queryString string - switch fmt { - case "multi": - queryString = strings.Join(lval, "&tags=") - case "ssv": - queryString = strings.Join(lval, " ") - case "pipes": - queryString = strings.Join(lval, "|") - case "tsv": - queryString = strings.Join(lval, "\t") - default: - queryString = strings.Join(lval, ",") - } - - urlStr := "http://localhost:8002/hello/1?name=the-name&tags=" + queryString - - req, _ := http.NewRequest("POST", urlStr, bytes.NewBuffer([]byte(`{"name":"toby","age":32}`))) - req.Header.Set("Content-Type", "application/json;charset=utf-8") - req.Header.Set("X-Request-Id", "1325959595") - - data := jsonRequestParams{} - err := binder.Bind(req, RouteParams([]RouteParam{{"id", "1"}}), runtime.JSONConsumer(), &data) - - expected := jsonRequestParams{ - ID: 1, - Name: "the-name", - Friend: friend{"toby", 32}, - RequestID: 1325959595, - Tags: []string{"one", "two", "three"}, - } - assert.NoError(t, err) - assert.Equal(t, expected, data) - } - - op1 := parametersForJSONRequestParams("") - - binder := newUntypedRequestBinder(op1, new(spec.Swagger), strfmt.Default) - urlStr := "http://localhost:8002/hello/1?name=the-name&tags=one,two,three" - req, _ := http.NewRequest("POST", urlStr, bytes.NewBuffer([]byte(`{"name":"toby","age":32}`))) - req.Header.Set("Content-Type", "application/json;charset=utf-8") - req.Header.Set("X-Request-Id", "1325959595") - - data2 := jsonRequestPtr{} - err := binder.Bind(req, []RouteParam{{"id", "1"}}, runtime.JSONConsumer(), &data2) - - expected2 := jsonRequestPtr{ - Friend: &friend{"toby", 32}, - Tags: []string{"one", "two", "three"}, - } - assert.NoError(t, err) - if data2.Friend == nil { - t.Fatal("friend is nil") - } - assert.Equal(t, *expected2.Friend, *data2.Friend) - assert.Equal(t, expected2.Tags, data2.Tags) - - req, _ = http.NewRequest("POST", urlStr, bytes.NewBuffer([]byte(`[{"name":"toby","age":32}]`))) - req.Header.Set("Content-Type", "application/json;charset=utf-8") - req.Header.Set("X-Request-Id", "1325959595") - op2 := parametersForJSONRequestSliceParams("") - binder = newUntypedRequestBinder(op2, new(spec.Swagger), strfmt.Default) - data3 := jsonRequestSlice{} - err = binder.Bind(req, []RouteParam{{"id", "1"}}, runtime.JSONConsumer(), &data3) - - expected3 := jsonRequestSlice{ - Friend: []friend{{"toby", 32}}, - Tags: []string{"one", "two", "three"}, - } - assert.NoError(t, err) - assert.Equal(t, expected3.Friend, data3.Friend) - assert.Equal(t, expected3.Tags, data3.Tags) -} - -type formRequest struct { - Name string - Age int -} - -func parametersForFormUpload() map[string]spec.Parameter { - nameParam := spec.FormDataParam("name").Typed("string", "") - - ageParam := spec.FormDataParam("age").Typed("integer", "int32") - - return map[string]spec.Parameter{"Name": *nameParam, "Age": *ageParam} -} - -func TestFormUpload(t *testing.T) { - params := parametersForFormUpload() - binder := newUntypedRequestBinder(params, new(spec.Swagger), strfmt.Default) - - urlStr := "http://localhost:8002/hello" - req, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(`name=the-name&age=32`)) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - data := formRequest{} - res := binder.Bind(req, nil, runtime.JSONConsumer(), &data) - assert.NoError(t, res) - assert.Equal(t, "the-name", data.Name) - assert.Equal(t, 32, data.Age) - - req, _ = http.NewRequest("POST", urlStr, bytes.NewBufferString(`name=%3&age=32`)) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - data = formRequest{} - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) -} - -type fileRequest struct { - Name string // body - File runtime.File // upload -} - -func paramsForFileUpload() *untypedRequestBinder { - nameParam := spec.FormDataParam("name").Typed("string", "") - - fileParam := spec.FileParam("file") - - params := map[string]spec.Parameter{"Name": *nameParam, "File": *fileParam} - return newUntypedRequestBinder(params, new(spec.Swagger), strfmt.Default) -} - -func TestBindingFileUpload(t *testing.T) { - binder := paramsForFileUpload() - - body := bytes.NewBuffer(nil) - writer := multipart.NewWriter(body) - part, err := writer.CreateFormFile("file", "plain-jane.txt") - assert.NoError(t, err) - - _, _ = part.Write([]byte("the file contents")) - _ = writer.WriteField("name", "the-name") - assert.NoError(t, writer.Close()) - - urlStr := "http://localhost:8002/hello" - req, _ := http.NewRequest("POST", urlStr, body) - req.Header.Set("Content-Type", writer.FormDataContentType()) - - data := fileRequest{} - assert.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) - assert.Equal(t, "the-name", data.Name) - assert.NotNil(t, data.File) - assert.NotNil(t, data.File.Header) - assert.Equal(t, "plain-jane.txt", data.File.Header.Filename) - - bb, err := ioutil.ReadAll(data.File.Data) - assert.NoError(t, err) - assert.Equal(t, []byte("the file contents"), bb) - - req, _ = http.NewRequest("POST", urlStr, body) - req.Header.Set("Content-Type", "application/json") - data = fileRequest{} - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) - - req, _ = http.NewRequest("POST", urlStr, body) - req.Header.Set("Content-Type", "application(") - data = fileRequest{} - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) - - body = bytes.NewBuffer(nil) - writer = multipart.NewWriter(body) - part, err = writer.CreateFormFile("bad-name", "plain-jane.txt") - assert.NoError(t, err) - - _, _ = part.Write([]byte("the file contents")) - _ = writer.WriteField("name", "the-name") - assert.NoError(t, writer.Close()) - req, _ = http.NewRequest("POST", urlStr, body) - req.Header.Set("Content-Type", writer.FormDataContentType()) - - data = fileRequest{} - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) - - req, _ = http.NewRequest("POST", urlStr, body) - req.Header.Set("Content-Type", writer.FormDataContentType()) - _, _ = req.MultipartReader() - - data = fileRequest{} - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) - -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/route_param_test.go b/vendor/github.com/go-openapi/runtime/middleware/route_param_test.go deleted file mode 100644 index 78c92b654..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/route_param_test.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestRouteParams(t *testing.T) { - coll1 := RouteParams([]RouteParam{ - {"blah", "foo"}, - {"abc", "bar"}, - {"ccc", "efg"}, - }) - - v := coll1.Get("blah") - assert.Equal(t, v, "foo") - v2 := coll1.Get("abc") - assert.Equal(t, v2, "bar") - v3 := coll1.Get("ccc") - assert.Equal(t, v3, "efg") - v4 := coll1.Get("ydkdk") - assert.Empty(t, v4) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/router.go b/vendor/github.com/go-openapi/runtime/middleware/router.go deleted file mode 100644 index a381e7306..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/router.go +++ /dev/null @@ -1,310 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "fmt" - "net/http" - fpath "path" - "regexp" - "strings" - - "github.com/go-openapi/analysis" - "github.com/go-openapi/errors" - "github.com/go-openapi/loads" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware/denco" - "github.com/go-openapi/spec" - "github.com/go-openapi/strfmt" -) - -// RouteParam is a object to capture route params in a framework agnostic way. -// implementations of the muxer should use these route params to communicate with the -// swagger framework -type RouteParam struct { - Name string - Value string -} - -// RouteParams the collection of route params -type RouteParams []RouteParam - -// Get gets the value for the route param for the specified key -func (r RouteParams) Get(name string) string { - vv, _, _ := r.GetOK(name) - if len(vv) > 0 { - return vv[len(vv)-1] - } - return "" -} - -// GetOK gets the value but also returns booleans to indicate if a key or value -// is present. This aids in validation and satisfies an interface in use there -// -// The returned values are: data, has key, has value -func (r RouteParams) GetOK(name string) ([]string, bool, bool) { - for _, p := range r { - if p.Name == name { - return []string{p.Value}, true, p.Value != "" - } - } - return nil, false, false -} - -// NewRouter creates a new context aware router middleware -func NewRouter(ctx *Context, next http.Handler) http.Handler { - if ctx.router == nil { - ctx.router = DefaultRouter(ctx.spec, ctx.api) - } - - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - if _, rCtx, ok := ctx.RouteInfo(r); ok { - next.ServeHTTP(rw, rCtx) - return - } - - // Not found, check if it exists in the other methods first - if others := ctx.AllowedMethods(r); len(others) > 0 { - ctx.Respond(rw, r, ctx.analyzer.RequiredProduces(), nil, errors.MethodNotAllowed(r.Method, others)) - return - } - - ctx.Respond(rw, r, ctx.analyzer.RequiredProduces(), nil, errors.NotFound("path %s was not found", r.URL.EscapedPath())) - }) -} - -// RoutableAPI represents an interface for things that can serve -// as a provider of implementations for the swagger router -type RoutableAPI interface { - HandlerFor(string, string) (http.Handler, bool) - ServeErrorFor(string) func(http.ResponseWriter, *http.Request, error) - ConsumersFor([]string) map[string]runtime.Consumer - ProducersFor([]string) map[string]runtime.Producer - AuthenticatorsFor(map[string]spec.SecurityScheme) map[string]runtime.Authenticator - Authorizer() runtime.Authorizer - Formats() strfmt.Registry - DefaultProduces() string - DefaultConsumes() string -} - -// Router represents a swagger aware router -type Router interface { - Lookup(method, path string) (*MatchedRoute, bool) - OtherMethods(method, path string) []string -} - -type defaultRouteBuilder struct { - spec *loads.Document - analyzer *analysis.Spec - api RoutableAPI - records map[string][]denco.Record -} - -type defaultRouter struct { - spec *loads.Document - routers map[string]*denco.Router -} - -func newDefaultRouteBuilder(spec *loads.Document, api RoutableAPI) *defaultRouteBuilder { - return &defaultRouteBuilder{ - spec: spec, - analyzer: analysis.New(spec.Spec()), - api: api, - records: make(map[string][]denco.Record), - } -} - -// DefaultRouter creates a default implemenation of the router -func DefaultRouter(spec *loads.Document, api RoutableAPI) Router { - builder := newDefaultRouteBuilder(spec, api) - if spec != nil { - for method, paths := range builder.analyzer.Operations() { - for path, operation := range paths { - fp := fpath.Join(spec.BasePath(), path) - debugLog("adding route %s %s %q", method, fp, operation.ID) - builder.AddRoute(method, fp, operation) - } - } - } - return builder.Build() -} - -type routeEntry struct { - PathPattern string - BasePath string - Operation *spec.Operation - Consumes []string - Consumers map[string]runtime.Consumer - Produces []string - Producers map[string]runtime.Producer - Parameters map[string]spec.Parameter - Handler http.Handler - Formats strfmt.Registry - Binder *untypedRequestBinder - Authenticators map[string]runtime.Authenticator - Authorizer runtime.Authorizer - Scopes map[string][]string -} - -// MatchedRoute represents the route that was matched in this request -type MatchedRoute struct { - routeEntry - Params RouteParams - Consumer runtime.Consumer - Producer runtime.Producer -} - -func (d *defaultRouter) Lookup(method, path string) (*MatchedRoute, bool) { - mth := strings.ToUpper(method) - debugLog("looking up route for %s %s", method, path) - if Debug { - if len(d.routers) == 0 { - debugLog("there are no known routers") - } - for meth := range d.routers { - debugLog("got a router for %s", meth) - } - } - if router, ok := d.routers[mth]; ok { - if m, rp, ok := router.Lookup(fpath.Clean(path)); ok && m != nil { - if entry, ok := m.(*routeEntry); ok { - debugLog("found a route for %s %s with %d parameters", method, path, len(entry.Parameters)) - var params RouteParams - for _, p := range rp { - v, err := pathUnescape(p.Value) - if err != nil { - debugLog("failed to escape %q: %v", p.Value, err) - v = p.Value - } - // a workaround to handle fragment/composig parameters until they are supported in denco router - // check if this parameter is a fragment within a path segment - if xpos := strings.Index(entry.PathPattern, fmt.Sprintf("{%s}", p.Name)) + len(p.Name) + 2; - xpos < len(entry.PathPattern) && entry.PathPattern[xpos] != '/' { - // extract fragment parameters - ep := strings.Split(entry.PathPattern[xpos:], "/")[0] - pnames, pvalues := decodeCompositParams(p.Name, v, ep, nil, nil) - for i, pname := range pnames { - params = append(params, RouteParam{Name: pname, Value: pvalues[i]}) - } - } else { - // use the parameter directly - params = append(params, RouteParam{Name: p.Name, Value: v}) - } - } - return &MatchedRoute{routeEntry: *entry, Params: params}, true - } - } else { - debugLog("couldn't find a route by path for %s %s", method, path) - } - } else { - debugLog("couldn't find a route by method for %s %s", method, path) - } - return nil, false -} - -func (d *defaultRouter) OtherMethods(method, path string) []string { - mn := strings.ToUpper(method) - var methods []string - for k, v := range d.routers { - if k != mn { - if _, _, ok := v.Lookup(fpath.Clean(path)); ok { - methods = append(methods, k) - continue - } - } - } - return methods -} - -// convert swagger parameters per path segment into a denco parameter as multiple parameters per segment are not supported in denco -var pathConverter = regexp.MustCompile(`{(.+?)}([^/]*)`) - -func decodeCompositParams(name string, value string, pattern string, names []string, values []string) ([]string, []string){ - pleft := strings.Index(pattern, "{") - names = append(names, name) - if pleft < 0 { - if strings.HasSuffix(value, pattern) { - values = append(values, value[:len(value)-len(pattern)]) - } else { - values = append(values, "") - } - } else { - toskip := pattern[:pleft] - pright := strings.Index(pattern, "}") - vright := strings.Index(value, toskip) - if vright >= 0 { - values = append(values, value[:vright]) - } else { - values = append(values, "") - value = "" - } - return decodeCompositParams(pattern[pleft+1:pright], value[vright+len(toskip):], pattern[pright+1:], names, values) - } - return names, values -} - -func (d *defaultRouteBuilder) AddRoute(method, path string, operation *spec.Operation) { - mn := strings.ToUpper(method) - - bp := fpath.Clean(d.spec.BasePath()) - if len(bp) > 0 && bp[len(bp)-1] == '/' { - bp = bp[:len(bp)-1] - } - - debugLog("operation: %#v", *operation) - if handler, ok := d.api.HandlerFor(method, strings.TrimPrefix(path, bp)); ok { - consumes := d.analyzer.ConsumesFor(operation) - produces := d.analyzer.ProducesFor(operation) - parameters := d.analyzer.ParamsFor(method, strings.TrimPrefix(path, bp)) - definitions := d.analyzer.SecurityDefinitionsFor(operation) - requirements := d.analyzer.SecurityRequirementsFor(operation) - scopes := make(map[string][]string, len(requirements)) - for _, v := range requirements { - scopes[v.Name] = v.Scopes - } - - - record := denco.NewRecord(pathConverter.ReplaceAllString(path, ":$1"), &routeEntry{ - BasePath: bp, - PathPattern: path, - Operation: operation, - Handler: handler, - Consumes: consumes, - Produces: produces, - Consumers: d.api.ConsumersFor(normalizeOffers(consumes)), - Producers: d.api.ProducersFor(normalizeOffers(produces)), - Parameters: parameters, - Formats: d.api.Formats(), - Binder: newUntypedRequestBinder(parameters, d.spec.Spec(), d.api.Formats()), - Authenticators: d.api.AuthenticatorsFor(definitions), - Authorizer: d.api.Authorizer(), - Scopes: scopes, - }) - d.records[mn] = append(d.records[mn], record) - } -} - -func (d *defaultRouteBuilder) Build() *defaultRouter { - routers := make(map[string]*denco.Router) - for method, records := range d.records { - router := denco.New() - _ = router.Build(records) - routers[method] = router - } - return &defaultRouter{ - spec: d.spec, - routers: routers, - } -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/router_test.go b/vendor/github.com/go-openapi/runtime/middleware/router_test.go deleted file mode 100644 index 931429c90..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/router_test.go +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "net/http" - "net/http/httptest" - "sort" - "strings" - "testing" - - "github.com/go-openapi/analysis" - "github.com/go-openapi/loads" - "github.com/go-openapi/runtime/internal/testing/petstore" - "github.com/go-openapi/runtime/middleware/untyped" - "github.com/stretchr/testify/assert" -) - -func terminator(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusOK) -} - -func TestRouterMiddleware(t *testing.T) { - spec, api := petstore.NewAPI(t) - context := NewContext(spec, api, nil) - mw := NewRouter(context, http.HandlerFunc(terminator)) - - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/api/pets", nil) - - mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("DELETE", "/api/pets", nil) - - mw.ServeHTTP(recorder, request) - assert.Equal(t, http.StatusMethodNotAllowed, recorder.Code) - - methods := strings.Split(recorder.Header().Get("Allow"), ",") - sort.Sort(sort.StringSlice(methods)) - assert.Equal(t, "GET,POST", strings.Join(methods, ",")) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/nopets", nil) - - mw.ServeHTTP(recorder, request) - assert.Equal(t, http.StatusNotFound, recorder.Code) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/pets", nil) - - mw.ServeHTTP(recorder, request) - assert.Equal(t, http.StatusNotFound, recorder.Code) - - spec, api = petstore.NewRootAPI(t) - context = NewContext(spec, api, nil) - mw = NewRouter(context, http.HandlerFunc(terminator)) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/pets", nil) - - mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("DELETE", "/pets", nil) - - mw.ServeHTTP(recorder, request) - assert.Equal(t, http.StatusMethodNotAllowed, recorder.Code) - - methods = strings.Split(recorder.Header().Get("Allow"), ",") - sort.Sort(sort.StringSlice(methods)) - assert.Equal(t, "GET,POST", strings.Join(methods, ",")) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/nopets", nil) - - mw.ServeHTTP(recorder, request) - assert.Equal(t, http.StatusNotFound, recorder.Code) - -} - -func TestRouterBuilder(t *testing.T) { - spec, api := petstore.NewAPI(t) - analyzed := analysis.New(spec.Spec()) - - assert.Len(t, analyzed.RequiredConsumes(), 3) - assert.Len(t, analyzed.RequiredProduces(), 5) - assert.Len(t, analyzed.OperationIDs(), 4) - - // context := NewContext(spec, api) - builder := petAPIRouterBuilder(spec, api, analyzed) - getRecords := builder.records["GET"] - postRecords := builder.records["POST"] - deleteRecords := builder.records["DELETE"] - - assert.Len(t, getRecords, 2) - assert.Len(t, postRecords, 1) - assert.Len(t, deleteRecords, 1) - - assert.Empty(t, builder.records["PATCH"]) - assert.Empty(t, builder.records["OPTIONS"]) - assert.Empty(t, builder.records["HEAD"]) - assert.Empty(t, builder.records["PUT"]) - - rec := postRecords[0] - assert.Equal(t, rec.Key, "/pets") - val := rec.Value.(*routeEntry) - assert.Len(t, val.Consumers, 1) - assert.Len(t, val.Producers, 1) - assert.Len(t, val.Consumes, 1) - assert.Len(t, val.Produces, 1) - - assert.Len(t, val.Parameters, 1) - - recG := getRecords[0] - assert.Equal(t, recG.Key, "/pets") - valG := recG.Value.(*routeEntry) - assert.Len(t, valG.Consumers, 2) - assert.Len(t, valG.Producers, 4) - assert.Len(t, valG.Consumes, 2) - assert.Len(t, valG.Produces, 4) - - assert.Len(t, valG.Parameters, 2) -} - -func TestRouterCanonicalBasePath(t *testing.T) { - spec, api := petstore.NewAPI(t) - spec.Spec().BasePath = "/api///" - context := NewContext(spec, api, nil) - mw := NewRouter(context, http.HandlerFunc(terminator)) - - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/api/pets", nil) - - mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) -} - -func TestRouter_EscapedPath(t *testing.T) { - spec, api := petstore.NewAPI(t) - spec.Spec().BasePath = "/api/" - context := NewContext(spec, api, nil) - mw := NewRouter(context, http.HandlerFunc(terminator)) - - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/api/pets/123", nil) - - mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/api/pets/abc%2Fdef", nil) - - mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) - ri, _, _ := context.RouteInfo(request) - if assert.NotNil(t, ri) { - if assert.NotNil(t, ri.Params) { - assert.Equal(t, "abc/def", ri.Params.Get("id")) - } - } -} - -func TestRouterStruct(t *testing.T) { - spec, api := petstore.NewAPI(t) - router := DefaultRouter(spec, newRoutableUntypedAPI(spec, api, new(Context))) - - methods := router.OtherMethods("post", "/api/pets/{id}") - assert.Len(t, methods, 2) - - entry, ok := router.Lookup("delete", "/api/pets/{id}") - assert.True(t, ok) - assert.NotNil(t, entry) - assert.Len(t, entry.Params, 1) - assert.Equal(t, "id", entry.Params[0].Name) - - _, ok = router.Lookup("delete", "/pets") - assert.False(t, ok) - - _, ok = router.Lookup("post", "/no-pets") - assert.False(t, ok) -} - -func petAPIRouterBuilder(spec *loads.Document, api *untyped.API, analyzed *analysis.Spec) *defaultRouteBuilder { - builder := newDefaultRouteBuilder(spec, newRoutableUntypedAPI(spec, api, new(Context))) - builder.AddRoute("GET", "/pets", analyzed.AllPaths()["/pets"].Get) - builder.AddRoute("POST", "/pets", analyzed.AllPaths()["/pets"].Post) - builder.AddRoute("DELETE", "/pets/{id}", analyzed.AllPaths()["/pets/{id}"].Delete) - builder.AddRoute("GET", "/pets/{id}", analyzed.AllPaths()["/pets/{id}"].Get) - - return builder -} - -func TestPathConverter(t *testing.T) { - cases := []struct { - swagger string - denco string - }{ - {"/", "/"}, - {"/something", "/something"}, - {"/{id}", "/:id"}, - {"/{id}/something/{anotherId}", "/:id/something/:anotherId"}, - {"/{petid}", "/:petid"}, - {"/{pet_id}", "/:pet_id"}, - {"/{petId}", "/:petId"}, - {"/{pet-id}", "/:pet-id"}, - // composit parameters tests - {"/p_{pet_id}", "/p_:pet_id"}, - {"/p_{petId}.{petSubId}", "/p_:petId"}, - } - - for _, tc := range cases { - actual := pathConverter.ReplaceAllString(tc.swagger, ":$1") - assert.Equal(t, tc.denco, actual, "expected swagger path %s to match %s but got %s", tc.swagger, tc.denco, actual) - } -} - -func TestExtractCompositParameters(t *testing.T) { - // name is the composite parameter's name, value is the value of this composit parameter, pattern is the pattern to be matched - cases := []struct { - name string - value string - pattern string - names []string - values []string - }{ - {name: "fragment", value: "gie", pattern: "e", names: []string{"fragment"}, values: []string{"gi"}}, - {name: "fragment", value: "t.simpson", pattern: ".{subfragment}", names: []string{"fragment", "subfragment"}, values: []string{"t", "simpson"}}, - } - for _, tc := range cases { - names, values := decodeCompositParams(tc.name, tc.value, tc.pattern, nil, nil) - assert.EqualValues(t, tc.names, names) - assert.EqualValues(t, tc.values, values) - } -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/security.go b/vendor/github.com/go-openapi/runtime/middleware/security.go deleted file mode 100644 index 399058310..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/security.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import "net/http" - -func newSecureAPI(ctx *Context, next http.Handler) http.Handler { - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := ctx.RouteInfo(r) - if rCtx != nil { - r = rCtx - } - if route != nil && len(route.Authenticators) == 0 { - next.ServeHTTP(rw, r) - return - } - - _, rCtx, err := ctx.Authorize(r, route) - if err != nil { - ctx.Respond(rw, r, route.Produces, route, err) - return - } - r = rCtx - - next.ServeHTTP(rw, r) - }) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/security_test.go b/vendor/github.com/go-openapi/runtime/middleware/security_test.go deleted file mode 100644 index 7c283fa70..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/security_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/go-openapi/runtime/internal/testing/petstore" - "github.com/stretchr/testify/assert" -) - -func TestSecurityMiddleware(t *testing.T) { - spec, api := petstore.NewAPI(t) - context := NewContext(spec, api, nil) - context.router = DefaultRouter(spec, context.api) - mw := newSecureAPI(context, http.HandlerFunc(terminator)) - - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/api/pets", nil) - - mw.ServeHTTP(recorder, request) - assert.Equal(t, 401, recorder.Code) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/api/pets", nil) - request.SetBasicAuth("admin", "wrong") - - mw.ServeHTTP(recorder, request) - assert.Equal(t, 401, recorder.Code) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "/api/pets", nil) - request.SetBasicAuth("admin", "admin") - - mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("GET", "//apipets/1", nil) - - mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) - -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/spec.go b/vendor/github.com/go-openapi/runtime/middleware/spec.go deleted file mode 100644 index 72bc5643a..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/spec.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "net/http" - "path" -) - -// Spec creates a middleware to serve a swagger spec. -// This allows for altering the spec before starting the http listener. -// This can be useful if you want to serve the swagger spec from another path than /swagger.json -// -func Spec(basePath string, b []byte, next http.Handler) http.Handler { - if basePath == "" { - basePath = "/" - } - pth := path.Join(basePath, "swagger.json") - - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - if r.URL.Path == pth { - rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(http.StatusOK) - _, _ = rw.Write(b) - return - } - - if next == nil { - rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(http.StatusNotFound) - return - } - next.ServeHTTP(rw, r) - }) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/spec_test.go b/vendor/github.com/go-openapi/runtime/middleware/spec_test.go deleted file mode 100644 index 822a7a6ad..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/spec_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "net/http" - "net/http/httptest" - "testing" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/internal/testing/petstore" - "github.com/stretchr/testify/assert" -) - -func TestServeSpecMiddleware(t *testing.T) { - spec, api := petstore.NewAPI(t) - ctx := NewContext(spec, api, nil) - - handler := Spec("", ctx.spec.Raw(), nil) - // serves spec - request, _ := http.NewRequest("GET", "/swagger.json", nil) - request.Header.Add(runtime.HeaderContentType, runtime.JSONMime) - recorder := httptest.NewRecorder() - handler.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) - - // returns 404 when no next handler - request, _ = http.NewRequest("GET", "/api/pets", nil) - request.Header.Add(runtime.HeaderContentType, runtime.JSONMime) - recorder = httptest.NewRecorder() - handler.ServeHTTP(recorder, request) - assert.Equal(t, 404, recorder.Code) - - // forwards to next handler for other url - handler = Spec("", ctx.spec.Raw(), http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - rw.WriteHeader(http.StatusOK) - })) - request, _ = http.NewRequest("GET", "/api/pets", nil) - request.Header.Add(runtime.HeaderContentType, runtime.JSONMime) - recorder = httptest.NewRecorder() - handler.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code) - -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/string_conversion_test.go b/vendor/github.com/go-openapi/runtime/middleware/string_conversion_test.go deleted file mode 100644 index c0ee01614..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/string_conversion_test.go +++ /dev/null @@ -1,301 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "errors" - "reflect" - "strings" - "testing" - "time" - - "github.com/go-openapi/spec" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - "github.com/stretchr/testify/assert" -) - -var evaluatesAsTrue = []string{"true", "1", "yes", "ok", "y", "on", "selected", "checked", "t", "enabled"} - -type unmarshallerSlice []string - -func (u *unmarshallerSlice) UnmarshalText(data []byte) error { - if len(data) == 0 { - return errors.New("an error") - } - *u = strings.Split(string(data), ",") - return nil -} - -type SomeOperationParams struct { - Name string - ID int64 - Confirmed bool - Age int - Visits int32 - Count int16 - Seq int8 - UID uint64 - UAge uint - UVisits uint32 - UCount uint16 - USeq uint8 - Score float32 - Rate float64 - Timestamp strfmt.DateTime - Birthdate strfmt.Date - LastFailure *strfmt.DateTime - Unsupported struct{} - Tags []string - Prefs []int32 - Categories unmarshallerSlice -} - -func FloatParamTest(t *testing.T, fName, pName, format string, val reflect.Value, defVal, expectedDef interface{}, actual func() interface{}) { - fld := val.FieldByName(pName) - binder := &untypedParamBinder{ - parameter: spec.QueryParam(pName).Typed("number", "double").WithDefault(defVal), - Name: pName, - } - - err := binder.setFieldValue(fld, defVal, "5", true) - assert.NoError(t, err) - assert.EqualValues(t, 5, actual()) - - err = binder.setFieldValue(fld, defVal, "", true) - assert.NoError(t, err) - assert.EqualValues(t, expectedDef, actual()) - - err = binder.setFieldValue(fld, defVal, "yada", true) - assert.Error(t, err) -} - -func IntParamTest(t *testing.T, pName string, val reflect.Value, defVal, expectedDef interface{}, actual func() interface{}) { - fld := val.FieldByName(pName) - - binder := &untypedParamBinder{ - parameter: spec.QueryParam(pName).Typed("integer", "int64").WithDefault(defVal), - Name: pName, - } - err := binder.setFieldValue(fld, defVal, "5", true) - assert.NoError(t, err) - assert.EqualValues(t, 5, actual()) - - err = binder.setFieldValue(fld, defVal, "", true) - assert.NoError(t, err) - assert.EqualValues(t, expectedDef, actual()) - - err = binder.setFieldValue(fld, defVal, "yada", true) - assert.Error(t, err) -} - -func TestParamBinding(t *testing.T) { - - actual := new(SomeOperationParams) - val := reflect.ValueOf(actual).Elem() - pName := "Name" - fld := val.FieldByName(pName) - - binder := &untypedParamBinder{ - parameter: spec.QueryParam(pName).Typed("string", "").WithDefault("some-name"), - Name: pName, - } - - err := binder.setFieldValue(fld, "some-name", "the name value", true) - assert.NoError(t, err) - assert.Equal(t, "the name value", actual.Name) - - err = binder.setFieldValue(fld, "some-name", "", true) - assert.NoError(t, err) - assert.Equal(t, "some-name", actual.Name) - - IntParamTest(t, "ID", val, 1, 1, func() interface{} { return actual.ID }) - IntParamTest(t, "ID", val, nil, 0, func() interface{} { return actual.ID }) - IntParamTest(t, "Age", val, 1, 1, func() interface{} { return actual.Age }) - IntParamTest(t, "Age", val, nil, 0, func() interface{} { return actual.Age }) - IntParamTest(t, "Visits", val, 1, 1, func() interface{} { return actual.Visits }) - IntParamTest(t, "Visits", val, nil, 0, func() interface{} { return actual.Visits }) - IntParamTest(t, "Count", val, 1, 1, func() interface{} { return actual.Count }) - IntParamTest(t, "Count", val, nil, 0, func() interface{} { return actual.Count }) - IntParamTest(t, "Seq", val, 1, 1, func() interface{} { return actual.Seq }) - IntParamTest(t, "Seq", val, nil, 0, func() interface{} { return actual.Seq }) - IntParamTest(t, "UID", val, uint64(1), 1, func() interface{} { return actual.UID }) - IntParamTest(t, "UID", val, uint64(0), 0, func() interface{} { return actual.UID }) - IntParamTest(t, "UAge", val, uint(1), 1, func() interface{} { return actual.UAge }) - IntParamTest(t, "UAge", val, nil, 0, func() interface{} { return actual.UAge }) - IntParamTest(t, "UVisits", val, uint32(1), 1, func() interface{} { return actual.UVisits }) - IntParamTest(t, "UVisits", val, nil, 0, func() interface{} { return actual.UVisits }) - IntParamTest(t, "UCount", val, uint16(1), 1, func() interface{} { return actual.UCount }) - IntParamTest(t, "UCount", val, nil, 0, func() interface{} { return actual.UCount }) - IntParamTest(t, "USeq", val, uint8(1), 1, func() interface{} { return actual.USeq }) - IntParamTest(t, "USeq", val, nil, 0, func() interface{} { return actual.USeq }) - - FloatParamTest(t, "score", "Score", "float", val, 1.0, 1, func() interface{} { return actual.Score }) - FloatParamTest(t, "score", "Score", "float", val, nil, 0, func() interface{} { return actual.Score }) - FloatParamTest(t, "rate", "Rate", "double", val, 1.0, 1, func() interface{} { return actual.Rate }) - FloatParamTest(t, "rate", "Rate", "double", val, nil, 0, func() interface{} { return actual.Rate }) - - pName = "Confirmed" - confirmedField := val.FieldByName(pName) - binder = &untypedParamBinder{ - parameter: spec.QueryParam(pName).Typed("boolean", "").WithDefault(true), - Name: pName, - } - - for _, tv := range evaluatesAsTrue { - err = binder.setFieldValue(confirmedField, true, tv, true) - assert.NoError(t, err) - assert.True(t, actual.Confirmed) - } - - err = binder.setFieldValue(confirmedField, true, "", true) - assert.NoError(t, err) - assert.True(t, actual.Confirmed) - - err = binder.setFieldValue(confirmedField, true, "0", true) - assert.NoError(t, err) - assert.False(t, actual.Confirmed) - - pName = "Timestamp" - timeField := val.FieldByName(pName) - dt := strfmt.DateTime(time.Date(2014, 3, 19, 2, 9, 0, 0, time.UTC)) - binder = &untypedParamBinder{ - parameter: spec.QueryParam(pName).Typed("string", "date-time").WithDefault(dt), - Name: pName, - } - exp := strfmt.DateTime(time.Date(2014, 5, 14, 2, 9, 0, 0, time.UTC)) - - err = binder.setFieldValue(timeField, dt, exp.String(), true) - assert.NoError(t, err) - assert.Equal(t, exp, actual.Timestamp) - - err = binder.setFieldValue(timeField, dt, "", true) - assert.NoError(t, err) - assert.Equal(t, dt, actual.Timestamp) - - err = binder.setFieldValue(timeField, dt, "yada", true) - assert.Error(t, err) - - ddt := strfmt.Date(time.Date(2014, 3, 19, 0, 0, 0, 0, time.UTC)) - pName = "Birthdate" - dateField := val.FieldByName(pName) - binder = &untypedParamBinder{ - parameter: spec.QueryParam(pName).Typed("string", "date").WithDefault(ddt), - Name: pName, - } - expd := strfmt.Date(time.Date(2014, 5, 14, 0, 0, 0, 0, time.UTC)) - - err = binder.setFieldValue(dateField, ddt, expd.String(), true) - assert.NoError(t, err) - assert.Equal(t, expd, actual.Birthdate) - - err = binder.setFieldValue(dateField, ddt, "", true) - assert.NoError(t, err) - assert.Equal(t, ddt, actual.Birthdate) - - err = binder.setFieldValue(dateField, ddt, "yada", true) - assert.Error(t, err) - - dt = strfmt.DateTime(time.Date(2014, 3, 19, 2, 9, 0, 0, time.UTC)) - fdt := &dt - pName = "LastFailure" - ftimeField := val.FieldByName(pName) - binder = &untypedParamBinder{ - parameter: spec.QueryParam(pName).Typed("string", "date").WithDefault(fdt), - Name: pName, - } - exp = strfmt.DateTime(time.Date(2014, 5, 14, 2, 9, 0, 0, time.UTC)) - fexp := &exp - - err = binder.setFieldValue(ftimeField, fdt, fexp.String(), true) - assert.NoError(t, err) - assert.Equal(t, fexp, actual.LastFailure) - - err = binder.setFieldValue(ftimeField, fdt, "", true) - assert.NoError(t, err) - assert.Equal(t, fdt, actual.LastFailure) - - err = binder.setFieldValue(ftimeField, fdt, "", true) - assert.NoError(t, err) - assert.Equal(t, fdt, actual.LastFailure) - - actual.LastFailure = nil - err = binder.setFieldValue(ftimeField, fdt, "yada", true) - assert.Error(t, err) - assert.Nil(t, actual.LastFailure) - - pName = "Unsupported" - unsupportedField := val.FieldByName(pName) - binder = &untypedParamBinder{ - parameter: spec.QueryParam(pName).Typed("string", ""), - Name: pName, - } - err = binder.setFieldValue(unsupportedField, nil, "", true) - assert.Error(t, err) -} - -func TestSliceConversion(t *testing.T) { - - actual := new(SomeOperationParams) - val := reflect.ValueOf(actual).Elem() - - // prefsField := val.FieldByName("Prefs") - // cData := "yada,2,3" - // _, _, err := readFormattedSliceFieldValue("Prefs", prefsField, cData, "csv", nil) - // assert.Error(t, err) - - sliced := []string{"some", "string", "values"} - seps := map[string]string{"ssv": " ", "tsv": "\t", "pipes": "|", "csv": ",", "": ","} - - tagsField := val.FieldByName("Tags") - for k, sep := range seps { - binder := &untypedParamBinder{ - Name: "Tags", - parameter: spec.QueryParam("tags").CollectionOf(stringItems, k), - } - - actual.Tags = nil - cData := strings.Join(sliced, sep) - tags, _, err := binder.readFormattedSliceFieldValue(cData, tagsField) - assert.NoError(t, err) - assert.Equal(t, sliced, tags) - cData = strings.Join(sliced, " "+sep+" ") - tags, _, err = binder.readFormattedSliceFieldValue(cData, tagsField) - assert.NoError(t, err) - assert.Equal(t, sliced, tags) - tags, _, err = binder.readFormattedSliceFieldValue("", tagsField) - assert.NoError(t, err) - assert.Empty(t, tags) - } - - assert.Nil(t, swag.SplitByFormat("yada", "multi")) - assert.Nil(t, swag.SplitByFormat("", "")) - - categoriesField := val.FieldByName("Categories") - binder := &untypedParamBinder{ - Name: "Categories", - parameter: spec.QueryParam("categories").CollectionOf(stringItems, "csv"), - } - cData := strings.Join(sliced, ",") - categories, custom, err := binder.readFormattedSliceFieldValue(cData, categoriesField) - assert.NoError(t, err) - assert.EqualValues(t, sliced, actual.Categories) - assert.True(t, custom) - assert.Empty(t, categories) - categories, custom, err = binder.readFormattedSliceFieldValue("", categoriesField) - assert.Error(t, err) - assert.True(t, custom) - assert.Empty(t, categories) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go b/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go deleted file mode 100644 index 3b0cd4e28..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/untyped/api.go +++ /dev/null @@ -1,286 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package untyped - -import ( - "fmt" - "net/http" - "sort" - "strings" - - "github.com/go-openapi/analysis" - "github.com/go-openapi/errors" - "github.com/go-openapi/loads" - "github.com/go-openapi/runtime" - "github.com/go-openapi/spec" - "github.com/go-openapi/strfmt" -) - -// NewAPI creates the default untyped API -func NewAPI(spec *loads.Document) *API { - var an *analysis.Spec - if spec != nil && spec.Spec() != nil { - an = analysis.New(spec.Spec()) - } - api := &API{ - spec: spec, - analyzer: an, - consumers: make(map[string]runtime.Consumer, 10), - producers: make(map[string]runtime.Producer, 10), - authenticators: make(map[string]runtime.Authenticator), - operations: make(map[string]map[string]runtime.OperationHandler), - ServeError: errors.ServeError, - Models: make(map[string]func() interface{}), - formats: strfmt.NewFormats(), - } - return api.WithJSONDefaults() -} - -// API represents an untyped mux for a swagger spec -type API struct { - spec *loads.Document - analyzer *analysis.Spec - DefaultProduces string - DefaultConsumes string - consumers map[string]runtime.Consumer - producers map[string]runtime.Producer - authenticators map[string]runtime.Authenticator - authorizer runtime.Authorizer - operations map[string]map[string]runtime.OperationHandler - ServeError func(http.ResponseWriter, *http.Request, error) - Models map[string]func() interface{} - formats strfmt.Registry -} - -// WithJSONDefaults loads the json defaults for this api -func (d *API) WithJSONDefaults() *API { - d.DefaultConsumes = runtime.JSONMime - d.DefaultProduces = runtime.JSONMime - d.consumers[runtime.JSONMime] = runtime.JSONConsumer() - d.producers[runtime.JSONMime] = runtime.JSONProducer() - return d -} - -// WithoutJSONDefaults clears the json defaults for this api -func (d *API) WithoutJSONDefaults() *API { - d.DefaultConsumes = "" - d.DefaultProduces = "" - delete(d.consumers, runtime.JSONMime) - delete(d.producers, runtime.JSONMime) - return d -} - -// Formats returns the registered string formats -func (d *API) Formats() strfmt.Registry { - if d.formats == nil { - d.formats = strfmt.NewFormats() - } - return d.formats -} - -// RegisterFormat registers a custom format validator -func (d *API) RegisterFormat(name string, format strfmt.Format, validator strfmt.Validator) { - if d.formats == nil { - d.formats = strfmt.NewFormats() - } - d.formats.Add(name, format, validator) -} - -// RegisterAuth registers an auth handler in this api -func (d *API) RegisterAuth(scheme string, handler runtime.Authenticator) { - if d.authenticators == nil { - d.authenticators = make(map[string]runtime.Authenticator) - } - d.authenticators[scheme] = handler -} - -// RegisterAuthorizer registers an authorizer handler in this api -func (d *API) RegisterAuthorizer(handler runtime.Authorizer) { - d.authorizer = handler -} - -// RegisterConsumer registers a consumer for a media type. -func (d *API) RegisterConsumer(mediaType string, handler runtime.Consumer) { - if d.consumers == nil { - d.consumers = make(map[string]runtime.Consumer, 10) - } - d.consumers[strings.ToLower(mediaType)] = handler -} - -// RegisterProducer registers a producer for a media type -func (d *API) RegisterProducer(mediaType string, handler runtime.Producer) { - if d.producers == nil { - d.producers = make(map[string]runtime.Producer, 10) - } - d.producers[strings.ToLower(mediaType)] = handler -} - -// RegisterOperation registers an operation handler for an operation name -func (d *API) RegisterOperation(method, path string, handler runtime.OperationHandler) { - if d.operations == nil { - d.operations = make(map[string]map[string]runtime.OperationHandler, 30) - } - um := strings.ToUpper(method) - if b, ok := d.operations[um]; !ok || b == nil { - d.operations[um] = make(map[string]runtime.OperationHandler) - } - d.operations[um][path] = handler -} - -// OperationHandlerFor returns the operation handler for the specified id if it can be found -func (d *API) OperationHandlerFor(method, path string) (runtime.OperationHandler, bool) { - if d.operations == nil { - return nil, false - } - if pi, ok := d.operations[strings.ToUpper(method)]; ok { - h, ok := pi[path] - return h, ok - } - return nil, false -} - -// ConsumersFor gets the consumers for the specified media types -func (d *API) ConsumersFor(mediaTypes []string) map[string]runtime.Consumer { - result := make(map[string]runtime.Consumer) - for _, mt := range mediaTypes { - if consumer, ok := d.consumers[mt]; ok { - result[mt] = consumer - } - } - return result -} - -// ProducersFor gets the producers for the specified media types -func (d *API) ProducersFor(mediaTypes []string) map[string]runtime.Producer { - result := make(map[string]runtime.Producer) - for _, mt := range mediaTypes { - if producer, ok := d.producers[mt]; ok { - result[mt] = producer - } - } - return result -} - -// AuthenticatorsFor gets the authenticators for the specified security schemes -func (d *API) AuthenticatorsFor(schemes map[string]spec.SecurityScheme) map[string]runtime.Authenticator { - result := make(map[string]runtime.Authenticator) - for k := range schemes { - if a, ok := d.authenticators[k]; ok { - result[k] = a - } - } - return result -} - -// AuthorizersFor returns the registered authorizer -func (d *API) Authorizer() runtime.Authorizer { - return d.authorizer -} - -// Validate validates this API for any missing items -func (d *API) Validate() error { - return d.validate() -} - -// validateWith validates the registrations in this API against the provided spec analyzer -func (d *API) validate() error { - var consumes []string - for k := range d.consumers { - consumes = append(consumes, k) - } - - var produces []string - for k := range d.producers { - produces = append(produces, k) - } - - var authenticators []string - for k := range d.authenticators { - authenticators = append(authenticators, k) - } - - var operations []string - for m, v := range d.operations { - for p := range v { - operations = append(operations, fmt.Sprintf("%s %s", strings.ToUpper(m), p)) - } - } - - var definedAuths []string - for k := range d.spec.Spec().SecurityDefinitions { - definedAuths = append(definedAuths, k) - } - - if err := d.verify("consumes", consumes, d.analyzer.RequiredConsumes()); err != nil { - return err - } - if err := d.verify("produces", produces, d.analyzer.RequiredProduces()); err != nil { - return err - } - if err := d.verify("operation", operations, d.analyzer.OperationMethodPaths()); err != nil { - return err - } - - requiredAuths := d.analyzer.RequiredSecuritySchemes() - if err := d.verify("auth scheme", authenticators, requiredAuths); err != nil { - return err - } - if err := d.verify("security definitions", definedAuths, requiredAuths); err != nil { - return err - } - return nil -} - -func (d *API) verify(name string, registrations []string, expectations []string) error { - - sort.Sort(sort.StringSlice(registrations)) - sort.Sort(sort.StringSlice(expectations)) - - expected := map[string]struct{}{} - seen := map[string]struct{}{} - - for _, v := range expectations { - expected[v] = struct{}{} - } - - var unspecified []string - for _, v := range registrations { - seen[v] = struct{}{} - if _, ok := expected[v]; !ok { - unspecified = append(unspecified, v) - } - } - - for k := range seen { - delete(expected, k) - } - - var unregistered []string - for k := range expected { - unregistered = append(unregistered, k) - } - sort.Sort(sort.StringSlice(unspecified)) - sort.Sort(sort.StringSlice(unregistered)) - - if len(unregistered) > 0 || len(unspecified) > 0 { - return &errors.APIVerificationFailed{ - Section: name, - MissingSpecification: unspecified, - MissingRegistration: unregistered, - } - } - - return nil -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/untyped/api_test.go b/vendor/github.com/go-openapi/runtime/middleware/untyped/api_test.go deleted file mode 100644 index 551bec71f..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/untyped/api_test.go +++ /dev/null @@ -1,286 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package untyped - -import ( - "io" - "net/http" - "sort" - "testing" - - "github.com/go-openapi/analysis" - "github.com/go-openapi/errors" - "github.com/go-openapi/loads" - "github.com/go-openapi/runtime" - swaggerspec "github.com/go-openapi/spec" - "github.com/stretchr/testify/assert" -) - -func stubAutenticator() runtime.Authenticator { - return runtime.AuthenticatorFunc(func(_ interface{}) (bool, interface{}, error) { return false, nil, nil }) -} - -func stubAuthorizer() runtime.Authorizer { - return runtime.AuthorizerFunc(func(_ *http.Request, _ interface{}) error { return nil }) -} - -type stubConsumer struct { -} - -func (s *stubConsumer) Consume(_ io.Reader, _ interface{}) error { - return nil -} - -type stubProducer struct { -} - -func (s *stubProducer) Produce(_ io.Writer, _ interface{}) error { - return nil -} - -type stubOperationHandler struct { -} - -func (s *stubOperationHandler) ParameterModel() interface{} { - return nil -} - -func (s *stubOperationHandler) Handle(params interface{}) (interface{}, error) { - return nil, nil -} - -func TestUntypedAPIRegistrations(t *testing.T) { - api := NewAPI(new(loads.Document)).WithJSONDefaults() - - api.RegisterConsumer("application/yada", new(stubConsumer)) - api.RegisterProducer("application/yada-2", new(stubProducer)) - api.RegisterOperation("get", "/{someId}", new(stubOperationHandler)) - api.RegisterAuth("basic", stubAutenticator()) - api.RegisterAuthorizer(stubAuthorizer()) - - assert.NotNil(t, api.authorizer) - assert.NotEmpty(t, api.authenticators) - - _, ok := api.authenticators["basic"] - assert.True(t, ok) - _, ok = api.consumers["application/yada"] - assert.True(t, ok) - _, ok = api.producers["application/yada-2"] - assert.True(t, ok) - _, ok = api.consumers["application/json"] - assert.True(t, ok) - _, ok = api.producers["application/json"] - assert.True(t, ok) - _, ok = api.operations["GET"]["/{someId}"] - assert.True(t, ok) - - authorizer := api.Authorizer() - assert.NotNil(t, authorizer) - - h, ok := api.OperationHandlerFor("get", "/{someId}") - assert.True(t, ok) - assert.NotNil(t, h) - - _, ok = api.OperationHandlerFor("doesntExist", "/{someId}") - assert.False(t, ok) -} - -func TestUntypedAppValidation(t *testing.T) { - invalidSpecStr := `{ - "consumes": ["application/json"], - "produces": ["application/json"], - "security": [ - {"apiKey":[]} - ], - "parameters": { - "format": { - "in": "query", - "name": "format", - "type": "string" - } - }, - "paths": { - "/": { - "parameters": [ - { - "name": "limit", - "type": "integer", - "format": "int32", - "x-go-name": "Limit" - } - ], - "get": { - "consumes": ["application/x-yaml"], - "produces": ["application/x-yaml"], - "security": [ - {"basic":[]} - ], - "parameters": [ - { - "name": "skip", - "type": "integer", - "format": "int32" - } - ] - } - } - } -}` - specStr := `{ - "consumes": ["application/json"], - "produces": ["application/json"], - "security": [ - {"apiKey":[]} - ], - "securityDefinitions": { - "basic": { "type": "basic" }, - "apiKey": { "type": "apiKey", "in":"header", "name":"X-API-KEY" } - }, - "parameters": { - "format": { - "in": "query", - "name": "format", - "type": "string" - } - }, - "paths": { - "/": { - "parameters": [ - { - "name": "limit", - "type": "integer", - "format": "int32", - "x-go-name": "Limit" - } - ], - "get": { - "consumes": ["application/x-yaml"], - "produces": ["application/x-yaml"], - "security": [ - {"basic":[]} - ], - "parameters": [ - { - "name": "skip", - "type": "integer", - "format": "int32" - } - ] - } - } - } - }` - validSpec, err := loads.Analyzed([]byte(specStr), "") - assert.NoError(t, err) - assert.NotNil(t, validSpec) - - spec, err := loads.Analyzed([]byte(invalidSpecStr), "") - assert.NoError(t, err) - assert.NotNil(t, spec) - - analyzed := analysis.New(spec.Spec()) - analyzedValid := analysis.New(validSpec.Spec()) - cons := analyzed.ConsumesFor(analyzed.AllPaths()["/"].Get) - assert.Len(t, cons, 1) - prods := analyzed.RequiredProduces() - assert.Len(t, prods, 2) - - api1 := NewAPI(spec) - err = api1.Validate() - assert.Error(t, err) - assert.Equal(t, "missing [application/x-yaml] consumes registrations", err.Error()) - api1.RegisterConsumer("application/x-yaml", new(stubConsumer)) - err = api1.validate() - assert.Error(t, err) - assert.Equal(t, "missing [application/x-yaml] produces registrations", err.Error()) - api1.RegisterProducer("application/x-yaml", new(stubProducer)) - err = api1.validate() - assert.Error(t, err) - assert.Equal(t, "missing [GET /] operation registrations", err.Error()) - api1.RegisterOperation("get", "/", new(stubOperationHandler)) - err = api1.validate() - assert.Error(t, err) - assert.Equal(t, "missing [apiKey, basic] auth scheme registrations", err.Error()) - api1.RegisterAuth("basic", stubAutenticator()) - api1.RegisterAuth("apiKey", stubAutenticator()) - err = api1.validate() - assert.Error(t, err) - assert.Equal(t, "missing [apiKey, basic] security definitions registrations", err.Error()) - - api3 := NewAPI(validSpec) - api3.RegisterConsumer("application/x-yaml", new(stubConsumer)) - api3.RegisterProducer("application/x-yaml", new(stubProducer)) - api3.RegisterOperation("get", "/", new(stubOperationHandler)) - api3.RegisterAuth("basic", stubAutenticator()) - api3.RegisterAuth("apiKey", stubAutenticator()) - err = api3.validate() - assert.NoError(t, err) - api3.RegisterConsumer("application/something", new(stubConsumer)) - err = api3.validate() - assert.Error(t, err) - assert.Equal(t, "missing from spec file [application/something] consumes", err.Error()) - - api2 := NewAPI(spec) - api2.RegisterConsumer("application/something", new(stubConsumer)) - err = api2.validate() - assert.Error(t, err) - assert.Equal(t, "missing [application/x-yaml] consumes registrations\nmissing from spec file [application/something] consumes", err.Error()) - api2.RegisterConsumer("application/x-yaml", new(stubConsumer)) - delete(api2.consumers, "application/something") - api2.RegisterProducer("application/something", new(stubProducer)) - err = api2.validate() - assert.Error(t, err) - assert.Equal(t, "missing [application/x-yaml] produces registrations\nmissing from spec file [application/something] produces", err.Error()) - delete(api2.producers, "application/something") - api2.RegisterProducer("application/x-yaml", new(stubProducer)) - - expected := []string{"application/x-yaml"} - sort.Sort(sort.StringSlice(expected)) - consumes := analyzed.ConsumesFor(analyzed.AllPaths()["/"].Get) - sort.Sort(sort.StringSlice(consumes)) - assert.Equal(t, expected, consumes) - consumers := api1.ConsumersFor(consumes) - assert.Len(t, consumers, 1) - - produces := analyzed.ProducesFor(analyzed.AllPaths()["/"].Get) - sort.Sort(sort.StringSlice(produces)) - assert.Equal(t, expected, produces) - producers := api1.ProducersFor(produces) - assert.Len(t, producers, 1) - - definitions := analyzedValid.SecurityDefinitionsFor(analyzedValid.AllPaths()["/"].Get) - expectedSchemes := map[string]swaggerspec.SecurityScheme{"basic": *swaggerspec.BasicAuth()} - assert.Equal(t, expectedSchemes, definitions) - authenticators := api3.AuthenticatorsFor(definitions) - assert.Len(t, authenticators, 1) - - opHandler := runtime.OperationHandlerFunc(func(data interface{}) (interface{}, error) { - return data, nil - }) - d, err := opHandler.Handle(1) - assert.NoError(t, err) - assert.Equal(t, 1, d) - - authenticator := runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) { - if str, ok := params.(string); ok { - return ok, str, nil - } - return true, nil, errors.Unauthenticated("authenticator") - }) - ok, p, err := authenticator.Authenticate("hello") - assert.True(t, ok) - assert.NoError(t, err) - assert.Equal(t, "hello", p) -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/untyped_request_test.go b/vendor/github.com/go-openapi/runtime/middleware/untyped_request_test.go deleted file mode 100644 index 5c226f62e..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/untyped_request_test.go +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "io/ioutil" - "mime/multipart" - "net/http" - "net/url" - "strings" - "testing" - "time" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/stretchr/testify/assert" -) - -func TestUntypedFormPost(t *testing.T) { - params := parametersForFormUpload() - binder := newUntypedRequestBinder(params, nil, strfmt.Default) - - urlStr := "http://localhost:8002/hello" - req, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(`name=the-name&age=32`)) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - data := make(map[string]interface{}) - assert.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) - assert.Equal(t, "the-name", data["name"]) - assert.EqualValues(t, 32, data["age"]) - - req, _ = http.NewRequest("POST", urlStr, bytes.NewBufferString(`name=%3&age=32`)) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - data = make(map[string]interface{}) - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) -} - -func TestUntypedFileUpload(t *testing.T) { - binder := paramsForFileUpload() - - body := bytes.NewBuffer(nil) - writer := multipart.NewWriter(body) - part, err := writer.CreateFormFile("file", "plain-jane.txt") - assert.NoError(t, err) - - _, _ = part.Write([]byte("the file contents")) - _ = writer.WriteField("name", "the-name") - assert.NoError(t, writer.Close()) - - urlStr := "http://localhost:8002/hello" - req, _ := http.NewRequest("POST", urlStr, body) - req.Header.Set("Content-Type", writer.FormDataContentType()) - - data := make(map[string]interface{}) - assert.NoError(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) - assert.Equal(t, "the-name", data["name"]) - assert.NotNil(t, data["file"]) - assert.IsType(t, runtime.File{}, data["file"]) - file := data["file"].(runtime.File) - assert.NotNil(t, file.Header) - assert.Equal(t, "plain-jane.txt", file.Header.Filename) - - bb, err := ioutil.ReadAll(file.Data) - assert.NoError(t, err) - assert.Equal(t, []byte("the file contents"), bb) - - req, _ = http.NewRequest("POST", urlStr, body) - req.Header.Set("Content-Type", "application/json") - data = make(map[string]interface{}) - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) - - req, _ = http.NewRequest("POST", urlStr, body) - req.Header.Set("Content-Type", "application(") - data = make(map[string]interface{}) - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) - - body = bytes.NewBuffer(nil) - writer = multipart.NewWriter(body) - part, err = writer.CreateFormFile("bad-name", "plain-jane.txt") - assert.NoError(t, err) - - _, _ = part.Write([]byte("the file contents")) - _ = writer.WriteField("name", "the-name") - assert.NoError(t, writer.Close()) - req, _ = http.NewRequest("POST", urlStr, body) - req.Header.Set("Content-Type", writer.FormDataContentType()) - - data = make(map[string]interface{}) - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) - - req, _ = http.NewRequest("POST", urlStr, body) - req.Header.Set("Content-Type", writer.FormDataContentType()) - _, _ = req.MultipartReader() - - data = make(map[string]interface{}) - assert.Error(t, binder.Bind(req, nil, runtime.JSONConsumer(), &data)) -} - -func TestUntypedBindingTypesForValid(t *testing.T) { - - op2 := parametersForAllTypes("") - binder := newUntypedRequestBinder(op2, nil, strfmt.Default) - - confirmed := true - name := "thomas" - friend := map[string]interface{}{"name": "toby", "age": json.Number("32")} - id, age, score, factor := int64(7575), int32(348), float32(5.309), float64(37.403) - requestID := 19394858 - tags := []string{"one", "two", "three"} - dt1 := time.Date(2014, 8, 9, 0, 0, 0, 0, time.UTC) - planned := strfmt.Date(dt1) - dt2 := time.Date(2014, 10, 12, 8, 5, 5, 0, time.UTC) - delivered := strfmt.DateTime(dt2) - picture := base64.URLEncoding.EncodeToString([]byte("hello")) - uri, _ := url.Parse("http://localhost:8002/hello/7575") - qs := uri.Query() - qs.Add("name", name) - qs.Add("confirmed", "true") - qs.Add("age", "348") - qs.Add("score", "5.309") - qs.Add("factor", "37.403") - qs.Add("tags", strings.Join(tags, ",")) - qs.Add("planned", planned.String()) - qs.Add("delivered", delivered.String()) - qs.Add("picture", picture) - - req, _ := http.NewRequest("POST", uri.String()+"?"+qs.Encode(), bytes.NewBuffer([]byte(`{"name":"toby","age":32}`))) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Request-Id", "19394858") - - data := make(map[string]interface{}) - err := binder.Bind(req, RouteParams([]RouteParam{{"id", "7575"}}), runtime.JSONConsumer(), &data) - assert.NoError(t, err) - assert.Equal(t, id, data["id"]) - assert.Equal(t, name, data["name"]) - assert.Equal(t, friend, data["friend"]) - assert.EqualValues(t, requestID, data["X-Request-Id"]) - assert.Equal(t, tags, data["tags"]) - assert.Equal(t, planned, data["planned"]) - assert.Equal(t, delivered, data["delivered"]) - assert.Equal(t, confirmed, data["confirmed"]) - assert.Equal(t, age, data["age"]) - assert.Equal(t, factor, data["factor"]) - assert.Equal(t, score, data["score"]) - pb, _ := base64.URLEncoding.DecodeString(picture) - assert.EqualValues(t, pb, data["picture"].(strfmt.Base64)) - -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/validation.go b/vendor/github.com/go-openapi/runtime/middleware/validation.go deleted file mode 100644 index bb8df3cb3..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/validation.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "mime" - "net/http" - "strings" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/swag" -) - -type validation struct { - context *Context - result []error - request *http.Request - route *MatchedRoute - bound map[string]interface{} -} - -// ContentType validates the content type of a request -func validateContentType(allowed []string, actual string) error { - debugLog("validating content type for %q against [%s]", actual, strings.Join(allowed, ", ")) - if len(allowed) == 0 { - return nil - } - mt, _, err := mime.ParseMediaType(actual) - if err != nil { - return errors.InvalidContentType(actual, allowed) - } - if swag.ContainsStringsCI(allowed, mt) { - return nil - } - if swag.ContainsStringsCI(allowed, "*/*") { - return nil - } - parts := strings.Split(actual, "/") - if len(parts) == 2 && swag.ContainsStringsCI(allowed, parts[0]+"/*") { - return nil - } - return errors.InvalidContentType(actual, allowed) -} - -func validateRequest(ctx *Context, request *http.Request, route *MatchedRoute) *validation { - debugLog("validating request %s %s", request.Method, request.URL.EscapedPath()) - validate := &validation{ - context: ctx, - request: request, - route: route, - bound: make(map[string]interface{}), - } - - validate.contentType() - if len(validate.result) == 0 { - validate.responseFormat() - } - if len(validate.result) == 0 { - validate.parameters() - } - - return validate -} - -func (v *validation) parameters() { - debugLog("validating request parameters for %s %s", v.request.Method, v.request.URL.EscapedPath()) - if result := v.route.Binder.Bind(v.request, v.route.Params, v.route.Consumer, v.bound); result != nil { - if result.Error() == "validation failure list" { - for _, e := range result.(*errors.Validation).Value.([]interface{}) { - v.result = append(v.result, e.(error)) - } - return - } - v.result = append(v.result, result) - } -} - -func (v *validation) contentType() { - if len(v.result) == 0 && runtime.HasBody(v.request) { - debugLog("validating body content type for %s %s", v.request.Method, v.request.URL.EscapedPath()) - ct, _, req, err := v.context.ContentType(v.request) - if err != nil { - v.result = append(v.result, err) - } else { - v.request = req - } - - if len(v.result) == 0 { - if err := validateContentType(v.route.Consumes, ct); err != nil { - v.result = append(v.result, err) - } - } - if ct != "" && v.route.Consumer == nil { - cons, ok := v.route.Consumers[ct] - if !ok { - v.result = append(v.result, errors.New(500, "no consumer registered for %s", ct)) - } else { - v.route.Consumer = cons - } - } - } -} - -func (v *validation) responseFormat() { - if str, rCtx := v.context.ResponseFormat(v.request, v.route.Produces); str == "" && runtime.HasBody(v.request) { - v.request = rCtx - v.result = append(v.result, errors.InvalidResponseFormat(v.request.Header.Get(runtime.HeaderAccept), v.route.Produces)) - } -} diff --git a/vendor/github.com/go-openapi/runtime/middleware/validation_test.go b/vendor/github.com/go-openapi/runtime/middleware/validation_test.go deleted file mode 100644 index 10ec57879..000000000 --- a/vendor/github.com/go-openapi/runtime/middleware/validation_test.go +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package middleware - -import ( - "bytes" - "net/http" - "net/http/httptest" - "testing" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/internal/testing/petstore" - "github.com/stretchr/testify/assert" -) - -func newTestValidation(ctx *Context, next http.Handler) http.Handler { - - return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - matched, rCtx, _ := ctx.RouteInfo(r) - if rCtx != nil { - r = rCtx - } - if matched == nil { - ctx.NotFound(rw, r) - return - } - _, r, result := ctx.BindAndValidate(r, matched) - - if result != nil { - ctx.Respond(rw, r, matched.Produces, matched, result) - return - } - - next.ServeHTTP(rw, r) - }) -} - -func TestContentTypeValidation(t *testing.T) { - spec, api := petstore.NewAPI(t) - context := NewContext(spec, api, nil) - context.router = DefaultRouter(spec, context.api) - mw := newTestValidation(context, http.HandlerFunc(terminator)) - - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/api/pets", nil) - request.Header.Add("Accept", "*/*") - mw.ServeHTTP(recorder, request) - assert.Equal(t, http.StatusOK, recorder.Code) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("POST", "/api/pets", nil) - request.Header.Add("content-type", "application(") - request.Header.Add("Accept", "application/json") - request.ContentLength = 1 - - mw.ServeHTTP(recorder, request) - assert.Equal(t, http.StatusBadRequest, recorder.Code) - assert.Equal(t, "application/json", recorder.Header().Get("content-type")) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("POST", "/api/pets", nil) - request.Header.Add("Accept", "application/json") - request.Header.Add("content-type", "text/html") - request.ContentLength = 1 - - mw.ServeHTTP(recorder, request) - assert.Equal(t, http.StatusUnsupportedMediaType, recorder.Code) - assert.Equal(t, "application/json", recorder.Header().Get("content-type")) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("POST", "/api/pets", nil) - request.Header.Add("Accept", "application/json") - request.Header.Add("content-type", "text/html") - request.TransferEncoding = []string{"chunked"} - - mw.ServeHTTP(recorder, request) - assert.Equal(t, http.StatusUnsupportedMediaType, recorder.Code) - assert.Equal(t, "application/json", recorder.Header().Get("content-type")) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("POST", "/api/pets", nil) - request.Header.Add("Accept", "application/json") - request.Header.Add("content-type", "text/html") - - mw.ServeHTTP(recorder, request) - assert.Equal(t, 422, recorder.Code) - assert.Equal(t, "application/json", recorder.Header().Get("content-type")) -} - -func TestResponseFormatValidation(t *testing.T) { - spec, api := petstore.NewAPI(t) - context := NewContext(spec, api, nil) - context.router = DefaultRouter(spec, context.api) - mw := newTestValidation(context, http.HandlerFunc(terminator)) - - recorder := httptest.NewRecorder() - request, _ := http.NewRequest("POST", "/api/pets", bytes.NewBuffer([]byte(`name: Dog`))) - request.Header.Set(runtime.HeaderContentType, "application/x-yaml") - request.Header.Set(runtime.HeaderAccept, "application/x-yaml") - - mw.ServeHTTP(recorder, request) - assert.Equal(t, 200, recorder.Code, recorder.Body.String()) - - recorder = httptest.NewRecorder() - request, _ = http.NewRequest("POST", "/api/pets", bytes.NewBuffer([]byte(`name: Dog`))) - request.Header.Set(runtime.HeaderContentType, "application/x-yaml") - request.Header.Set(runtime.HeaderAccept, "application/sml") - - mw.ServeHTTP(recorder, request) - assert.Equal(t, http.StatusNotAcceptable, recorder.Code) -} - -func TestValidateContentType(t *testing.T) { - data := []struct { - hdr string - allowed []string - err *errors.Validation - }{ - {"application/json", []string{"application/json"}, nil}, - {"application/json", []string{"application/x-yaml", "text/html"}, errors.InvalidContentType("application/json", []string{"application/x-yaml", "text/html"})}, - {"text/html; charset=utf-8", []string{"text/html"}, nil}, - {"text/html;charset=utf-8", []string{"text/html"}, nil}, - {"", []string{"application/json"}, errors.InvalidContentType("", []string{"application/json"})}, - {"text/html; charset=utf-8", []string{"application/json"}, errors.InvalidContentType("text/html; charset=utf-8", []string{"application/json"})}, - {"application(", []string{"application/json"}, errors.InvalidContentType("application(", []string{"application/json"})}, - {"application/json;char*", []string{"application/json"}, errors.InvalidContentType("application/json;char*", []string{"application/json"})}, - {"application/octet-stream", []string{"image/jpeg", "application/*"}, nil}, - {"image/png", []string{"*/*", "application/json"}, nil}, - } - - for _, v := range data { - err := validateContentType(v.allowed, v.hdr) - if v.err == nil { - assert.NoError(t, err, "input: %q", v.hdr) - } else { - assert.Error(t, err, "input: %q", v.hdr) - assert.IsType(t, &errors.Validation{}, err, "input: %q", v.hdr) - assert.Equal(t, v.err.Error(), err.Error(), "input: %q", v.hdr) - assert.EqualValues(t, http.StatusUnsupportedMediaType, err.(*errors.Validation).Code()) - } - } -} diff --git a/vendor/github.com/go-openapi/runtime/request.go b/vendor/github.com/go-openapi/runtime/request.go deleted file mode 100644 index 87b73da45..000000000 --- a/vendor/github.com/go-openapi/runtime/request.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "io" - "net/http" - "strings" - - "github.com/go-openapi/swag" -) - -// CanHaveBody returns true if this method can have a body -func CanHaveBody(method string) bool { - mn := strings.ToUpper(method) - return mn == "POST" || mn == "PUT" || mn == "PATCH" || mn == "DELETE" -} - -// IsSafe returns true if this is a request with a safe method -func IsSafe(r *http.Request) bool { - mn := strings.ToUpper(r.Method) - return mn == "GET" || mn == "HEAD" -} - -// AllowsBody returns true if the request allows for a body -func AllowsBody(r *http.Request) bool { - mn := strings.ToUpper(r.Method) - return mn != "HEAD" -} - -// HasBody returns true if this method needs a content-type -func HasBody(r *http.Request) bool { - return len(r.TransferEncoding) > 0 || r.ContentLength > 0 -} - -// JSONRequest creates a new http request with json headers set -func JSONRequest(method, urlStr string, body io.Reader) (*http.Request, error) { - req, err := http.NewRequest(method, urlStr, body) - if err != nil { - return nil, err - } - req.Header.Add(HeaderContentType, JSONMime) - req.Header.Add(HeaderAccept, JSONMime) - return req, nil -} - -// Gettable for things with a method GetOK(string) (data string, hasKey bool, hasValue bool) -type Gettable interface { - GetOK(string) ([]string, bool, bool) -} - -// ReadSingleValue reads a single value from the source -func ReadSingleValue(values Gettable, name string) string { - vv, _, hv := values.GetOK(name) - if hv { - return vv[len(vv)-1] - } - return "" -} - -// ReadCollectionValue reads a collection value from a string data source -func ReadCollectionValue(values Gettable, name, collectionFormat string) []string { - v := ReadSingleValue(values, name) - return swag.SplitByFormat(v, collectionFormat) -} diff --git a/vendor/github.com/go-openapi/runtime/request_test.go b/vendor/github.com/go-openapi/runtime/request_test.go deleted file mode 100644 index ba65f75f7..000000000 --- a/vendor/github.com/go-openapi/runtime/request_test.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "net/url" - "testing" - - "github.com/stretchr/testify/assert" -) - -/* -type tstreadcloser struct { - closed bool -} - -func (t *tstreadcloser) Read(p []byte) (int, error) { return 0, nil } -func (t *tstreadcloser) Close() error { - t.closed = true - return nil -} - -func TestPeekingReader(t *testing.T) { - // just passes to original reader when nothing called - exp1 := []byte("original") - pr1 := &peekingReader{rdr: ioutil.NopCloser(bytes.NewReader(exp1))} - b1, err := ioutil.ReadAll(pr1) - if assert.NoError(t, err) { - assert.Equal(t, exp1, b1) - } - - // uses actual when there was some buffering - exp2 := []byte("actual") - pt1, pt2 := []byte("a"), []byte("ctual") - pr2 := &peekingReader{ - rdr: ioutil.NopCloser(bytes.NewReader(exp1)), - actual: io.MultiReader(bytes.NewReader(pt1), bytes.NewReader(pt2)), - peeked: pt1, - } - b2, err := ioutil.ReadAll(pr2) - if assert.NoError(t, err) { - assert.Equal(t, exp2, b2) - } - - // closes original reader - tr := new(tstreadcloser) - pr3 := &peekingReader{ - rdr: tr, - actual: ioutil.NopCloser(bytes.NewBuffer(nil)), - peeked: pt1, - } - - - // returns true when peeked previously with data - // returns true when peeked with data -} -*/ - -func TestJSONRequest(t *testing.T) { - req, err := JSONRequest("GET", "/swagger.json", nil) - assert.NoError(t, err) - assert.Equal(t, "GET", req.Method) - assert.Equal(t, JSONMime, req.Header.Get(HeaderContentType)) - assert.Equal(t, JSONMime, req.Header.Get(HeaderAccept)) - - req, err = JSONRequest("GET", "%2", nil) - assert.Error(t, err) - assert.Nil(t, req) -} - -//func TestCanHaveBody(t *testing.T) { -//assert.True(t, CanHaveBody("put")) -//assert.True(t, CanHaveBody("post")) -//assert.True(t, CanHaveBody("patch")) -//assert.True(t, CanHaveBody("delete")) -//assert.False(t, CanHaveBody("")) -//assert.False(t, CanHaveBody("get")) -//assert.False(t, CanHaveBody("options")) -//assert.False(t, CanHaveBody("head")) -//assert.False(t, CanHaveBody("invalid")) -//} - -func TestReadSingle(t *testing.T) { - values := url.Values(make(map[string][]string)) - values.Add("something", "the thing") - assert.Equal(t, "the thing", ReadSingleValue(tv(values), "something")) - assert.Empty(t, ReadSingleValue(tv(values), "notthere")) -} - -func TestReadCollection(t *testing.T) { - values := url.Values(make(map[string][]string)) - values.Add("something", "value1,value2") - assert.Equal(t, []string{"value1", "value2"}, ReadCollectionValue(tv(values), "something", "csv")) - assert.Empty(t, ReadCollectionValue(tv(values), "notthere", "")) -} - -type tv map[string][]string - -func (v tv) GetOK(key string) (value []string, hasKey bool, hasValue bool) { - value, hasKey = v[key] - if !hasKey { - return - } - if len(value) == 0 { - return - } - hasValue = true - return - -} diff --git a/vendor/github.com/go-openapi/runtime/security/apikey_auth_test.go b/vendor/github.com/go-openapi/runtime/security/apikey_auth_test.go deleted file mode 100644 index 958b2ea42..000000000 --- a/vendor/github.com/go-openapi/runtime/security/apikey_auth_test.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package security - -import ( - "net/http" - "testing" - - "github.com/go-openapi/errors" - "github.com/stretchr/testify/assert" -) - -var tokenAuth = TokenAuthentication(func(token string) (interface{}, error) { - if token == "token123" { - return "admin", nil - } - return nil, errors.Unauthenticated("token") -}) - -func TestInvalidApiKeyAuthInitialization(t *testing.T) { - assert.Panics(t, func() { APIKeyAuth("api_key", "qery", tokenAuth) }) -} - -func TestValidApiKeyAuth(t *testing.T) { - ta := APIKeyAuth("api_key", "query", tokenAuth) - ta2 := APIKeyAuth("X-API-KEY", "header", tokenAuth) - - req1, _ := http.NewRequest("GET", "/blah?api_key=token123", nil) - - ok, usr, err := ta.Authenticate(req1) - assert.True(t, ok) - assert.Equal(t, "admin", usr) - assert.NoError(t, err) - - req2, _ := http.NewRequest("GET", "/blah", nil) - req2.Header.Set("X-API-KEY", "token123") - - ok, usr, err = ta2.Authenticate(req2) - assert.True(t, ok) - assert.Equal(t, "admin", usr) - assert.NoError(t, err) -} - -func TestInvalidApiKeyAuth(t *testing.T) { - ta := APIKeyAuth("api_key", "query", tokenAuth) - ta2 := APIKeyAuth("X-API-KEY", "header", tokenAuth) - - req1, _ := http.NewRequest("GET", "/blah?api_key=token124", nil) - - ok, usr, err := ta.Authenticate(req1) - assert.True(t, ok) - assert.Equal(t, nil, usr) - assert.Error(t, err) - - req2, _ := http.NewRequest("GET", "/blah", nil) - req2.Header.Set("X-API-KEY", "token124") - - ok, usr, err = ta2.Authenticate(req2) - assert.True(t, ok) - assert.Equal(t, nil, usr) - assert.Error(t, err) -} - -func TestMissingApiKeyAuth(t *testing.T) { - ta := APIKeyAuth("api_key", "query", tokenAuth) - ta2 := APIKeyAuth("X-API-KEY", "header", tokenAuth) - - req1, _ := http.NewRequest("GET", "/blah", nil) - req1.Header.Set("X-API-KEY", "token123") - - ok, usr, err := ta.Authenticate(req1) - assert.False(t, ok) - assert.Equal(t, nil, usr) - assert.NoError(t, err) - - req2, _ := http.NewRequest("GET", "/blah?api_key=token123", nil) - - ok, usr, err = ta2.Authenticate(req2) - assert.False(t, ok) - assert.Equal(t, nil, usr) - assert.NoError(t, err) -} diff --git a/vendor/github.com/go-openapi/runtime/security/authenticator.go b/vendor/github.com/go-openapi/runtime/security/authenticator.go deleted file mode 100644 index 251854e6d..000000000 --- a/vendor/github.com/go-openapi/runtime/security/authenticator.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package security - -import ( - "net/http" - "strings" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" -) - -// HttpAuthenticator is a function that authenticates a HTTP request -func HttpAuthenticator(handler func(*http.Request) (bool, interface{}, error)) runtime.Authenticator { - return runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) { - if request, ok := params.(*http.Request); ok { - return handler(request) - } - if scoped, ok := params.(*ScopedAuthRequest); ok { - return handler(scoped.Request) - } - return false, nil, nil - }) -} - -// ScopedAuthenticator is a function that authenticates a HTTP request against a list of valid scopes -func ScopedAuthenticator(handler func(*ScopedAuthRequest) (bool, interface{}, error)) runtime.Authenticator { - return runtime.AuthenticatorFunc(func(params interface{}) (bool, interface{}, error) { - if request, ok := params.(*ScopedAuthRequest); ok { - return handler(request) - } - return false, nil, nil - }) -} - -// UserPassAuthentication authentication function -type UserPassAuthentication func(string, string) (interface{}, error) - -// TokenAuthentication authentication function -type TokenAuthentication func(string) (interface{}, error) - -// ScopedTokenAuthentication authentication function -type ScopedTokenAuthentication func(string, []string) (interface{}, error) - -// BasicAuth creates a basic auth authenticator with the provided authentication function -func BasicAuth(authenticate UserPassAuthentication) runtime.Authenticator { - return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) { - if usr, pass, ok := r.BasicAuth(); ok { - p, err := authenticate(usr, pass) - return true, p, err - } - - return false, nil, nil - }) -} - -// APIKeyAuth creates an authenticator that uses a token for authorization. -// This token can be obtained from either a header or a query string -func APIKeyAuth(name, in string, authenticate TokenAuthentication) runtime.Authenticator { - inl := strings.ToLower(in) - if inl != "query" && inl != "header" { - // panic because this is most likely a typo - panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\".")) - } - - var getToken func(*http.Request) string - switch inl { - case "header": - getToken = func(r *http.Request) string { return r.Header.Get(name) } - case "query": - getToken = func(r *http.Request) string { return r.URL.Query().Get(name) } - } - - return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) { - token := getToken(r) - if token == "" { - return false, nil, nil - } - - p, err := authenticate(token) - return true, p, err - }) -} - -// ScopedAuthRequest contains both a http request and the required scopes for a particular operation -type ScopedAuthRequest struct { - Request *http.Request - RequiredScopes []string -} - -// BearerAuth for use with oauth2 flows -func BearerAuth(name string, authenticate ScopedTokenAuthentication) runtime.Authenticator { - const prefix = "Bearer " - return ScopedAuthenticator(func(r *ScopedAuthRequest) (bool, interface{}, error) { - var token string - hdr := r.Request.Header.Get("Authorization") - if strings.HasPrefix(hdr, prefix) { - token = strings.TrimPrefix(hdr, prefix) - } - if token == "" { - qs := r.Request.URL.Query() - token = qs.Get("access_token") - } - ct, _, _ := runtime.ContentType(r.Request.Header) - if token == "" && (ct == "application/x-www-form-urlencoded" || ct == "multipart/form-data") { - token = r.Request.FormValue("access_token") - } - - if token == "" { - return false, nil, nil - } - - p, err := authenticate(token, r.RequiredScopes) - return true, p, err - }) -} diff --git a/vendor/github.com/go-openapi/runtime/security/authorizer.go b/vendor/github.com/go-openapi/runtime/security/authorizer.go deleted file mode 100644 index 00c1a4d6a..000000000 --- a/vendor/github.com/go-openapi/runtime/security/authorizer.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package security - -import ( - "net/http" - - "github.com/go-openapi/runtime" -) - -// Authorized provides a default implementation of the Authorizer interface where all -// requests are authorized (successful) -func Authorized() runtime.Authorizer { - return runtime.AuthorizerFunc(func(_ *http.Request, _ interface{}) error { return nil }) -} diff --git a/vendor/github.com/go-openapi/runtime/security/authorizer_test.go b/vendor/github.com/go-openapi/runtime/security/authorizer_test.go deleted file mode 100644 index 7f1f9b053..000000000 --- a/vendor/github.com/go-openapi/runtime/security/authorizer_test.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package security - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestAuthorized(t *testing.T) { - authorizer := Authorized() - - err := authorizer.Authorize(nil, nil) - assert.NoError(t, err) -} diff --git a/vendor/github.com/go-openapi/runtime/security/basic_auth_test.go b/vendor/github.com/go-openapi/runtime/security/basic_auth_test.go deleted file mode 100644 index 94830bca5..000000000 --- a/vendor/github.com/go-openapi/runtime/security/basic_auth_test.go +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package security - -import ( - "net/http" - "testing" - - "github.com/go-openapi/errors" - "github.com/stretchr/testify/assert" -) - -var basicAuthHandler = UserPassAuthentication(func(user, pass string) (interface{}, error) { - if user == "admin" && pass == "123456" { - return "admin", nil - } - return "", errors.Unauthenticated("basic") -}) - -func TestValidBasicAuth(t *testing.T) { - ba := BasicAuth(basicAuthHandler) - - req, _ := http.NewRequest("GET", "/blah", nil) - req.SetBasicAuth("admin", "123456") - ok, usr, err := ba.Authenticate(req) - - assert.NoError(t, err) - assert.True(t, ok) - assert.Equal(t, "admin", usr) -} - -func TestInvalidBasicAuth(t *testing.T) { - ba := BasicAuth(basicAuthHandler) - - req, _ := http.NewRequest("GET", "/blah", nil) - req.SetBasicAuth("admin", "admin") - ok, usr, err := ba.Authenticate(req) - - assert.Error(t, err) - assert.True(t, ok) - assert.Equal(t, "", usr) -} - -func TestMissingbasicAuth(t *testing.T) { - ba := BasicAuth(basicAuthHandler) - - req, _ := http.NewRequest("GET", "/blah", nil) - - ok, usr, err := ba.Authenticate(req) - assert.NoError(t, err) - assert.False(t, ok) - assert.Equal(t, nil, usr) -} - -func TestNoRequestBasicAuth(t *testing.T) { - ba := BasicAuth(basicAuthHandler) - - ok, usr, err := ba.Authenticate("token") - - assert.NoError(t, err) - assert.False(t, ok) - assert.Nil(t, usr) -} diff --git a/vendor/github.com/go-openapi/runtime/security/bearer_auth_test.go b/vendor/github.com/go-openapi/runtime/security/bearer_auth_test.go deleted file mode 100644 index 899dc73d9..000000000 --- a/vendor/github.com/go-openapi/runtime/security/bearer_auth_test.go +++ /dev/null @@ -1,143 +0,0 @@ -package security - -import ( - "bytes" - "mime/multipart" - "net/http" - "net/url" - "strings" - "testing" - - "github.com/go-openapi/errors" - "github.com/stretchr/testify/assert" -) - -var bearerAuth = ScopedTokenAuthentication(func(token string, requiredScopes []string) (interface{}, error) { - if token == "token123" { - return "admin", nil - } - return nil, errors.Unauthenticated("bearer") -}) - -func TestValidBearerAuth(t *testing.T) { - ba := BearerAuth("owners_auth", bearerAuth) - - req1, _ := http.NewRequest("GET", "/blah?access_token=token123", nil) - - ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1}) - assert.True(t, ok) - assert.Equal(t, "admin", usr) - assert.NoError(t, err) - - req2, _ := http.NewRequest("GET", "/blah", nil) - req2.Header.Set("Authorization", "Bearer token123") - - ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2}) - assert.True(t, ok) - assert.Equal(t, "admin", usr) - assert.NoError(t, err) - - body := url.Values(map[string][]string{}) - body.Set("access_token", "token123") - req3, _ := http.NewRequest("POST", "/blah", strings.NewReader(body.Encode())) - req3.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req3}) - assert.True(t, ok) - assert.Equal(t, "admin", usr) - assert.NoError(t, err) - - mpbody := bytes.NewBuffer(nil) - writer := multipart.NewWriter(mpbody) - _ = writer.WriteField("access_token", "token123") - writer.Close() - req4, _ := http.NewRequest("POST", "/blah", mpbody) - req4.Header.Set("Content-Type", writer.FormDataContentType()) - - ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req4}) - assert.True(t, ok) - assert.Equal(t, "admin", usr) - assert.NoError(t, err) -} - -func TestInvalidBearerAuth(t *testing.T) { - ba := BearerAuth("owners_auth", bearerAuth) - - req1, _ := http.NewRequest("GET", "/blah?access_token=token124", nil) - - ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1}) - assert.True(t, ok) - assert.Equal(t, nil, usr) - assert.Error(t, err) - - req2, _ := http.NewRequest("GET", "/blah", nil) - req2.Header.Set("Authorization", "Bearer token124") - - ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2}) - assert.True(t, ok) - assert.Equal(t, nil, usr) - assert.Error(t, err) - - body := url.Values(map[string][]string{}) - body.Set("access_token", "token124") - req3, _ := http.NewRequest("POST", "/blah", strings.NewReader(body.Encode())) - req3.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req3}) - assert.True(t, ok) - assert.Equal(t, nil, usr) - assert.Error(t, err) - - mpbody := bytes.NewBuffer(nil) - writer := multipart.NewWriter(mpbody) - _ = writer.WriteField("access_token", "token124") - writer.Close() - req4, _ := http.NewRequest("POST", "/blah", mpbody) - req4.Header.Set("Content-Type", writer.FormDataContentType()) - - ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req4}) - assert.True(t, ok) - assert.Equal(t, nil, usr) - assert.Error(t, err) -} - -func TestMissingBearerAuth(t *testing.T) { - ba := BearerAuth("owners_auth", bearerAuth) - - req1, _ := http.NewRequest("GET", "/blah?access_toke=token123", nil) - - ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1}) - assert.False(t, ok) - assert.Equal(t, nil, usr) - assert.NoError(t, err) - - req2, _ := http.NewRequest("GET", "/blah", nil) - req2.Header.Set("Authorization", "Beare token123") - - ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2}) - assert.False(t, ok) - assert.Equal(t, nil, usr) - assert.NoError(t, err) - - body := url.Values(map[string][]string{}) - body.Set("access_toke", "token123") - req3, _ := http.NewRequest("POST", "/blah", strings.NewReader(body.Encode())) - req3.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req3}) - assert.False(t, ok) - assert.Equal(t, nil, usr) - assert.NoError(t, err) - - mpbody := bytes.NewBuffer(nil) - writer := multipart.NewWriter(mpbody) - _ = writer.WriteField("access_toke", "token123") - writer.Close() - req4, _ := http.NewRequest("POST", "/blah", mpbody) - req4.Header.Set("Content-Type", writer.FormDataContentType()) - - ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req4}) - assert.False(t, ok) - assert.Equal(t, nil, usr) - assert.NoError(t, err) -} diff --git a/vendor/github.com/go-openapi/runtime/statuses.go b/vendor/github.com/go-openapi/runtime/statuses.go deleted file mode 100644 index 3b011a0bf..000000000 --- a/vendor/github.com/go-openapi/runtime/statuses.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -// Statuses lists the most common HTTP status codes to default message -// taken from https://httpstatuses.com/ -var Statuses = map[int]string{ - 100: "Continue", - 101: "Switching Protocols", - 102: "Processing", - 103: "Checkpoint", - 122: "URI too long", - 200: "OK", - 201: "Created", - 202: "Accepted", - 203: "Request Processed", - 204: "No Content", - 205: "Reset Content", - 206: "Partial Content", - 207: "Multi-Status", - 208: "Already Reported", - 226: "IM Used", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Found", - 303: "See Other", - 304: "Not Modified", - 305: "Use Proxy", - 306: "Switch Proxy", - 307: "Temporary Redirect", - 308: "Permanent Redirect", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 409: "Conflict", - 410: "Gone", - 411: "Length Required", - 412: "Precondition Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Request Range Not Satisfiable", - 417: "Expectation Failed", - 418: "I'm a teapot", - 420: "Enhance Your Calm", - 422: "Unprocessable Entity", - 423: "Locked", - 424: "Failed Dependency", - 426: "Upgrade Required", - 428: "Precondition Required", - 429: "Too Many Requests", - 431: "Request Header Fields Too Large", - 444: "No Response", - 449: "Retry With", - 450: "Blocked by Windows Parental Controls", - 451: "Wrong Exchange Server", - 499: "Client Closed Request", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Gateway Timeout", - 505: "HTTP Version Not Supported", - 506: "Variant Also Negotiates", - 507: "Insufficient Storage", - 508: "Loop Detected", - 509: "Bandwidth Limit Exceeded", - 510: "Not Extended", - 511: "Network Authentication Required", - 598: "Network read timeout error", - 599: "Network connect timeout error", -} diff --git a/vendor/github.com/go-openapi/runtime/text.go b/vendor/github.com/go-openapi/runtime/text.go deleted file mode 100644 index 77099feda..000000000 --- a/vendor/github.com/go-openapi/runtime/text.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "bytes" - "encoding" - "errors" - "fmt" - "io" - "reflect" - - "github.com/go-openapi/swag" -) - -// TextConsumer creates a new text consumer -func TextConsumer() Consumer { - return ConsumerFunc(func(reader io.Reader, data interface{}) error { - if reader == nil { - return errors.New("TextConsumer requires a reader") // early exit - } - - buf := new(bytes.Buffer) - _, err := buf.ReadFrom(reader) - if err != nil { - return err - } - b := buf.Bytes() - - if tu, ok := data.(encoding.TextUnmarshaler); ok { - err := tu.UnmarshalText(b) - if err != nil { - return fmt.Errorf("text consumer: %v", err) - } - - return nil - } - - t := reflect.TypeOf(data) - if data != nil && t.Kind() == reflect.Ptr { - v := reflect.Indirect(reflect.ValueOf(data)) - if t.Elem().Kind() == reflect.String { - v.SetString(string(b)) - return nil - } - } - - return fmt.Errorf("%v (%T) is not supported by the TextConsumer, %s", - data, data, "can be resolved by supporting TextUnmarshaler interface") - }) -} - -// TextProducer creates a new text producer -func TextProducer() Producer { - return ProducerFunc(func(writer io.Writer, data interface{}) error { - if writer == nil { - return errors.New("TextProducer requires a writer") // early exit - } - - if data == nil { - return errors.New("no data given to produce text from") - } - - if tm, ok := data.(encoding.TextMarshaler); ok { - txt, err := tm.MarshalText() - if err != nil { - return fmt.Errorf("text producer: %v", err) - } - _, err = writer.Write(txt) - return err - } - - if str, ok := data.(error); ok { - _, err := writer.Write([]byte(str.Error())) - return err - } - - if str, ok := data.(fmt.Stringer); ok { - _, err := writer.Write([]byte(str.String())) - return err - } - - v := reflect.Indirect(reflect.ValueOf(data)) - if t := v.Type(); t.Kind() == reflect.Struct || t.Kind() == reflect.Slice { - b, err := swag.WriteJSON(data) - if err != nil { - return err - } - _, err = writer.Write(b) - return err - } - if v.Kind() != reflect.String { - return fmt.Errorf("%T is not a supported type by the TextProducer", data) - } - - _, err := writer.Write([]byte(v.String())) - return err - }) -} diff --git a/vendor/github.com/go-openapi/runtime/text_test.go b/vendor/github.com/go-openapi/runtime/text_test.go deleted file mode 100644 index 86f8f5682..000000000 --- a/vendor/github.com/go-openapi/runtime/text_test.go +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "bytes" - "errors" - "fmt" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" -) - -var consProdText = `The quick brown fox jumped over the lazy dog.` - -func TestTextConsumer(t *testing.T) { - cons := TextConsumer() - - // can consume as a string - var str string - err1 := cons.Consume(bytes.NewBuffer([]byte(consProdText)), &str) - assert.NoError(t, err1) - assert.Equal(t, consProdText, str) - - var tu textUnmarshalDummy - - // can consume as a TextUnmarshaler - err3 := cons.Consume(bytes.NewBuffer([]byte(consProdText)), &tu) - assert.NoError(t, err3) - assert.Equal(t, consProdText, tu.str) - - // text unmarshal objects can return an error as well, this will be propagated - assert.Error(t, cons.Consume(bytes.NewBuffer(nil), &tu)) - - // when readers can't be read, those errors will be propogated as well - assert.Error(t, cons.Consume(new(nopReader), &tu)) - - // readers can also not be nil - assert.Error(t, cons.Consume(nil, &tu)) - - // can't consume nil ptr's or unsupported types - assert.Error(t, cons.Consume(bytes.NewBuffer([]byte(consProdText)), nil)) - assert.Error(t, cons.Consume(bytes.NewBuffer([]byte(consProdText)), 42)) - assert.Error(t, cons.Consume(bytes.NewBuffer([]byte(consProdText)), &struct{}{})) -} - -type textUnmarshalDummy struct { - str string -} - -func (t *textUnmarshalDummy) UnmarshalText(b []byte) error { - if len(b) == 0 { - return errors.New("no text given") - } - - t.str = string(b) - return nil -} - -type nopReader struct{} - -func (n *nopReader) Read(p []byte) (int, error) { - return 0, errors.New("nop") -} - -func TestTextProducer(t *testing.T) { - prod := TextProducer() - rw := httptest.NewRecorder() - err := prod.Produce(rw, consProdText) - assert.NoError(t, err) - assert.Equal(t, consProdText, rw.Body.String()) - rw2 := httptest.NewRecorder() - err2 := prod.Produce(rw2, &consProdText) - assert.NoError(t, err2) - assert.Equal(t, consProdText, rw2.Body.String()) - - // should always work with type aliases - // as an alias is sometimes given by generated go-swagger code - type alias string - aliasProdText := alias(consProdText) - rw3 := httptest.NewRecorder() - err3 := prod.Produce(rw3, aliasProdText) - assert.NoError(t, err3) - assert.Equal(t, consProdText, rw3.Body.String()) - rw4 := httptest.NewRecorder() - err4 := prod.Produce(rw4, &aliasProdText) - assert.NoError(t, err4) - assert.Equal(t, consProdText, rw4.Body.String()) - - const answer = "42" - - // Should always work with objects implementing Stringer interface - rw5 := httptest.NewRecorder() - err5 := prod.Produce(rw5, &stringerDummy{answer}) - assert.NoError(t, err5) - assert.Equal(t, answer, rw5.Body.String()) - - // Should always work with objects implementing TextMarshaler interface - rw6 := httptest.NewRecorder() - err6 := prod.Produce(rw6, &textMarshalDummy{answer}) - assert.NoError(t, err6) - assert.Equal(t, answer, rw6.Body.String()) - - rw10 := httptest.NewRecorder() - err10 := prod.Produce(rw10, errors.New(answer)) - assert.NoError(t, err10) - assert.Equal(t, answer, rw10.Body.String()) - - rw11 := httptest.NewRecorder() - err11 := prod.Produce(rw11, Error{Message: answer}) - assert.NoError(t, err11) - assert.Equal(t, fmt.Sprintf(`{"message":%q}`, answer), rw11.Body.String()) - - rw12 := httptest.NewRecorder() - err12 := prod.Produce(rw12, &Error{Message: answer}) - assert.NoError(t, err12) - assert.Equal(t, fmt.Sprintf(`{"message":%q}`, answer), rw12.Body.String()) - - rw13 := httptest.NewRecorder() - err13 := prod.Produce(rw13, []string{answer}) - assert.NoError(t, err13) - assert.Equal(t, fmt.Sprintf(`[%q]`, answer), rw13.Body.String()) - - // should not work with anything that's not (indirectly) a string - rw7 := httptest.NewRecorder() - err7 := prod.Produce(rw7, 42) - assert.Error(t, err7) - // nil values should also be safely caught with an error - rw8 := httptest.NewRecorder() - err8 := prod.Produce(rw8, nil) - assert.Error(t, err8) - - // writer can not be nil - assert.Error(t, prod.Produce(nil, &textMarshalDummy{answer})) - - // should not work for a textMarshaler that returns an error during marshalling - rw9 := httptest.NewRecorder() - err9 := prod.Produce(rw9, new(textMarshalDummy)) - assert.Error(t, err9) -} - -type Error struct { - Message string `json:"message"` -} - -type stringerDummy struct { - str string -} - -func (t *stringerDummy) String() string { - return t.str -} - -type textMarshalDummy struct { - str string -} - -func (t *textMarshalDummy) MarshalText() ([]byte, error) { - if t.str == "" { - return nil, errors.New("no text set") - } - return []byte(t.str), nil -} diff --git a/vendor/github.com/go-openapi/runtime/values.go b/vendor/github.com/go-openapi/runtime/values.go deleted file mode 100644 index 11f5732af..000000000 --- a/vendor/github.com/go-openapi/runtime/values.go +++ /dev/null @@ -1,19 +0,0 @@ -package runtime - -// Values typically represent parameters on a http request. -type Values map[string][]string - -// GetOK returns the values collection for the given key. -// When the key is present in the map it will return true for hasKey. -// When the value is not empty it will return true for hasValue. -func (v Values) GetOK(key string) (value []string, hasKey bool, hasValue bool) { - value, hasKey = v[key] - if !hasKey { - return - } - if len(value) == 0 { - return - } - hasValue = true - return -} diff --git a/vendor/github.com/go-openapi/runtime/xml.go b/vendor/github.com/go-openapi/runtime/xml.go deleted file mode 100644 index 821c7393d..000000000 --- a/vendor/github.com/go-openapi/runtime/xml.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "encoding/xml" - "io" -) - -// XMLConsumer creates a new XML consumer -func XMLConsumer() Consumer { - return ConsumerFunc(func(reader io.Reader, data interface{}) error { - dec := xml.NewDecoder(reader) - return dec.Decode(data) - }) -} - -// XMLProducer creates a new XML producer -func XMLProducer() Producer { - return ProducerFunc(func(writer io.Writer, data interface{}) error { - enc := xml.NewEncoder(writer) - return enc.Encode(data) - }) -} diff --git a/vendor/github.com/go-openapi/runtime/xml_test.go b/vendor/github.com/go-openapi/runtime/xml_test.go deleted file mode 100644 index 1f2dfd250..000000000 --- a/vendor/github.com/go-openapi/runtime/xml_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package runtime - -import ( - "bytes" - "encoding/xml" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" -) - -var consProdXML = `Somebody1` - -func TestXMLConsumer(t *testing.T) { - cons := XMLConsumer() - var data struct { - XMLName xml.Name `xml:"person"` - Name string `xml:"name"` - ID int `xml:"id"` - } - err := cons.Consume(bytes.NewBuffer([]byte(consProdXML)), &data) - assert.NoError(t, err) - assert.Equal(t, "Somebody", data.Name) - assert.Equal(t, 1, data.ID) -} - -func TestXMLProducer(t *testing.T) { - prod := XMLProducer() - data := struct { - XMLName xml.Name `xml:"person"` - Name string `xml:"name"` - ID int `xml:"id"` - }{Name: "Somebody", ID: 1} - - rw := httptest.NewRecorder() - err := prod.Produce(rw, data) - assert.NoError(t, err) - assert.Equal(t, consProdXML, rw.Body.String()) -} diff --git a/vendor/github.com/go-openapi/runtime/yamlpc/yaml.go b/vendor/github.com/go-openapi/runtime/yamlpc/yaml.go deleted file mode 100644 index fdbcc529c..000000000 --- a/vendor/github.com/go-openapi/runtime/yamlpc/yaml.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package yamlpc - -import ( - "io" - "io/ioutil" - - "github.com/go-openapi/runtime" - - "gopkg.in/yaml.v2" -) - -// YAMLConsumer creates a consumer for yaml data -func YAMLConsumer() runtime.Consumer { - return runtime.ConsumerFunc(func(r io.Reader, v interface{}) error { - buf, err := ioutil.ReadAll(r) - if err != nil { - return err - } - return yaml.Unmarshal(buf, v) - }) -} - -// YAMLProducer creates a producer for yaml data -func YAMLProducer() runtime.Producer { - return runtime.ProducerFunc(func(w io.Writer, v interface{}) error { - b, _ := yaml.Marshal(v) // can't make this error come up - _, err := w.Write(b) - return err - }) -} diff --git a/vendor/github.com/go-openapi/runtime/yamlpc/yaml_test.go b/vendor/github.com/go-openapi/runtime/yamlpc/yaml_test.go deleted file mode 100644 index 5cfe53951..000000000 --- a/vendor/github.com/go-openapi/runtime/yamlpc/yaml_test.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package yamlpc - -import ( - "bytes" - "errors" - "net/http/httptest" - "testing" - - "github.com/stretchr/testify/assert" -) - -var consProdYAML = "name: Somebody\nid: 1\n" - -func TestYAMLConsumer(t *testing.T) { - cons := YAMLConsumer() - var data struct { - Name string - ID int - } - err := cons.Consume(bytes.NewBuffer([]byte(consProdYAML)), &data) - assert.NoError(t, err) - assert.Equal(t, "Somebody", data.Name) - assert.Equal(t, 1, data.ID) -} - -func TestYAMLProducer(t *testing.T) { - prod := YAMLProducer() - data := struct { - Name string `yaml:"name"` - ID int `yaml:"id"` - }{Name: "Somebody", ID: 1} - - rw := httptest.NewRecorder() - err := prod.Produce(rw, data) - assert.NoError(t, err) - assert.Equal(t, consProdYAML, rw.Body.String()) -} - -type failReader struct { -} - -func (f *failReader) Read(p []byte) (n int, err error) { - return 0, errors.New("expected") -} -func TestFailYAMLReader(t *testing.T) { - cons := YAMLConsumer() - assert.Error(t, cons.Consume(&failReader{}, nil)) -} diff --git a/vendor/github.com/go-openapi/spec/.editorconfig b/vendor/github.com/go-openapi/spec/.editorconfig deleted file mode 100644 index 3152da69a..000000000 --- a/vendor/github.com/go-openapi/spec/.editorconfig +++ /dev/null @@ -1,26 +0,0 @@ -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -end_of_line = lf -insert_final_newline = true -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true - -# Set default charset -[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] -charset = utf-8 - -# Tab indentation (no size specified) -[*.go] -indent_style = tab - -[*.md] -trim_trailing_whitespace = false - -# Matches the exact files either package.json or .travis.yml -[{package.json,.travis.yml}] -indent_style = space -indent_size = 2 diff --git a/vendor/github.com/go-openapi/spec/.github/CONTRIBUTING.md b/vendor/github.com/go-openapi/spec/.github/CONTRIBUTING.md deleted file mode 100644 index 7dea4240d..000000000 --- a/vendor/github.com/go-openapi/spec/.github/CONTRIBUTING.md +++ /dev/null @@ -1,117 +0,0 @@ -## Contribution Guidelines - -### Pull requests are always welcome - -We are always thrilled to receive pull requests, and do our best to -process them as fast as possible. Not sure if that typo is worth a pull -request? Do it! We will appreciate it. - -If your pull request is not accepted on the first try, don't be -discouraged! If there's a problem with the implementation, hopefully you -received feedback on what to improve. - -We're trying very hard to keep go-swagger lean and focused. We don't want it -to do everything for everybody. This means that we might decide against -incorporating a new feature. However, there might be a way to implement -that feature *on top of* go-swagger. - - -### Conventions - -Fork the repo and make changes on your fork in a feature branch: - -- If it's a bugfix branch, name it XXX-something where XXX is the number of the - issue -- If it's a feature branch, create an enhancement issue to announce your - intentions, and name it XXX-something where XXX is the number of the issue. - -Submit unit tests for your changes. Go has a great test framework built in; use -it! Take a look at existing tests for inspiration. Run the full test suite on -your branch before submitting a pull request. - -Update the documentation when creating or modifying features. Test -your documentation changes for clarity, concision, and correctness, as -well as a clean documentation build. See ``docs/README.md`` for more -information on building the docs and how docs get released. - -Write clean code. Universally formatted code promotes ease of writing, reading, -and maintenance. Always run `gofmt -s -w file.go` on each changed file before -committing your changes. Most editors have plugins that do this automatically. - -Pull requests descriptions should be as clear as possible and include a -reference to all the issues that they address. - -Pull requests must not contain commits from other users or branches. - -Commit messages must start with a capitalized and short summary (max. 50 -chars) written in the imperative, followed by an optional, more detailed -explanatory text which is separated from the summary by an empty line. - -Code review comments may be added to your pull request. Discuss, then make the -suggested modifications and push additional commits to your feature branch. Be -sure to post a comment after pushing. The new commits will show up in the pull -request automatically, but the reviewers will not be notified unless you -comment. - -Before the pull request is merged, make sure that you squash your commits into -logical units of work using `git rebase -i` and `git push -f`. After every -commit the test suite should be passing. Include documentation changes in the -same commit so that a revert would remove all traces of the feature or fix. - -Commits that fix or close an issue should include a reference like `Closes #XXX` -or `Fixes #XXX`, which will automatically close the issue when merged. - -### Sign your work - -The sign-off is a simple line at the end of the explanation for the -patch, which certifies that you wrote it or otherwise have the right to -pass it on as an open-source patch. The rules are pretty simple: if you -can certify the below (from -[developercertificate.org](http://developercertificate.org/)): - -``` -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` - -then you just add a line to every git commit message: - - Signed-off-by: Joe Smith - -using your real name (sorry, no pseudonyms or anonymous contributions.) - -You can add the sign off when creating the git commit via `git commit -s`. diff --git a/vendor/github.com/go-openapi/spec/.gitignore b/vendor/github.com/go-openapi/spec/.gitignore deleted file mode 100644 index dd91ed6a0..000000000 --- a/vendor/github.com/go-openapi/spec/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -secrets.yml -coverage.out diff --git a/vendor/github.com/go-openapi/spec/.travis.yml b/vendor/github.com/go-openapi/spec/.travis.yml deleted file mode 100644 index ea80ef2a7..000000000 --- a/vendor/github.com/go-openapi/spec/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -language: go -go: -- 1.7 -install: -- go get -u github.com/stretchr/testify -- go get -u github.com/go-openapi/swag -- go get -u gopkg.in/yaml.v2 -- go get -u github.com/go-openapi/jsonpointer -- go get -u github.com/go-openapi/jsonreference -script: -- go test -v -race -cover -coverprofile=coverage.txt -covermode=atomic ./... -after_success: -- bash <(curl -s https://codecov.io/bash) -notifications: - slack: - secure: QUWvCkBBK09GF7YtEvHHVt70JOkdlNBG0nIKu/5qc4/nW5HP8I2w0SEf/XR2je0eED1Qe3L/AfMCWwrEj+IUZc3l4v+ju8X8R3Lomhme0Eb0jd1MTMCuPcBT47YCj0M7RON7vXtbFfm1hFJ/jLe5+9FXz0hpXsR24PJc5ZIi/ogNwkaPqG4BmndzecpSh0vc2FJPZUD9LT0I09REY/vXR0oQAalLkW0asGD5taHZTUZq/kBpsNxaAFrLM23i4mUcf33M5fjLpvx5LRICrX/57XpBrDh2TooBU6Qj3CgoY0uPRYUmSNxbVx1czNzl2JtEpb5yjoxfVPQeg0BvQM00G8LJINISR+ohrjhkZmAqchDupAX+yFrxTtORa78CtnIL6z/aTNlgwwVD8kvL/1pFA/JWYmKDmz93mV/+6wubGzNSQCstzjkFA4/iZEKewKUoRIAi/fxyscP6L/rCpmY/4llZZvrnyTqVbt6URWpopUpH4rwYqreXAtJxJsfBJIeSmUIiDIOMGkCTvyTEW3fWGmGoqWtSHLoaWDyAIGb7azb+KvfpWtEcoPFWfSWU+LGee0A/YsUhBl7ADB9A0CJEuR8q4BPpKpfLwPKSiKSAXL7zDkyjExyhtgqbSl2jS+rKIHOZNL8JkCcTP2MKMVd563C5rC5FMKqu3S9m2b6380E= diff --git a/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e..000000000 --- a/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/spec/LICENSE b/vendor/github.com/go-openapi/spec/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/go-openapi/spec/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/go-openapi/spec/README.md b/vendor/github.com/go-openapi/spec/README.md deleted file mode 100644 index 1d1622082..000000000 --- a/vendor/github.com/go-openapi/spec/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# OAI object model [![Build Status](https://travis-ci.org/go-openapi/spec.svg?branch=master)](https://travis-ci.org/go-openapi/spec) [![codecov](https://codecov.io/gh/go-openapi/spec/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/spec) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/spec/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/spec?status.svg)](http://godoc.org/github.com/go-openapi/spec) - -The object model for OpenAPI specification documents diff --git a/vendor/github.com/go-openapi/spec/auth_test.go b/vendor/github.com/go-openapi/spec/auth_test.go deleted file mode 100644 index 5449fdec9..000000000 --- a/vendor/github.com/go-openapi/spec/auth_test.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "testing" -) - -func TestSerialization_AuthSerialization(t *testing.T) { - assertSerializeJSON(t, BasicAuth(), `{"type":"basic"}`) - - assertSerializeJSON(t, APIKeyAuth("api-key", "header"), `{"type":"apiKey","name":"api-key","in":"header"}`) - - assertSerializeJSON( - t, - OAuth2Implicit("http://foo.com/authorization"), - `{"type":"oauth2","flow":"implicit","authorizationUrl":"http://foo.com/authorization"}`) - - assertSerializeJSON( - t, - OAuth2Password("http://foo.com/token"), - `{"type":"oauth2","flow":"password","tokenUrl":"http://foo.com/token"}`) - - assertSerializeJSON(t, - OAuth2Application("http://foo.com/token"), - `{"type":"oauth2","flow":"application","tokenUrl":"http://foo.com/token"}`) - - assertSerializeJSON( - t, - OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token"), - `{"type":"oauth2","flow":"accessCode","authorizationUrl":"http://foo.com/authorization","tokenUrl":"http://foo.com/token"}`) - - auth1 := OAuth2Implicit("http://foo.com/authorization") - auth1.AddScope("email", "read your email") - assertSerializeJSON( - t, - auth1, - `{"type":"oauth2","flow":"implicit","authorizationUrl":"http://foo.com/authorization","scopes":{"email":"read your email"}}`) - - auth2 := OAuth2Password("http://foo.com/authorization") - auth2.AddScope("email", "read your email") - assertSerializeJSON( - t, - auth2, - `{"type":"oauth2","flow":"password","tokenUrl":"http://foo.com/authorization","scopes":{"email":"read your email"}}`) - - auth3 := OAuth2Application("http://foo.com/token") - auth3.AddScope("email", "read your email") - assertSerializeJSON( - t, - auth3, - `{"type":"oauth2","flow":"application","tokenUrl":"http://foo.com/token","scopes":{"email":"read your email"}}`) - - auth4 := OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token") - auth4.AddScope("email", "read your email") - assertSerializeJSON( - t, - auth4, - `{"type":"oauth2","flow":"accessCode","authorizationUrl":"http://foo.com/authorization","tokenUrl":"http://foo.com/token","scopes":{"email":"read your email"}}`) -} - -func TestSerialization_AuthDeserialization(t *testing.T) { - - assertParsesJSON(t, `{"type":"basic"}`, BasicAuth()) - - assertParsesJSON( - t, - `{"in":"header","name":"api-key","type":"apiKey"}`, - APIKeyAuth("api-key", "header")) - - assertParsesJSON( - t, - `{"authorizationUrl":"http://foo.com/authorization","flow":"implicit","type":"oauth2"}`, - OAuth2Implicit("http://foo.com/authorization")) - - assertParsesJSON( - t, - `{"flow":"password","tokenUrl":"http://foo.com/token","type":"oauth2"}`, - OAuth2Password("http://foo.com/token")) - - assertParsesJSON( - t, - `{"flow":"application","tokenUrl":"http://foo.com/token","type":"oauth2"}`, - OAuth2Application("http://foo.com/token")) - - assertParsesJSON( - t, - `{"authorizationUrl":"http://foo.com/authorization","flow":"accessCode","tokenUrl":"http://foo.com/token","type":"oauth2"}`, - OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token")) - - auth1 := OAuth2Implicit("http://foo.com/authorization") - auth1.AddScope("email", "read your email") - assertParsesJSON(t, - `{"authorizationUrl":"http://foo.com/authorization","flow":"implicit","scopes":{"email":"read your email"},"type":"oauth2"}`, - auth1) - - auth2 := OAuth2Password("http://foo.com/token") - auth2.AddScope("email", "read your email") - assertParsesJSON(t, - `{"flow":"password","scopes":{"email":"read your email"},"tokenUrl":"http://foo.com/token","type":"oauth2"}`, - auth2) - - auth3 := OAuth2Application("http://foo.com/token") - auth3.AddScope("email", "read your email") - assertParsesJSON(t, - `{"flow":"application","scopes":{"email":"read your email"},"tokenUrl":"http://foo.com/token","type":"oauth2"}`, - auth3) - - auth4 := OAuth2AccessToken("http://foo.com/authorization", "http://foo.com/token") - auth4.AddScope("email", "read your email") - assertParsesJSON( - t, - `{"authorizationUrl":"http://foo.com/authorization","flow":"accessCode","scopes":{"email":"read your email"},"tokenUrl":"http://foo.com/token","type":"oauth2"}`, - auth4) - -} diff --git a/vendor/github.com/go-openapi/spec/bindata.go b/vendor/github.com/go-openapi/spec/bindata.go deleted file mode 100644 index 9afb5df19..000000000 --- a/vendor/github.com/go-openapi/spec/bindata.go +++ /dev/null @@ -1,260 +0,0 @@ -// Code generated by go-bindata. -// sources: -// schemas/jsonschema-draft-04.json -// schemas/v2/schema.json -// DO NOT EDIT! - -package spec - -import ( - "bytes" - "compress/gzip" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "strings" - "time" -) - -func bindataRead(data []byte, name string) ([]byte, error) { - gz, err := gzip.NewReader(bytes.NewBuffer(data)) - if err != nil { - return nil, fmt.Errorf("Read %q: %v", name, err) - } - - var buf bytes.Buffer - _, err = io.Copy(&buf, gz) - clErr := gz.Close() - - if err != nil { - return nil, fmt.Errorf("Read %q: %v", name, err) - } - if clErr != nil { - return nil, err - } - - return buf.Bytes(), nil -} - -type asset struct { - bytes []byte - info os.FileInfo -} - -type bindataFileInfo struct { - name string - size int64 - mode os.FileMode - modTime time.Time -} - -func (fi bindataFileInfo) Name() string { - return fi.name -} -func (fi bindataFileInfo) Size() int64 { - return fi.size -} -func (fi bindataFileInfo) Mode() os.FileMode { - return fi.mode -} -func (fi bindataFileInfo) ModTime() time.Time { - return fi.modTime -} -func (fi bindataFileInfo) IsDir() bool { - return false -} -func (fi bindataFileInfo) Sys() interface{} { - return nil -} - -var _jsonschemaDraft04JSON = []byte("\x1f\x8b\x08\x00\x00\x09\x6e\x88\x00\xff\xc4\x57\x3b\x6f\xdb\x3e\x10\xdf\xf3\x29\x08\x26\x63\xf2\x97\xff\x40\x27\x6f\x45\xbb\x18\x68\xd1\x0c\xdd\x0c\x0f\xb4\x75\xb2\x19\x50\xa4\x42\x51\x81\x0d\x43\xdf\xbd\xa0\xa8\x07\x29\x91\x92\x2d\xbb\x8d\x97\x28\xbc\xd7\xef\x8e\xf7\xe2\xf9\x01\x21\x84\x30\x8d\xf1\x12\xe1\x83\x52\xd9\x32\x8a\xde\x72\xc1\x5f\xf2\xdd\x01\x52\xf2\x9f\x90\xfb\x28\x96\x24\x51\x2f\x8b\x2f\x91\x39\x7b\xc4\xcf\x46\xe8\xc9\xfc\x3f\x43\x32\x86\x7c\x27\x69\xa6\xa8\xe0\x5a\xfa\x9b\x90\x80\x0c\x0b\x4a\x41\x91\x5a\x45\xc7\x9d\x50\x4e\x35\x73\x8e\x97\xc8\x20\xae\x08\x86\xed\xab\x94\xe4\xe4\x10\x2a\xa2\x3a\x65\xa0\x95\x93\x8a\xfc\xec\x12\x53\xca\x57\x0a\x52\xad\xef\xff\x1e\x89\xd6\xe7\x67\x84\x9f\x24\x24\x5a\xc5\x23\x46\x65\xcb\x54\x76\xfc\x38\x13\x39\x55\xf4\x03\x56\x5c\xc1\x1e\x64\x18\x04\xad\x19\x86\x30\x68\x5a\xa4\x78\x89\x16\x97\xe8\xff\x0e\x09\x29\x98\x5a\x0c\xed\x10\xc6\x7e\x69\xa8\x6b\x07\x76\x64\x45\x2e\xea\x63\x45\xe5\xb3\x66\x8e\x8d\x4e\x0d\x01\x95\x68\xe3\x85\x91\xd3\x34\x63\xf0\xfb\x94\x41\x3e\x34\x0d\xbc\x72\x60\xdd\x46\x1a\xe1\xad\x10\x0c\x08\xd7\x9f\xad\xe3\x08\xf3\x82\x31\xf3\x37\xdd\x9a\x13\xb1\x7d\x83\x9d\xd2\x5f\xb9\x92\x94\xef\x71\xc8\x7e\x45\x9d\x73\xcf\xd6\x65\x36\x7c\x8d\xa9\xf2\xf2\x94\x28\x38\x7d\x2f\xa0\xa1\x2a\x59\x40\x07\xf3\xc1\x02\xdb\xda\x68\x1c\x33\xa7\x99\x14\x19\x48\x45\x7b\xd1\x33\x45\x17\xf0\xa6\x46\xd9\x03\x92\x08\x99\x12\x7d\x57\xb8\x90\x14\x7b\x63\xd5\x15\xe5\xbd\x35\x2b\xaa\x18\x4c\xea\xf5\x8a\xba\xf5\x3e\x4b\x41\x93\xa5\x67\xfb\x38\x2d\x98\xa2\x19\x83\x2a\xf7\x03\x6a\x9b\x74\x0b\x56\x5e\x8f\x02\xc7\x1d\x2b\x72\xfa\x01\x3f\x5b\x16\xf7\xc6\x6d\xfb\xe4\x58\xb3\x8c\x1b\xf7\x0a\x77\x86\xa6\xb4\xb4\xf5\xe4\x92\xbb\xa0\x24\x84\xe5\x01\x84\xad\x13\x37\x21\x9c\xd2\x72\x0b\x42\x72\xfc\x01\x7c\xaf\x0e\xbd\x9e\x3b\xd5\xbc\x1c\x1f\xaf\xd6\xd0\xb6\x52\xb7\xdf\x12\xa5\x40\x4e\xe7\x68\xb0\x78\x24\xec\xe1\xe8\x0f\x26\x89\xe3\x0a\x0a\x61\x4d\x23\xe9\xf7\x70\x7e\x32\x3d\xdc\x39\xd6\xbf\xf3\x30\xd0\xfd\xf6\x55\xb3\x79\x27\x96\xfe\x6d\x82\x37\x73\xf6\x8f\x36\x3a\x03\xa4\x6d\x7d\x1c\x9e\x73\x35\xf6\x18\xbf\x15\x76\x4a\x8e\x2b\xcf\x00\xbf\x2a\x99\xae\x55\xe0\xcf\x25\x77\x68\xfc\x95\xba\x79\x75\x06\xcb\x5c\x77\x67\x69\xf1\xfb\x2c\xe1\xbd\xa0\x12\xe2\x31\x45\xf6\x30\x0f\x14\xc8\xab\x7f\x60\x4e\x27\xe0\x3f\xaf\x92\xd0\x6a\x8a\x82\xdb\xc0\xa4\xbb\x63\x65\x34\x0d\x28\xb0\x6b\x7c\x1e\x1e\xd3\x51\xc7\x6e\xf4\x33\x60\xc5\x90\x01\x8f\x81\xef\xee\x88\x68\x90\x69\x23\xb9\x8a\x2e\x69\x98\x7d\xa6\x91\x32\x1a\xc8\x6e\x9c\x13\x7f\x10\xea\xcd\xfd\x4e\xef\xa6\xb1\x25\xd9\xde\x22\x8d\xfa\x59\x63\xc5\x0d\x80\xf5\x28\xf1\xd6\xb9\x37\x9e\xa3\xee\xb5\x4c\xbe\x37\xe0\x55\xc6\x27\x82\x75\x49\xd0\xda\xe0\xb9\x1d\xca\xbf\x5b\xd4\xcf\xbf\x0b\x47\xac\x2d\x59\x07\xfe\x7a\x49\xc1\x61\xa6\x24\x17\x2a\xf0\xbe\x2e\xdb\x17\x7f\xa0\x3c\x7d\x4b\xf3\xba\xdb\xc3\xed\x06\xee\xdb\x5e\xd7\xdd\x42\x5c\x47\xb2\xb3\x68\x75\x8c\xf2\xe1\x4f\x00\x00\x00\xff\xff\x4e\x9b\x8d\xdf\x17\x11\x00\x00") - -func jsonschemaDraft04JSONBytes() ([]byte, error) { - return bindataRead( - _jsonschemaDraft04JSON, - "jsonschema-draft-04.json", - ) -} - -func jsonschemaDraft04JSON() (*asset, error) { - bytes, err := jsonschemaDraft04JSONBytes() - if err != nil { - return nil, err - } - - info := bindataFileInfo{name: "jsonschema-draft-04.json", size: 4375, mode: os.FileMode(420), modTime: time.Unix(1482389892, 0)} - a := &asset{bytes: bytes, info: info} - return a, nil -} - -var _v2SchemaJSON = []byte("\x1f\x8b\x08\x00\x00\x09\x6e\x88\x00\xff\xec\x5d\x4f\x93\xdb\x36\xb2\xbf\xfb\x53\xa0\x14\x57\xd9\xae\xd8\x92\xe3\xf7\x2e\xcf\x97\xd4\xbc\xd8\x49\x66\x37\x5e\x4f\x79\x26\xbb\x87\x78\x5c\x05\x91\x2d\x09\x09\x09\x30\x00\x38\x33\x5a\xef\x7c\xf7\x2d\xf0\x9f\x08\x02\x20\x41\x8a\xd2\xc8\x0e\x0f\xa9\x78\x28\xa0\xd1\xdd\x68\x34\x7e\xdd\xf8\xf7\xf9\x11\x42\x33\x49\x64\x04\xb3\xd7\x68\x76\x86\xfe\x76\xf9\xfe\x1f\xe8\x32\xd8\x40\x8c\xd1\x8a\x71\x74\x79\x8b\xd7\x6b\xe0\xe8\xd5\xfc\x25\x3a\xbb\x38\x9f\xcf\x9e\xab\x0a\x24\x54\xa5\x37\x52\x26\xaf\x17\x0b\x91\x17\x99\x13\xb6\xb8\x79\xb5\x10\x59\xdd\xf9\xef\x82\xd1\x6f\xf2\xc2\x8f\xf3\x4f\xb5\x1a\xea\xc7\x17\x45\x41\xc6\xd7\x8b\x90\xe3\x95\x7c\xf1\xf2\x7f\x8b\xca\x45\x3d\xb9\x4d\x32\xa6\xd8\xf2\x77\x08\x64\xfe\x8d\xc3\x9f\x29\xe1\xa0\x9a\xff\xed\x11\x42\x08\xcd\x8a\xd6\xb3\x9f\x15\x67\x74\xc5\xca\x7f\x27\x58\x6e\xc4\xec\x11\x42\xd7\x59\x5d\x1c\x86\x44\x12\x46\x71\x74\xc1\x59\x02\x5c\x12\x10\xb3\xd7\x68\x85\x23\x01\x59\x81\x04\x4b\x09\x9c\x6a\xbf\x7e\xce\x49\x7d\xba\x7b\x51\xfd\xa1\x44\xe2\xb0\x52\xac\x7d\xb3\x08\x61\x45\x68\x46\x56\x2c\x6e\x80\x86\x8c\xbf\xbd\x93\x40\x05\x61\x74\x96\x95\xbe\x7f\x84\xd0\x7d\x4e\xde\x42\xb7\xe4\xbe\x46\xbb\x14\x5b\x48\x4e\xe8\xba\x90\x05\xa1\x19\xd0\x34\xae\xc4\xce\xbe\xbc\x9a\xbf\x9c\x15\x7f\x5d\x57\xc5\x42\x10\x01\x27\x89\xe2\x48\x51\xb9\xda\x40\xd5\x87\x37\xc0\x15\x5f\x88\xad\x90\xdc\x10\x81\x42\x16\xa4\x31\x50\x39\x2f\x38\xad\xab\xb0\x53\xd8\xac\x94\x56\x6f\xc3\x84\xf4\x11\xa4\x50\xb3\xfa\xe9\xd3\x6f\x9f\x3e\xdf\x2f\xd0\xeb\x8f\x1f\x3f\x7e\xbc\xfe\xf6\xe9\xf7\xaf\x5f\x7f\xfc\x18\x7e\xfb\xec\xfb\xc7\xb3\x36\x79\x54\x43\xe8\x29\xc5\x31\x20\xc6\x11\x49\x9e\xe5\x12\x41\x66\xa0\xe8\xed\x1d\x8e\x93\x08\x5e\xa3\x27\x3b\xc3\x7c\xa2\x73\xba\xc4\x02\x2e\xb0\xdc\xf4\xe5\x76\xd1\xca\x96\xa2\x8a\x94\xcd\x21\xc9\x6c\xec\x2c\x70\x42\x9e\x34\x74\x9d\x19\x7c\xcd\x20\x9c\xea\x2e\x0a\xfe\x42\x84\xd4\x29\x04\x8c\x8a\xb4\x41\xa2\xc1\xdc\x19\x8a\x88\x90\x4a\x49\xef\xce\xdf\xbd\x45\x4a\x52\x81\x70\x10\x40\x22\x21\x44\xcb\x6d\xc5\xec\x4e\x3c\x1c\x45\xef\x57\x9a\xb5\x7d\xae\xfe\xe5\xe4\x31\x86\x90\xe0\xab\x6d\x02\x3b\x2e\xcb\x11\x90\xd9\xa8\xc6\x77\xc2\x59\x98\x06\xfd\xf9\x2e\x78\x45\x01\xa6\xa8\xa0\x71\x5c\xbe\x33\xa7\xd2\xd9\x5f\x95\xef\xd9\xd5\xac\xfd\xdc\x5d\xbf\x5e\xb8\xd1\x3e\xc7\x31\x48\xe0\x5e\x4c\x14\x65\xdf\xb8\xa8\x71\x10\x09\xa3\xc2\xc7\x02\xcb\xa2\x4e\x5a\x02\x82\x94\x13\xb9\xf5\x30\xe6\xb2\xa4\xb5\xfe\x9b\x3e\x7a\xb2\x55\xd2\xa8\x4a\xbc\x16\xb6\x71\x8e\x39\xc7\xdb\x9d\xe1\x10\x09\x71\xbd\x9c\xb3\x41\x89\xd7\xa5\x89\xdc\x57\xb5\x53\x4a\xfe\x4c\xe1\xbc\xa0\x21\x79\x0a\x1a\x0f\x70\xa7\x5c\x08\x8e\xde\xb0\xc0\x43\x24\xad\x74\x63\x0e\xb1\xd9\x90\xe1\xb0\x2d\x13\xa7\x6d\x78\xfd\x04\x14\x38\x8e\x90\xaa\xce\x63\xac\x3e\x23\xbc\x64\xa9\xb4\xf8\x03\x63\xde\xcd\xbe\x16\x13\x4a\x55\xac\x82\x12\xc6\xac\xd4\x35\xf7\x22\xd4\x3a\xff\x22\x73\x0e\x6e\x51\xa0\x75\x1e\xae\x8f\xe8\x5d\xc7\x59\xe6\xe4\x9a\x18\x8d\xd6\x1c\x53\x84\x4d\xb7\x67\x28\x37\x09\x84\x69\x88\x12\x0e\x01\x11\x80\x32\xa2\xf5\xb9\xaa\xc6\xd9\x73\x53\xab\xfb\xb4\x2e\x20\xc6\x54\x92\xa0\x9a\xf3\x69\x1a\x2f\x81\x77\x37\xae\x53\x1a\xce\x40\xc4\xa8\x82\x1c\xb5\xef\xda\x24\x7d\xb9\x61\x69\x14\xa2\x25\xa0\x90\xac\x56\xc0\x81\x4a\xb4\xe2\x2c\xce\x4a\x64\x7a\x9a\x23\xf4\x13\x91\x3f\xa7\x4b\xf4\x63\x84\x6f\x18\x87\x10\xbd\xc3\xfc\x8f\x90\xdd\x52\x44\x04\xc2\x51\xc4\x6e\x21\x74\x48\x21\x81\xc7\xe2\xfd\xea\x12\xf8\x0d\x09\xf6\xe9\x47\x35\xaf\x67\xc4\x14\xf7\x22\x27\x97\xe1\xe2\x76\x2d\x06\x8c\x4a\x1c\x48\x3f\x73\x2d\x0b\x5b\x29\x45\x24\x00\x2a\x0c\x11\xec\x94\xca\xc2\xa6\xc1\x37\x21\x43\x83\x3b\x5f\x97\xf1\x43\x5e\x53\x73\x19\xa5\x36\xd8\x2d\x05\x2e\x34\x0b\xeb\x39\xfc\x1d\x63\x51\x01\xbd\x3d\xbb\x90\x84\x40\x25\x59\x6d\x09\x5d\xa3\x1c\x37\xe6\x5c\x16\x9a\x40\x09\x70\xc1\xe8\x82\xf1\x35\xa6\xe4\xdf\x99\x5c\x8e\x9e\x4d\x79\xb4\x27\x2f\xbf\x7e\xf8\x05\x25\x8c\x50\xa9\x98\x29\x90\x62\x60\xea\x75\xae\x13\xca\xbf\x2b\x1a\x29\x27\x76\xd6\x20\xc6\x64\x5f\xe6\x32\x1a\x08\x87\x21\x07\x21\xbc\xb4\xe4\xe0\x32\x67\xa6\xcd\xf3\x1e\xcd\xd9\x6b\xb6\x6f\x8e\x27\xa7\xed\xdb\xe7\xbc\xcc\x1a\x07\xce\x6f\x87\x33\xf0\xba\x51\x17\x22\x66\x78\x79\x8e\xce\xe5\x13\x81\x80\x06\x2c\xe5\x78\x0d\xa1\xb2\xb8\x54\xa8\x79\x09\xbd\xbf\x3c\x47\x01\x8b\x13\x2c\xc9\x32\xaa\xaa\x1d\xd5\xee\xab\x36\xbd\x6c\xfd\x54\x6c\xc8\x08\x01\x3c\xbd\xe7\x07\x88\xb0\x24\x37\x79\x90\x28\x4a\x1d\x10\x1a\x92\x1b\x12\xa6\x38\x42\x40\xc3\x4c\x43\x62\x8e\xae\x36\xb0\x45\x71\x2a\xa4\x9a\x23\x79\x59\xb1\xa8\xf2\xa4\x0c\x60\x9f\xcc\x8d\x40\xf5\x80\xca\xa8\x99\xc3\xa7\x85\x1f\x31\x25\xa9\x82\xc5\x6d\xbd\xd8\x36\x76\x7c\x02\x28\x97\xf6\x1d\x74\x3b\x11\x7e\x91\xae\x32\xf8\x6c\xf4\xe6\x7b\x9a\xa5\x1f\x62\xc6\x21\xcf\x9a\xe5\xed\x8b\x02\xf3\x2c\x33\x33\xdf\x00\xca\xc9\x09\xb4\x04\xf5\xa5\x08\xd7\xc3\x02\x18\x66\xf1\xab\x1e\x83\x37\x4c\xcd\x12\xc1\x1d\x50\xf6\xaa\xbd\xfe\xe2\x73\x48\x38\x08\xa0\x32\x9b\x18\x44\x86\x0b\x6a\xc1\xaa\x26\x96\x2d\x96\x3c\xa0\x54\x65\x73\x87\x15\xca\x15\xe5\xf5\x94\x46\x9f\x33\x1a\x0c\x9a\xb1\x5a\xd9\x6a\x95\xcd\xcb\x7e\xec\x9a\xc5\x94\x3b\x37\x26\x31\xd7\xfc\xe4\x1f\x13\x8c\x31\x75\x9c\xba\xf7\x87\x3c\xa1\xb7\x4f\x17\x1b\x09\x82\x98\xc4\x70\x95\xd3\xe8\x4c\x48\x5a\xa6\xd6\x2a\x3d\x56\x42\x80\x9f\xaf\xae\x2e\x50\x0c\x42\xe0\x35\x34\x3c\x8a\x62\x03\x37\xba\xb2\x27\x04\xda\x25\x8d\x06\xe2\xa0\x13\x8a\xf3\xf5\xec\x10\x72\x67\x88\x90\x3d\x4b\x64\xeb\xaa\xda\x8f\xf7\x5a\x75\x47\x9a\xa8\x51\x70\x26\xd2\x38\xc6\x7c\xbb\x57\xfc\xbd\xe4\x04\x56\xa8\xa0\x54\x9a\x45\xd5\xf7\x0f\x16\xfc\x57\x1c\x3c\xdf\x23\xba\x77\x38\xda\x16\x4b\x31\x53\x6a\x4d\x9a\x15\x63\xe7\xe1\x18\x69\x9f\x22\xe0\x24\xbb\x94\x4b\x97\xee\x2d\xf9\x70\x87\x72\x7b\xe6\xc4\x33\x2a\x66\x5e\x1c\x35\x72\xe3\x2d\xda\x73\xe4\xc7\x51\x6d\xa4\xa1\x2a\x4f\xde\x94\xcb\xb2\x3e\x31\x48\xae\x82\xce\xc9\xc8\x65\xcd\xc3\xb7\x34\xb6\x2b\xdf\x58\x65\x78\x6e\x73\xac\x5e\x24\x0d\x3f\xdc\x70\x23\xc6\xda\x52\x0b\x2d\x63\x7d\xa9\x49\x2d\x54\x48\x28\xc0\x12\x9c\xe3\x63\xc9\x58\x04\x98\x36\x07\xc8\x0a\xa7\x91\xd4\xf0\xbc\xc1\xa8\xb9\x70\xd0\xc6\xa9\xb6\x78\x80\x5a\xa3\xb4\x2c\xf4\x18\x0b\x8a\x9d\xd0\xb4\x55\x10\xee\x0d\xc5\xd6\xe0\x99\x93\xdc\xa1\x04\xbb\xf1\xa7\x23\xd1\xd1\x97\x8c\x87\x13\x0a\x21\x02\xe9\x99\x25\xed\x20\xc5\x92\x66\x3c\x32\x9c\xd6\x06\xb0\x31\x5c\x86\x29\x0a\xcb\x60\x33\x12\xa5\x91\xfc\x96\x75\xd0\x59\xd7\x13\xbd\xd3\x23\x79\xdd\x2a\x90\xa6\x38\x06\x91\x39\x7f\x20\x72\x03\x1c\x2d\x01\x61\xba\x45\x37\x38\x22\x61\x8e\x71\x85\xc4\x32\x15\x28\x60\x61\x16\xb8\x3d\x29\xdc\x4d\x3d\x2f\x12\x13\x7d\xc8\x7e\x37\xee\xa8\x7f\xfa\xdb\xcb\x17\xff\x77\xfd\xf9\x7f\xee\x9f\x3d\xfe\xcf\xa7\xa7\x45\xfb\xcf\x1e\xf7\xf3\xe0\xff\xc4\x51\x0a\x8e\x4c\xcb\x01\xdc\x0a\x65\xb2\x01\x83\xed\x3d\xe4\xa9\xa3\x4e\x2d\x59\xc5\xe8\x2f\x48\x7d\x5a\x6e\x37\xbf\x5c\x9f\x35\x13\x64\x14\xfa\xef\x0b\x68\xa6\x0d\xb4\x8e\xf1\xa8\xff\xbb\x60\xf4\x03\x64\xab\x5b\x81\x65\x51\xe6\xda\xca\xfa\xf0\xb0\xac\x3e\x9c\xca\x26\x0e\x1d\xdb\x57\x5b\xbb\xb4\x9a\xa6\xb6\x9b\x1a\x6b\xd1\x9a\x9e\x7e\x33\x9a\xec\x41\x69\x45\x22\xb8\xb4\x51\xeb\x04\x77\xca\x6f\x7b\x7b\xc8\xb2\xb0\x95\x92\x25\x5b\xd0\x42\xaa\x2a\xdd\x32\x78\x4f\x0c\xab\x68\x46\x6c\xea\x6d\xf4\x5c\x5e\xde\xc4\xac\xa5\xf9\xd1\x00\x9f\x7d\x98\x65\x24\xbd\xc7\x97\xd4\xb3\x3a\xa8\x2b\xa0\x34\x76\xf9\x65\x5f\x2d\x25\x95\x1b\xcf\xd6\xf4\x9b\x5f\x09\x95\xb0\x36\x3f\xdb\xd0\x39\x2a\x93\x1c\x9d\x03\xa2\x4a\xca\xf5\xf6\x10\xb6\x94\x89\x0b\x6a\x70\x12\x13\x49\x6e\x40\xe4\x29\x12\x2b\xbd\x80\x45\x11\x04\xaa\xc2\x8f\x56\x9e\x5c\x6b\xec\x8d\x5a\x0e\x14\x59\x06\x2b\x1e\x24\xcb\xc2\x56\x4a\x31\xbe\x23\x71\x1a\xfb\x51\x2a\x0b\x3b\x1c\x48\x10\xa5\x82\xdc\xc0\xbb\x3e\x24\x8d\x5a\x76\x2e\x09\xed\xc1\x65\x51\xb8\x83\xcb\x3e\x24\x8d\x5a\x2e\x5d\xfe\x02\x74\x2d\x3d\xf1\xef\xae\xb8\x4b\xe6\x5e\xd4\xaa\xe2\x2e\x5c\x5e\xec\x0e\xf5\x5b\x0c\xcb\x0a\xbb\xa4\x3c\xf7\x1f\x2a\x55\x69\x97\x8c\x7d\x68\x95\xa5\xad\xb4\xf4\x9c\xa5\x07\xb9\x7a\x05\xbb\xad\x50\x6f\xfb\xa0\x4e\x9b\x48\x23\x49\x92\x28\x87\x19\x3e\x32\xee\xca\x3b\x46\x7e\x7f\x18\x64\xcc\xcc\x0f\x34\xe9\x36\x8b\xb7\x6c\xa8\xa5\x5b\x54\x4c\x54\x5b\x15\x3a\xf1\x6c\x2d\xfe\x96\xc8\x0d\xba\x7b\x81\x88\xc8\x23\xab\xee\x7d\x3b\x92\xa7\x60\x29\xe3\xdc\xff\xb8\x64\xe1\xf6\xa2\x5a\x59\xdc\x6f\xeb\x45\x7d\x6a\xd1\x76\x1e\xea\xb8\xf1\xfa\x14\xd3\x36\x63\xe5\xd7\xf3\xe4\xbe\x25\xbd\x5e\x05\xeb\x73\x74\xb5\x21\x2a\x2e\x4e\xa3\x30\xdf\xbf\x43\x28\x2a\xd1\xa5\x2a\x9d\x8a\xfd\x76\xd8\x8d\xbc\x67\x65\xc7\xb8\x03\x45\xec\xa3\xb0\x37\x8a\x70\x4c\x68\x91\x51\x8e\x58\x80\xed\x4a\xf3\x81\x62\xca\x96\xbb\xf1\x52\xcd\x80\xfb\xe4\x4a\x5d\x6c\xdf\x6e\x20\x4b\x80\x30\x8e\x28\x93\xf9\xe9\x8d\x8a\x6d\xd5\x59\x65\x7b\xaa\x44\x9e\xc0\xc2\xd1\x7c\x40\x26\xd6\x1a\xce\xf9\xc5\x69\x7b\x6c\xec\xc8\x71\x7b\xe5\x21\x2e\xd3\xe5\x65\x93\x91\x53\x0b\x7b\x3a\xc7\xfa\x17\x6a\x01\xa7\x33\xd0\xf4\x40\x0f\x39\x87\xda\xe4\x54\x87\x3a\xd5\xe3\xc7\xa6\x8e\x20\xd4\x11\xb2\x4e\xb1\xe9\x14\x9b\x4e\xb1\xe9\x14\x9b\xfe\x15\x63\xd3\x47\xf5\xff\x97\x38\xe9\xcf\x14\xf8\x76\x82\x49\x13\x4c\xaa\x7d\xcd\x6c\x62\x42\x49\x87\x43\x49\x19\x33\x6f\xe3\x44\x6e\x9b\xab\x8a\x3e\x86\xaa\x99\x52\x1b\x5b\x59\x33\x02\x09\xa0\x21\xa1\x6b\x84\x6b\x66\xbb\xdc\x16\x0c\xd3\x68\xab\xec\x36\x4b\xd8\x60\x8a\x40\x31\x85\x6e\x14\x57\x13\xc2\xfb\x92\x10\xde\xbf\x88\xdc\xbc\x53\x5e\x7f\x82\x7a\x13\xd4\x9b\xa0\xde\x04\xf5\x90\x01\xf5\x94\xcb\x7b\x83\x25\x9e\xd0\xde\x84\xf6\x6a\x5f\x4b\xb3\x98\x00\xdf\x04\xf8\x6c\xbc\x7f\x19\x80\xaf\xf1\x71\x45\x22\x98\x40\xe0\x04\x02\x27\x10\xd8\x29\xf5\x04\x02\xff\x4a\x20\x30\xc1\x72\xf3\x65\x02\x40\xd7\xc1\xd1\xe2\x6b\xf1\xa9\x7b\xfb\xe4\x20\xc0\x68\x9d\xd4\xb4\xd3\x96\xb5\xa6\xd1\x41\x20\xe6\x89\xc3\x48\x65\x58\x13\x84\x9c\x56\x56\x3b\x0c\xe0\x6b\x83\x5c\x13\xd2\x9a\x90\xd6\x84\xb4\x26\xa4\x85\x0c\xa4\x45\x19\xfd\xff\x63\x6c\x52\xb5\x1f\x1e\x19\x74\x3a\xcd\xb9\x69\xce\xa6\x3a\x0f\x7a\x2d\x19\xc7\x81\x14\x5d\xcb\xd5\x03\xc9\x39\xd0\xb0\xd1\xb3\xcd\xfb\x7a\x2d\x5d\x3a\x48\xe1\xfa\x2e\xe6\x81\x42\x18\x86\xd6\xc1\xbe\xb1\x23\xd3\xf7\x34\xed\x19\x0a\x0b\xc4\x48\x44\xfd\x22\x50\xb6\x42\x58\xbb\xe5\x3d\xa7\x73\xd4\x8b\xc4\x8c\x70\x61\xec\x73\xee\xc3\x81\x8b\xf5\xe2\xd7\x52\x3e\xcf\xeb\xeb\x17\x3b\x71\x16\xda\x7d\xb8\xde\xf0\x7a\x8f\x06\x2d\xa7\x40\x7b\xc1\x9d\x41\x4d\xb6\x61\xa2\x4e\x9f\x3d\xa0\xc5\xae\xe3\x1c\x1d\x40\x6c\x48\x8b\x63\xa0\xb5\x01\xed\x8e\x02\xe9\x86\xc8\x3b\x06\xee\xdb\x4b\xde\xbd\xc0\xa1\x6f\xcb\xda\xfc\xc2\x44\x16\x87\x9c\x17\x31\xd3\x30\x20\x39\x42\xcb\x6f\xf2\xf1\xf4\x72\x10\xf8\x1c\xa0\xf3\xbd\x10\xea\x21\x35\x7d\xe8\x86\xdb\x15\xed\x81\x81\x07\x28\xbb\x13\x28\xc7\xf8\xce\x7d\x8d\xc2\x31\xb4\x7e\x94\xd6\xdb\x55\xef\x4a\xfb\xed\xc3\x40\x3e\xeb\x9f\xe9\x99\x0f\xdf\x08\x65\x88\x27\x73\x86\x31\x9d\x47\xdf\x55\x19\xba\x3d\xee\x15\x0a\xcd\x8c\xaa\x5e\xb9\xf6\x57\x33\x73\x5a\xa1\x89\x7b\x3b\xa0\xb2\xa4\xc2\xf6\xc1\x53\xb5\x00\xca\x23\xe5\xf4\x60\x6a\xb4\x2d\x74\xea\x4e\xed\x3b\xe3\x47\xfb\xed\x82\x3d\x19\xd4\x3b\x6b\xaf\xae\x2b\x2f\x57\xb3\x82\x68\xcb\xed\x88\x2e\xe1\x5c\xd7\x26\xfa\x0a\x65\xe7\xce\x11\x33\xb4\xdd\x66\xe3\x37\xf6\xfa\x70\xd6\x4f\xa1\x21\x51\xd8\x3c\x26\x14\x4b\xc6\x87\x44\x27\x1c\x70\xf8\x9e\x46\xce\xab\x21\x07\x5f\xc1\x76\x17\x1b\x77\xb4\xda\x75\xa0\x0a\x3a\x30\xe1\xf8\x97\x32\x16\x2b\x00\x75\x85\xee\x62\x46\xef\xd3\x85\xb5\x6b\x60\xbe\xf2\x30\x7a\x8c\x0b\x4b\xa6\xd0\xf9\x64\x42\xe7\x07\x41\x41\xe3\x2c\x5d\xf9\x6d\xe9\x39\x98\x3b\x3b\x5d\x67\xd4\x5c\xed\xf2\xf0\x48\x7b\xbd\x2d\x31\xdd\x3f\x34\xad\x44\x76\x51\x9a\x56\x22\xa7\x95\xc8\x69\x25\xf2\xe1\x56\x22\x1f\x00\x32\x6a\x73\x92\xed\xe1\xc6\x7d\x9f\x49\x2c\x69\x7e\xc8\x31\x4c\x0c\xb4\xf2\x54\x3b\x79\x3b\x9e\x4d\xb4\xd1\x18\x3e\x5f\x9a\x93\xa2\x11\xc3\xda\x27\x0b\xaf\x37\x2e\x5c\x37\xfb\xeb\x9a\xd6\xc3\xac\xc3\xcc\xf8\x1e\x5b\x9d\xac\x22\x64\xb7\xed\x26\xb8\xf3\xb9\x3c\xbb\x1f\xe2\xb0\x22\x77\x43\x6a\x62\x29\x39\x59\xa6\xe6\xe5\xcd\x7b\x83\xc0\x5b\x8e\x93\x64\xac\xeb\xca\x4f\x65\xac\x4a\xbc\x1e\xcd\x82\xfa\x3c\x70\x36\xb6\xb5\xed\x79\xef\xec\x68\x00\xff\x54\xfa\xb5\xe3\xf1\xdb\xe1\xbe\xce\x76\x17\xaf\x57\xb6\x6b\x89\x05\x09\xce\x52\xb9\x01\x2a\x49\xbe\xd9\xf4\xd2\xb8\x7a\xbf\x91\x02\xf3\x22\x8c\x13\xf2\x77\xd8\x8e\x43\x8b\xe1\x54\x6e\x5e\x9d\xc7\x49\x44\x02\x22\xc7\xa4\x79\x81\x85\xb8\x65\x3c\x1c\x93\xe6\x59\xa2\xf8\x1c\x51\x95\x05\xd9\x20\x00\x21\x7e\x60\x21\x58\xa9\x56\xff\xbe\xb6\x5a\x5e\x5b\x3f\x1f\xd6\xd3\x3c\xc4\x4d\xba\x99\xb4\x63\x6e\x7d\x3e\x3d\x57\xd2\x18\x5f\x47\xe8\xc3\x06\x8a\x68\x6c\x7f\x3b\x72\x0f\xe7\xe2\x77\x77\xf1\xd0\x99\xab\xdf\x2e\xfe\xd6\xbb\xcd\x1a\xb9\x90\xd1\xaf\xf2\x38\x3d\xdb\x74\xf8\xeb\xe3\xda\xe8\x2a\x62\xb7\xda\x1b\x07\xa9\xdc\x30\x5e\xbc\x68\xfb\x6b\x9f\x97\xf1\xc6\xb1\xd8\x5c\x29\x1e\x49\x30\xc5\xf7\xde\xad\x91\x42\xf9\xdd\xed\x89\x80\x25\xbe\x37\xd7\xe7\x32\x5c\xe6\x35\xac\xd4\x0c\x2d\xf7\x90\xc4\xe3\xf5\xe3\x2f\x7f\x54\x18\x88\xe3\x61\x47\x85\x64\x7f\xc0\xd7\x3f\x1a\x92\x42\xe9\xc7\x1e\x0d\x95\x76\xa7\x51\xa0\x8f\x02\x1b\x46\x9e\x06\x42\xd1\xf2\x01\x07\x02\xde\xe9\x7d\x1a\x0b\xa7\x32\x16\xcc\xc0\xee\xc4\x90\xd2\x5f\x6f\x98\x54\x5d\xf2\x95\xe1\xa7\x69\x10\x3a\x06\xe1\x65\xb3\x17\x47\x58\x78\xd0\x45\xd6\x5b\xd5\x5f\x25\x1d\x71\x49\xa6\x7a\x64\xda\xd0\x6f\xc7\x3a\x4c\xe3\x09\xc0\x6e\x96\x2c\xa7\xa7\x77\x34\x10\x05\x08\x21\x44\x92\x65\x77\xdf\x20\x5c\xbc\xe7\x97\x3f\xf4\x1a\x45\xd6\xe7\x27\x4a\xde\x74\x27\x66\x11\x7d\x70\xba\xd3\x78\xf9\x1e\x0d\xca\xc8\x39\xde\x7c\xb3\xa6\xe1\xbc\xd7\xc1\x6a\x6f\xb3\x0e\x52\xbe\xe4\x98\x8a\x15\x70\x94\x70\x26\x59\xc0\xa2\xf2\x1c\xfb\xd9\xc5\xf9\xbc\xd5\x92\x9c\xa3\xdf\xe6\x1e\xb3\x0d\x49\xba\x87\x50\x5f\x84\xfe\xe9\xd6\xf8\xbb\xe6\xf0\x7a\xeb\xa6\x65\x3b\x86\x8b\x79\x93\xf5\x59\x20\x6e\xb4\xa7\x44\xf4\x3f\xa5\xfe\x67\x42\x12\xdb\xd3\xe7\xbb\xa5\xa3\x8c\x5c\x2b\x97\xbb\xbb\x7f\x8e\xc5\x6e\xed\x43\x5c\xbf\x74\xc8\x8f\xff\xe6\xd6\xbe\x91\xb6\xf5\x95\xe4\xed\x93\xc4\xa8\x5b\xf9\x76\x4d\x35\xb7\xd8\x8c\xb6\x7d\xaf\x72\xe0\xb6\xbd\x01\x63\x9e\x76\xab\x1a\x32\x76\xe4\x8c\x76\xc2\xad\x6c\xa2\x65\xf7\xcf\xf8\xa7\xda\x2a\xb9\x8c\x3d\x3c\xa3\x9d\x64\x33\xe5\x1a\xb5\x2d\xfb\x86\xa2\x5a\x7f\x19\x5b\x7f\xc6\x3f\xd1\x53\xd3\xe2\x41\x5b\xd3\x4f\xf0\xec\xb0\x42\x73\x43\xd2\x68\x27\xd3\x6a\x6a\x34\xf6\x4e\x1e\x52\x8b\x87\x6c\xcc\xae\x44\xfb\x9e\xa7\x51\x4f\x9d\x55\x03\x81\x8e\x67\xfc\xb4\x69\xf0\x3a\x18\xf2\x40\xd0\xf6\xa8\x34\xe3\xc9\x98\xaf\xf6\xda\x24\xd3\xeb\x60\xb9\x0e\xd3\x1f\xa9\xff\xee\x1f\xfd\x37\x00\x00\xff\xff\x69\x5d\x0a\x6a\x39\x9d\x00\x00") - -func v2SchemaJSONBytes() ([]byte, error) { - return bindataRead( - _v2SchemaJSON, - "v2/schema.json", - ) -} - -func v2SchemaJSON() (*asset, error) { - bytes, err := v2SchemaJSONBytes() - if err != nil { - return nil, err - } - - info := bindataFileInfo{name: "v2/schema.json", size: 40249, mode: os.FileMode(420), modTime: time.Unix(1482389892, 0)} - a := &asset{bytes: bytes, info: info} - return a, nil -} - -// Asset loads and returns the asset for the given name. -// It returns an error if the asset could not be found or -// could not be loaded. -func Asset(name string) ([]byte, error) { - cannonicalName := strings.Replace(name, "\\", "/", -1) - if f, ok := _bindata[cannonicalName]; ok { - a, err := f() - if err != nil { - return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err) - } - return a.bytes, nil - } - return nil, fmt.Errorf("Asset %s not found", name) -} - -// MustAsset is like Asset but panics when Asset would return an error. -// It simplifies safe initialization of global variables. -func MustAsset(name string) []byte { - a, err := Asset(name) - if err != nil { - panic("asset: Asset(" + name + "): " + err.Error()) - } - - return a -} - -// AssetInfo loads and returns the asset info for the given name. -// It returns an error if the asset could not be found or -// could not be loaded. -func AssetInfo(name string) (os.FileInfo, error) { - cannonicalName := strings.Replace(name, "\\", "/", -1) - if f, ok := _bindata[cannonicalName]; ok { - a, err := f() - if err != nil { - return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err) - } - return a.info, nil - } - return nil, fmt.Errorf("AssetInfo %s not found", name) -} - -// AssetNames returns the names of the assets. -func AssetNames() []string { - names := make([]string, 0, len(_bindata)) - for name := range _bindata { - names = append(names, name) - } - return names -} - -// _bindata is a table, holding each asset generator, mapped to its name. -var _bindata = map[string]func() (*asset, error){ - "jsonschema-draft-04.json": jsonschemaDraft04JSON, - "v2/schema.json": v2SchemaJSON, -} - -// AssetDir returns the file names below a certain -// directory embedded in the file by go-bindata. -// For example if you run go-bindata on data/... and data contains the -// following hierarchy: -// data/ -// foo.txt -// img/ -// a.png -// b.png -// then AssetDir("data") would return []string{"foo.txt", "img"} -// AssetDir("data/img") would return []string{"a.png", "b.png"} -// AssetDir("foo.txt") and AssetDir("notexist") would return an error -// AssetDir("") will return []string{"data"}. -func AssetDir(name string) ([]string, error) { - node := _bintree - if len(name) != 0 { - cannonicalName := strings.Replace(name, "\\", "/", -1) - pathList := strings.Split(cannonicalName, "/") - for _, p := range pathList { - node = node.Children[p] - if node == nil { - return nil, fmt.Errorf("Asset %s not found", name) - } - } - } - if node.Func != nil { - return nil, fmt.Errorf("Asset %s not found", name) - } - rv := make([]string, 0, len(node.Children)) - for childName := range node.Children { - rv = append(rv, childName) - } - return rv, nil -} - -type bintree struct { - Func func() (*asset, error) - Children map[string]*bintree -} -var _bintree = &bintree{nil, map[string]*bintree{ - "jsonschema-draft-04.json": &bintree{jsonschemaDraft04JSON, map[string]*bintree{}}, - "v2": &bintree{nil, map[string]*bintree{ - "schema.json": &bintree{v2SchemaJSON, map[string]*bintree{}}, - }}, -}} - -// RestoreAsset restores an asset under the given directory -func RestoreAsset(dir, name string) error { - data, err := Asset(name) - if err != nil { - return err - } - info, err := AssetInfo(name) - if err != nil { - return err - } - err = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755)) - if err != nil { - return err - } - err = ioutil.WriteFile(_filePath(dir, name), data, info.Mode()) - if err != nil { - return err - } - err = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime()) - if err != nil { - return err - } - return nil -} - -// RestoreAssets restores an asset under the given directory recursively -func RestoreAssets(dir, name string) error { - children, err := AssetDir(name) - // File - if err != nil { - return RestoreAsset(dir, name) - } - // Dir - for _, child := range children { - err = RestoreAssets(dir, filepath.Join(name, child)) - if err != nil { - return err - } - } - return nil -} - -func _filePath(dir, name string) string { - cannonicalName := strings.Replace(name, "\\", "/", -1) - return filepath.Join(append([]string{dir}, strings.Split(cannonicalName, "/")...)...) -} - diff --git a/vendor/github.com/go-openapi/spec/contact_info.go b/vendor/github.com/go-openapi/spec/contact_info.go deleted file mode 100644 index f285970aa..000000000 --- a/vendor/github.com/go-openapi/spec/contact_info.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -// ContactInfo contact information for the exposed API. -// -// For more information: http://goo.gl/8us55a#contactObject -type ContactInfo struct { - Name string `json:"name,omitempty"` - URL string `json:"url,omitempty"` - Email string `json:"email,omitempty"` -} diff --git a/vendor/github.com/go-openapi/spec/contact_info_test.go b/vendor/github.com/go-openapi/spec/contact_info_test.go deleted file mode 100644 index 5e644d0f0..000000000 --- a/vendor/github.com/go-openapi/spec/contact_info_test.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "testing" -) - -var contactInfoJSON = `{"name":"wordnik api team","url":"http://developer.wordnik.com","email":"some@mailayada.dkdkd"}` -var contactInfoYAML = `name: wordnik api team -url: http://developer.wordnik.com -email: some@mailayada.dkdkd -` -var contactInfo = ContactInfo{ - Name: "wordnik api team", - URL: "http://developer.wordnik.com", - Email: "some@mailayada.dkdkd", -} - -func TestIntegrationContactInfo(t *testing.T) { - assertSerializeJSON(t, contactInfo, contactInfoJSON) - assertSerializeYAML(t, contactInfo, contactInfoYAML) - assertParsesJSON(t, contactInfoJSON, contactInfo) - assertParsesYAML(t, contactInfoYAML, contactInfo) -} diff --git a/vendor/github.com/go-openapi/spec/expander.go b/vendor/github.com/go-openapi/spec/expander.go deleted file mode 100644 index d8ce4eec1..000000000 --- a/vendor/github.com/go-openapi/spec/expander.go +++ /dev/null @@ -1,1044 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "fmt" - "log" - "net/url" - "os" - "path" - "path/filepath" - "reflect" - "strings" - "sync" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -var ( - // Debug enables logging when SWAGGER_DEBUG env var is not empty - Debug = os.Getenv("SWAGGER_DEBUG") != "" -) - -// ExpandOptions provides options for expand. -type ExpandOptions struct { - RelativeBase string - SkipSchemas bool - ContinueOnError bool -} - -// ResolutionCache a cache for resolving urls -type ResolutionCache interface { - Get(string) (interface{}, bool) - Set(string, interface{}) -} - -type simpleCache struct { - lock sync.Mutex - store map[string]interface{} -} - -var resCache ResolutionCache - -func init() { - resCache = initResolutionCache() -} - -func initResolutionCache() ResolutionCache { - return &simpleCache{store: map[string]interface{}{ - "http://swagger.io/v2/schema.json": MustLoadSwagger20Schema(), - "http://json-schema.org/draft-04/schema": MustLoadJSONSchemaDraft04(), - }} -} - -func (s *simpleCache) Get(uri string) (interface{}, bool) { - debugLog("getting %q from resolution cache", uri) - s.lock.Lock() - v, ok := s.store[uri] - debugLog("got %q from resolution cache: %t", uri, ok) - - s.lock.Unlock() - return v, ok -} - -func (s *simpleCache) Set(uri string, data interface{}) { - s.lock.Lock() - s.store[uri] = data - s.lock.Unlock() -} - -// ResolveRefWithBase resolves a reference against a context root with preservation of base path -func ResolveRefWithBase(root interface{}, ref *Ref, opts *ExpandOptions) (*Schema, error) { - resolver, err := defaultSchemaLoader(root, opts, nil) - if err != nil { - return nil, err - } - specBasePath := "" - if opts != nil && opts.RelativeBase != "" { - specBasePath, _ = absPath(opts.RelativeBase) - } - - result := new(Schema) - if err := resolver.Resolve(ref, result, specBasePath); err != nil { - return nil, err - } - return result, nil -} - -// ResolveRef resolves a reference against a context root -// ref is guaranteed to be in root (no need to go to external files) -// ResolveRef is ONLY called from the code generation module -func ResolveRef(root interface{}, ref *Ref) (*Schema, error) { - res, _, err := ref.GetPointer().Get(root) - if err != nil { - panic(err) - } - switch sch := res.(type) { - case Schema: - return &sch, nil - case *Schema: - return sch, nil - case map[string]interface{}: - b, _ := json.Marshal(sch) - newSch := new(Schema) - json.Unmarshal(b, newSch) - return newSch, nil - default: - return nil, fmt.Errorf("unknown type for the resolved reference") - } -} - -// ResolveParameter resolves a paramter reference against a context root -func ResolveParameter(root interface{}, ref Ref) (*Parameter, error) { - return ResolveParameterWithBase(root, ref, nil) -} - -// ResolveParameterWithBase resolves a paramter reference against a context root and base path -func ResolveParameterWithBase(root interface{}, ref Ref, opts *ExpandOptions) (*Parameter, error) { - resolver, err := defaultSchemaLoader(root, opts, nil) - if err != nil { - return nil, err - } - - result := new(Parameter) - if err := resolver.Resolve(&ref, result, ""); err != nil { - return nil, err - } - return result, nil -} - -// ResolveResponse resolves response a reference against a context root -func ResolveResponse(root interface{}, ref Ref) (*Response, error) { - return ResolveResponseWithBase(root, ref, nil) -} - -// ResolveResponseWithBase resolves response a reference against a context root and base path -func ResolveResponseWithBase(root interface{}, ref Ref, opts *ExpandOptions) (*Response, error) { - resolver, err := defaultSchemaLoader(root, opts, nil) - if err != nil { - return nil, err - } - - result := new(Response) - if err := resolver.Resolve(&ref, result, ""); err != nil { - return nil, err - } - return result, nil -} - -// ResolveItems resolves header and parameter items reference against a context root and base path -func ResolveItems(root interface{}, ref Ref, opts *ExpandOptions) (*Items, error) { - resolver, err := defaultSchemaLoader(root, opts, nil) - if err != nil { - return nil, err - } - basePath := "" - if opts.RelativeBase != "" { - basePath = opts.RelativeBase - } - result := new(Items) - if err := resolver.Resolve(&ref, result, basePath); err != nil { - return nil, err - } - return result, nil -} - -// ResolvePathItem resolves response a path item against a context root and base path -func ResolvePathItem(root interface{}, ref Ref, opts *ExpandOptions) (*PathItem, error) { - resolver, err := defaultSchemaLoader(root, opts, nil) - if err != nil { - return nil, err - } - basePath := "" - if opts.RelativeBase != "" { - basePath = opts.RelativeBase - } - result := new(PathItem) - if err := resolver.Resolve(&ref, result, basePath); err != nil { - return nil, err - } - return result, nil -} - -type schemaLoader struct { - root interface{} - options *ExpandOptions - cache ResolutionCache - loadDoc func(string) (json.RawMessage, error) -} - -var idPtr, _ = jsonpointer.New("/id") -var refPtr, _ = jsonpointer.New("/$ref") - -// PathLoader function to use when loading remote refs -var PathLoader func(string) (json.RawMessage, error) - -func init() { - PathLoader = func(path string) (json.RawMessage, error) { - data, err := swag.LoadFromFileOrHTTP(path) - if err != nil { - return nil, err - } - return json.RawMessage(data), nil - } -} - -func defaultSchemaLoader( - root interface{}, - expandOptions *ExpandOptions, - cache ResolutionCache) (*schemaLoader, error) { - - if cache == nil { - cache = resCache - } - if expandOptions == nil { - expandOptions = &ExpandOptions{} - } - - return &schemaLoader{ - root: root, - options: expandOptions, - cache: cache, - loadDoc: func(path string) (json.RawMessage, error) { - debugLog("fetching document at %q", path) - return PathLoader(path) - }, - }, nil -} - -func idFromNode(node interface{}) (*Ref, error) { - if idValue, _, err := idPtr.Get(node); err == nil { - if refStr, ok := idValue.(string); ok && refStr != "" { - idRef, err := NewRef(refStr) - if err != nil { - return nil, err - } - return &idRef, nil - } - } - return nil, nil -} - -func nextRef(startingNode interface{}, startingRef *Ref, ptr *jsonpointer.Pointer) *Ref { - if startingRef == nil { - return nil - } - - if ptr == nil { - return startingRef - } - - ret := startingRef - var idRef *Ref - node := startingNode - - for _, tok := range ptr.DecodedTokens() { - node, _, _ = jsonpointer.GetForToken(node, tok) - if node == nil { - break - } - - idRef, _ = idFromNode(node) - if idRef != nil { - nw, err := ret.Inherits(*idRef) - if err != nil { - break - } - ret = nw - } - - refRef, _, _ := refPtr.Get(node) - if refRef != nil { - var rf Ref - switch value := refRef.(type) { - case string: - rf, _ = NewRef(value) - } - nw, err := ret.Inherits(rf) - if err != nil { - break - } - nwURL := nw.GetURL() - if nwURL.Scheme == "file" || (nwURL.Scheme == "" && nwURL.Host == "") { - nwpt := filepath.ToSlash(nwURL.Path) - if filepath.IsAbs(nwpt) { - _, err := os.Stat(nwpt) - if err != nil { - nwURL.Path = filepath.Join(".", nwpt) - } - } - } - - ret = nw - } - - } - - return ret -} - -func debugLog(msg string, args ...interface{}) { - if Debug { - log.Printf(msg, args...) - } -} - -// normalize absolute path for cache. -// on Windows, drive letters should be converted to lower as scheme in net/url.URL -func normalizeAbsPath(path string) string { - u, err := url.Parse(path) - if err != nil { - debugLog("normalize absolute path failed: %s", err) - return path - } - return u.String() -} - -// base or refPath could be a file path or a URL -// given a base absolute path and a ref path, return the absolute path of refPath -// 1) if refPath is absolute, return it -// 2) if refPath is relative, join it with basePath keeping the scheme, hosts, and ports if exists -// base could be a directory or a full file path -func normalizePaths(refPath, base string) string { - refURL, _ := url.Parse(refPath) - if path.IsAbs(refURL.Path) || filepath.IsAbs(refPath) { - // refPath is actually absolute - if refURL.Host != "" { - return refPath - } - parts := strings.Split(refPath, "#") - result := filepath.FromSlash(parts[0]) - if len(parts) == 2 { - result += "#" + parts[1] - } - return result - } - - // relative refPath - baseURL, _ := url.Parse(base) - if !strings.HasPrefix(refPath, "#") { - // combining paths - if baseURL.Host != "" { - baseURL.Path = path.Join(path.Dir(baseURL.Path), refURL.Path) - } else { // base is a file - newBase := fmt.Sprintf("%s#%s", filepath.Join(filepath.Dir(base), filepath.FromSlash(refURL.Path)), refURL.Fragment) - return newBase - } - - } - // copying fragment from ref to base - baseURL.Fragment = refURL.Fragment - return baseURL.String() -} - -// relativeBase could be an ABSOLUTE file path or an ABSOLUTE URL -func normalizeFileRef(ref *Ref, relativeBase string) *Ref { - // This is important for when the reference is pointing to the root schema - if ref.String() == "" { - r, _ := NewRef(relativeBase) - return &r - } - - refURL := ref.GetURL() - debugLog("normalizing %s against %s (%s)", ref.String(), relativeBase, refURL.String()) - - s := normalizePaths(ref.String(), relativeBase) - r, _ := NewRef(s) - return &r -} - -func (r *schemaLoader) resolveRef(ref *Ref, target interface{}, basePath string) error { - tgt := reflect.ValueOf(target) - if tgt.Kind() != reflect.Ptr { - return fmt.Errorf("resolve ref: target needs to be a pointer") - } - - refURL := ref.GetURL() - if refURL == nil { - return nil - } - - var res interface{} - var data interface{} - var err error - // Resolve against the root if it isn't nil, and if ref is pointing at the root, or has a fragment only which means - // it is pointing somewhere in the root. - root := r.root - if (ref.IsRoot() || ref.HasFragmentOnly) && root == nil && basePath != "" { - if baseRef, err := NewRef(basePath); err == nil { - root, _, _, _ = r.load(baseRef.GetURL()) - } - } - if (ref.IsRoot() || ref.HasFragmentOnly) && root != nil { - data = root - } else { - baseRef := normalizeFileRef(ref, basePath) - debugLog("current ref is: %s", ref.String()) - debugLog("current ref normalized file: %s", baseRef.String()) - data, _, _, err = r.load(baseRef.GetURL()) - if err != nil { - return err - } - } - - res = data - if ref.String() != "" { - res, _, err = ref.GetPointer().Get(data) - if err != nil { - return err - } - } - if err := swag.DynamicJSONToStruct(res, target); err != nil { - return err - } - - return nil -} - -func (r *schemaLoader) load(refURL *url.URL) (interface{}, url.URL, bool, error) { - debugLog("loading schema from url: %s", refURL) - toFetch := *refURL - toFetch.Fragment = "" - - normalized := normalizeAbsPath(toFetch.String()) - - data, fromCache := r.cache.Get(normalized) - if !fromCache { - b, err := r.loadDoc(normalized) - if err != nil { - return nil, url.URL{}, false, err - } - - if err := json.Unmarshal(b, &data); err != nil { - return nil, url.URL{}, false, err - } - r.cache.Set(normalized, data) - } - - return data, toFetch, fromCache, nil -} - -// Resolve resolves a reference against basePath and stores the result in target -// Resolve is not in charge of following references, it only resolves ref by following its URL -// if the schema that ref is referring to has more refs in it. Resolve doesn't resolve them -// if basePath is an empty string, ref is resolved against the root schema stored in the schemaLoader struct -func (r *schemaLoader) Resolve(ref *Ref, target interface{}, basePath string) error { - return r.resolveRef(ref, target, basePath) -} - -// absPath returns the absolute path of a file -func absPath(fname string) (string, error) { - if strings.HasPrefix(fname, "http") { - return fname, nil - } - if filepath.IsAbs(fname) { - return fname, nil - } - wd, err := os.Getwd() - return filepath.Join(wd, fname), err -} - -// ExpandSpec expands the references in a swagger spec -func ExpandSpec(spec *Swagger, options *ExpandOptions) error { - resolver, err := defaultSchemaLoader(spec, options, nil) - // Just in case this ever returns an error. - if shouldStopOnError(err, resolver.options) { - return err - } - - // getting the base path of the spec to adjust all subsequent reference resolutions - specBasePath := "" - if options != nil && options.RelativeBase != "" { - specBasePath, _ = absPath(options.RelativeBase) - } - - if options == nil || !options.SkipSchemas { - for key, definition := range spec.Definitions { - var def *Schema - var err error - if def, err = expandSchema(definition, []string{fmt.Sprintf("#/defintions/%s", key)}, resolver, specBasePath); shouldStopOnError(err, resolver.options) { - return err - } - if def != nil { - spec.Definitions[key] = *def - } - } - } - - for key, parameter := range spec.Parameters { - if err := expandParameter(¶meter, resolver, specBasePath); shouldStopOnError(err, resolver.options) { - return err - } - spec.Parameters[key] = parameter - } - - for key, response := range spec.Responses { - if err := expandResponse(&response, resolver, specBasePath); shouldStopOnError(err, resolver.options) { - return err - } - spec.Responses[key] = response - } - - if spec.Paths != nil { - for key, path := range spec.Paths.Paths { - if err := expandPathItem(&path, resolver, specBasePath); shouldStopOnError(err, resolver.options) { - return err - } - spec.Paths.Paths[key] = path - } - } - - return nil -} - -func shouldStopOnError(err error, opts *ExpandOptions) bool { - if err != nil && !opts.ContinueOnError { - return true - } - - if err != nil { - log.Println(err) - } - - return false -} - -// ExpandSchema expands the refs in the schema object with reference to the root object -// go-openapi/validate uses this function -// notice that it is impossible to reference a json scema in a different file other than root -func ExpandSchema(schema *Schema, root interface{}, cache ResolutionCache) error { - // Only save the root to a tmp file if it isn't nil. - var base string - if root != nil { - base, _ = absPath("root") - if cache == nil { - cache = resCache - } - cache.Set(normalizeAbsPath(base), root) - base = "root" - } - - opts := &ExpandOptions{ - RelativeBase: base, - SkipSchemas: false, - ContinueOnError: false, - } - return ExpandSchemaWithBasePath(schema, cache, opts) -} - -// ExpandSchemaWithBasePath expands the refs in the schema object, base path configured through expand options -func ExpandSchemaWithBasePath(schema *Schema, cache ResolutionCache, opts *ExpandOptions) error { - if schema == nil { - return nil - } - - var basePath string - if opts.RelativeBase != "" { - basePath, _ = absPath(opts.RelativeBase) - } - - resolver, err := defaultSchemaLoader(nil, opts, cache) - if err != nil { - return err - } - - refs := []string{""} - var s *Schema - if s, err = expandSchema(*schema, refs, resolver, basePath); err != nil { - return err - } - *schema = *s - return nil -} - -func expandItems(target Schema, parentRefs []string, resolver *schemaLoader, basePath string) (*Schema, error) { - if target.Items != nil { - if target.Items.Schema != nil { - t, err := expandSchema(*target.Items.Schema, parentRefs, resolver, basePath) - if err != nil { - return nil, err - } - *target.Items.Schema = *t - } - for i := range target.Items.Schemas { - t, err := expandSchema(target.Items.Schemas[i], parentRefs, resolver, basePath) - if err != nil { - return nil, err - } - target.Items.Schemas[i] = *t - } - } - return &target, nil -} - -// basePathFromSchemaID returns a new basePath based on an existing basePath and a schema ID -func basePathFromSchemaID(oldBasePath, id string) string { - u, err := url.Parse(oldBasePath) - if err != nil { - panic(err) - } - uid, err := url.Parse(id) - if err != nil { - panic(err) - } - - if path.IsAbs(uid.Path) { - return id - } - u.Path = path.Join(path.Dir(u.Path), uid.Path) - return u.String() -} - -func isCircular(ref *Ref, basePath string, parentRefs ...string) bool { - return basePath != "" && swag.ContainsStringsCI(parentRefs, ref.String()) -} - -func expandSchema(target Schema, parentRefs []string, resolver *schemaLoader, basePath string) (*Schema, error) { - if target.Ref.String() == "" && target.Ref.IsRoot() { - // normalizing is important - newRef := normalizeFileRef(&target.Ref, basePath) - target.Ref = *newRef - return &target, nil - - } - - /* change the base path of resolution when an ID is encountered - otherwise the basePath should inherit the parent's */ - // important: ID can be relative path - if target.ID != "" { - // handling the case when id is a folder - // remember that basePath has to be a file - refPath := target.ID - if strings.HasSuffix(target.ID, "/") { - // path.Clean here would not work correctly if basepath is http - refPath = fmt.Sprintf("%s%s", refPath, "placeholder.json") - } - basePath = normalizePaths(refPath, basePath) - } - - /* Explain here what this function does */ - - var t *Schema - /* if Ref is found, everything else doesn't matter */ - /* Ref also changes the resolution scope of children expandSchema */ - if target.Ref.String() != "" { - /* Here the resolution scope is changed because a $ref was encountered */ - normalizedRef := normalizeFileRef(&target.Ref, basePath) - normalizedBasePath := normalizedRef.RemoteURI() - - /* this means there is a circle in the recursion tree */ - /* return the Ref */ - if isCircular(normalizedRef, basePath, parentRefs...) { - target.Ref = *normalizedRef - return &target, nil - } - - debugLog("\nbasePath: %s", basePath) - if Debug { - b, _ := json.Marshal(target) - debugLog("calling Resolve with target: %s", string(b)) - } - if err := resolver.Resolve(&target.Ref, &t, basePath); shouldStopOnError(err, resolver.options) { - return nil, err - } - - if t != nil { - parentRefs = append(parentRefs, normalizedRef.String()) - var err error - resolver, err = transitiveResolver(basePath, target.Ref, resolver) - if shouldStopOnError(err, resolver.options) { - return nil, err - } - - return expandSchema(*t, parentRefs, resolver, normalizedBasePath) - } - } - - t, err := expandItems(target, parentRefs, resolver, basePath) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - target = *t - } - - for i := range target.AllOf { - t, err := expandSchema(target.AllOf[i], parentRefs, resolver, basePath) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - target.AllOf[i] = *t - } - for i := range target.AnyOf { - t, err := expandSchema(target.AnyOf[i], parentRefs, resolver, basePath) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - target.AnyOf[i] = *t - } - for i := range target.OneOf { - t, err := expandSchema(target.OneOf[i], parentRefs, resolver, basePath) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - target.OneOf[i] = *t - } - } - if target.Not != nil { - t, err := expandSchema(*target.Not, parentRefs, resolver, basePath) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - *target.Not = *t - } - } - for k := range target.Properties { - t, err := expandSchema(target.Properties[k], parentRefs, resolver, basePath) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - target.Properties[k] = *t - } - } - if target.AdditionalProperties != nil && target.AdditionalProperties.Schema != nil { - t, err := expandSchema(*target.AdditionalProperties.Schema, parentRefs, resolver, basePath) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - *target.AdditionalProperties.Schema = *t - } - } - for k := range target.PatternProperties { - t, err := expandSchema(target.PatternProperties[k], parentRefs, resolver, basePath) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - target.PatternProperties[k] = *t - } - } - for k := range target.Dependencies { - if target.Dependencies[k].Schema != nil { - t, err := expandSchema(*target.Dependencies[k].Schema, parentRefs, resolver, basePath) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - *target.Dependencies[k].Schema = *t - } - } - } - if target.AdditionalItems != nil && target.AdditionalItems.Schema != nil { - t, err := expandSchema(*target.AdditionalItems.Schema, parentRefs, resolver, basePath) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - *target.AdditionalItems.Schema = *t - } - } - for k := range target.Definitions { - t, err := expandSchema(target.Definitions[k], parentRefs, resolver, basePath) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - target.Definitions[k] = *t - } - } - return &target, nil -} - -func derefPathItem(pathItem *PathItem, parentRefs []string, resolver *schemaLoader, basePath string) error { - curRef := pathItem.Ref.String() - if curRef != "" { - normalizedRef := normalizeFileRef(&pathItem.Ref, basePath) - normalizedBasePath := normalizedRef.RemoteURI() - - if isCircular(normalizedRef, basePath, parentRefs...) { - return nil - } - - if err := resolver.Resolve(&pathItem.Ref, pathItem, basePath); shouldStopOnError(err, resolver.options) { - return err - } - - if pathItem.Ref.String() != "" && pathItem.Ref.String() != curRef && basePath != normalizedBasePath { - parentRefs = append(parentRefs, normalizedRef.String()) - return derefPathItem(pathItem, parentRefs, resolver, normalizedBasePath) - } - } - - return nil -} - -func expandPathItem(pathItem *PathItem, resolver *schemaLoader, basePath string) error { - if pathItem == nil { - return nil - } - - parentRefs := []string{} - if err := derefPathItem(pathItem, parentRefs, resolver, basePath); shouldStopOnError(err, resolver.options) { - return err - } - if pathItem.Ref.String() != "" { - var err error - resolver, err = transitiveResolver(basePath, pathItem.Ref, resolver) - if shouldStopOnError(err, resolver.options) { - return err - } - } - pathItem.Ref = Ref{} - - parentRefs = parentRefs[0:] - - for idx := range pathItem.Parameters { - if err := expandParameter(&(pathItem.Parameters[idx]), resolver, basePath); shouldStopOnError(err, resolver.options) { - return err - } - } - if err := expandOperation(pathItem.Get, resolver, basePath); shouldStopOnError(err, resolver.options) { - return err - } - if err := expandOperation(pathItem.Head, resolver, basePath); shouldStopOnError(err, resolver.options) { - return err - } - if err := expandOperation(pathItem.Options, resolver, basePath); shouldStopOnError(err, resolver.options) { - return err - } - if err := expandOperation(pathItem.Put, resolver, basePath); shouldStopOnError(err, resolver.options) { - return err - } - if err := expandOperation(pathItem.Post, resolver, basePath); shouldStopOnError(err, resolver.options) { - return err - } - if err := expandOperation(pathItem.Patch, resolver, basePath); shouldStopOnError(err, resolver.options) { - return err - } - if err := expandOperation(pathItem.Delete, resolver, basePath); shouldStopOnError(err, resolver.options) { - return err - } - return nil -} - -func expandOperation(op *Operation, resolver *schemaLoader, basePath string) error { - if op == nil { - return nil - } - - for i, param := range op.Parameters { - if err := expandParameter(¶m, resolver, basePath); shouldStopOnError(err, resolver.options) { - return err - } - op.Parameters[i] = param - } - - if op.Responses != nil { - responses := op.Responses - if err := expandResponse(responses.Default, resolver, basePath); shouldStopOnError(err, resolver.options) { - return err - } - for code, response := range responses.StatusCodeResponses { - if err := expandResponse(&response, resolver, basePath); shouldStopOnError(err, resolver.options) { - return err - } - responses.StatusCodeResponses[code] = response - } - } - return nil -} - -func transitiveResolver(basePath string, ref Ref, resolver *schemaLoader) (*schemaLoader, error) { - baseRef, _ := NewRef(basePath) - currentRef := normalizeFileRef(&ref, basePath) - // Set a new root to resolve against - if !strings.HasPrefix(currentRef.String(), baseRef.String()) { - rootURL := currentRef.GetURL() - rootURL.Fragment = "" - root, _ := resolver.cache.Get(rootURL.String()) - var err error - resolver, err = defaultSchemaLoader(root, resolver.options, resolver.cache) - if err != nil { - return nil, err - } - } - - return resolver, nil -} - -// ExpandResponse expands a response based on a basepath -// This is the exported version of expandResponse -// all refs inside response will be resolved relative to basePath -func ExpandResponse(response *Response, basePath string) error { - opts := &ExpandOptions{ - RelativeBase: basePath, - } - resolver, err := defaultSchemaLoader(nil, opts, nil) - if err != nil { - return err - } - - return expandResponse(response, resolver, basePath) -} - -func derefResponse(response *Response, parentRefs []string, resolver *schemaLoader, basePath string) error { - curRef := response.Ref.String() - if curRef != "" { - /* Here the resolution scope is changed because a $ref was encountered */ - normalizedRef := normalizeFileRef(&response.Ref, basePath) - normalizedBasePath := normalizedRef.RemoteURI() - - if isCircular(normalizedRef, basePath, parentRefs...) { - return nil - } - - if err := resolver.Resolve(&response.Ref, response, basePath); shouldStopOnError(err, resolver.options) { - return err - } - - if response.Ref.String() != "" && response.Ref.String() != curRef && basePath != normalizedBasePath { - parentRefs = append(parentRefs, normalizedRef.String()) - return derefResponse(response, parentRefs, resolver, normalizedBasePath) - } - } - - return nil -} - -func expandResponse(response *Response, resolver *schemaLoader, basePath string) error { - if response == nil { - return nil - } - - parentRefs := []string{} - if err := derefResponse(response, parentRefs, resolver, basePath); shouldStopOnError(err, resolver.options) { - return err - } - if response.Ref.String() != "" { - var err error - resolver, err = transitiveResolver(basePath, response.Ref, resolver) - if shouldStopOnError(err, resolver.options) { - return err - } - } - response.Ref = Ref{} - - parentRefs = parentRefs[0:] - if !resolver.options.SkipSchemas && response.Schema != nil { - parentRefs = append(parentRefs, response.Schema.Ref.String()) - s, err := expandSchema(*response.Schema, parentRefs, resolver, basePath) - if shouldStopOnError(err, resolver.options) { - return err - } - *response.Schema = *s - } - - return nil -} - -// ExpandParameter expands a parameter based on a basepath -// This is the exported version of expandParameter -// all refs inside parameter will be resolved relative to basePath -func ExpandParameter(parameter *Parameter, basePath string) error { - opts := &ExpandOptions{ - RelativeBase: basePath, - } - resolver, err := defaultSchemaLoader(nil, opts, nil) - if err != nil { - return err - } - - return expandParameter(parameter, resolver, basePath) -} - -func derefParameter(parameter *Parameter, parentRefs []string, resolver *schemaLoader, basePath string) error { - curRef := parameter.Ref.String() - if curRef != "" { - normalizedRef := normalizeFileRef(¶meter.Ref, basePath) - normalizedBasePath := normalizedRef.RemoteURI() - - if isCircular(normalizedRef, basePath, parentRefs...) { - return nil - } - - if err := resolver.Resolve(¶meter.Ref, parameter, basePath); shouldStopOnError(err, resolver.options) { - return err - } - - if parameter.Ref.String() != "" && parameter.Ref.String() != curRef && basePath != normalizedBasePath { - parentRefs = append(parentRefs, normalizedRef.String()) - return derefParameter(parameter, parentRefs, resolver, normalizedBasePath) - } - } - - return nil -} - -func expandParameter(parameter *Parameter, resolver *schemaLoader, basePath string) error { - if parameter == nil { - return nil - } - - parentRefs := []string{} - if err := derefParameter(parameter, parentRefs, resolver, basePath); shouldStopOnError(err, resolver.options) { - return err - } - if parameter.Ref.String() != "" { - var err error - resolver, err = transitiveResolver(basePath, parameter.Ref, resolver) - if shouldStopOnError(err, resolver.options) { - return err - } - } - parameter.Ref = Ref{} - - parentRefs = parentRefs[0:] - if !resolver.options.SkipSchemas && parameter.Schema != nil { - parentRefs = append(parentRefs, parameter.Schema.Ref.String()) - s, err := expandSchema(*parameter.Schema, parentRefs, resolver, basePath) - if shouldStopOnError(err, resolver.options) { - return err - } - *parameter.Schema = *s - } - return nil -} diff --git a/vendor/github.com/go-openapi/spec/expander_test.go b/vendor/github.com/go-openapi/spec/expander_test.go deleted file mode 100644 index 0116e3395..000000000 --- a/vendor/github.com/go-openapi/spec/expander_test.go +++ /dev/null @@ -1,1476 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "io/ioutil" - "log" - "net/http" - "net/http/httptest" - "runtime" - "testing" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" - "github.com/stretchr/testify/assert" -) - -func jsonDoc(path string) (json.RawMessage, error) { - data, err := swag.LoadFromFileOrHTTP(path) - if err != nil { - return nil, err - } - return json.RawMessage(data), nil -} - -// tests that paths are normalized correctly -func TestNormalizePaths(t *testing.T) { - type testNormalizePathsTestCases []struct { - refPath string - base string - expOutput string - } - testCases := func() testNormalizePathsTestCases { - testCases := testNormalizePathsTestCases{ - { - // http basePath, absolute refPath - refPath: "http://www.anotherexample.com/another/base/path/swagger.json#/definitions/Pet", - base: "http://www.example.com/base/path/swagger.json", - expOutput: "http://www.anotherexample.com/another/base/path/swagger.json#/definitions/Pet", - }, - { - // http basePath, relative refPath - refPath: "another/base/path/swagger.json#/definitions/Pet", - base: "http://www.example.com/base/path/swagger.json", - expOutput: "http://www.example.com/base/path/another/base/path/swagger.json#/definitions/Pet", - }, - } - if runtime.GOOS == "windows" { - testCases = append(testCases, testNormalizePathsTestCases{ - { - // file basePath, absolute refPath, no fragment - refPath: `C:\another\base\path.json`, - base: `C:\base\path.json`, - expOutput: `C:\another\base\path.json`, - }, - { - // file basePath, absolute refPath - refPath: `C:\another\base\path.json#/definitions/Pet`, - base: `C:\base\path.json`, - expOutput: `C:\another\base\path.json#/definitions/Pet`, - }, - { - // file basePath, relative refPath - refPath: `another\base\path.json#/definitions/Pet`, - base: `C:\base\path.json`, - expOutput: `C:\base\another\base\path.json#/definitions/Pet`, - }, - }...) - return testCases - } - // linux case - testCases = append(testCases, testNormalizePathsTestCases{ - { - // file basePath, absolute refPath, no fragment - refPath: "/another/base/path.json", - base: "/base/path.json", - expOutput: "/another/base/path.json", - }, - { - // file basePath, absolute refPath - refPath: "/another/base/path.json#/definitions/Pet", - base: "/base/path.json", - expOutput: "/another/base/path.json#/definitions/Pet", - }, - { - // file basePath, relative refPath - refPath: "another/base/path.json#/definitions/Pet", - base: "/base/path.json", - expOutput: "/base/another/base/path.json#/definitions/Pet", - }, - }...) - return testCases - }() - - for _, tcase := range testCases { - out := normalizePaths(tcase.refPath, tcase.base) - assert.Equal(t, tcase.expOutput, out) - } -} - -func TestExpandsKnownRef(t *testing.T) { - schema := RefProperty("http://json-schema.org/draft-04/schema#") - if assert.NoError(t, ExpandSchema(schema, nil, nil)) { - assert.Equal(t, "Core schema meta-schema", schema.Description) - } -} - -func TestExpandResponseSchema(t *testing.T) { - fp := "./fixtures/local_expansion/spec.json" - b, err := jsonDoc(fp) - if assert.NoError(t, err) { - var spec Swagger - if err := json.Unmarshal(b, &spec); assert.NoError(t, err) { - err := ExpandSpec(&spec, &ExpandOptions{RelativeBase: fp}) - if assert.NoError(t, err) { - sch := spec.Paths.Paths["/item"].Get.Responses.StatusCodeResponses[200].Schema - if assert.NotNil(t, sch) { - assert.Empty(t, sch.Ref.String()) - assert.Contains(t, sch.Type, "object") - assert.Len(t, sch.Properties, 2) - } - } - } - } -} - -func TestSpecExpansion(t *testing.T) { - spec := new(Swagger) - // resolver, err := defaultSchemaLoader(spec, nil, nil) - // assert.NoError(t, err) - - err := ExpandSpec(spec, nil) - assert.NoError(t, err) - - specDoc, err := jsonDoc("fixtures/expansion/all-the-things.json") - assert.NoError(t, err) - - specPath, _ := absPath("fixtures/expansion/all-the-things.json") - opts := &ExpandOptions{ - RelativeBase: specPath, - } - - spec = new(Swagger) - err = json.Unmarshal(specDoc, spec) - assert.NoError(t, err) - - pet := spec.Definitions["pet"] - errorModel := spec.Definitions["errorModel"] - petResponse := spec.Responses["petResponse"] - petResponse.Schema = &pet - stringResponse := spec.Responses["stringResponse"] - tagParam := spec.Parameters["tag"] - idParam := spec.Parameters["idParam"] - - err = ExpandSpec(spec, opts) - assert.NoError(t, err) - - assert.Equal(t, tagParam, spec.Parameters["query"]) - assert.Equal(t, petResponse, spec.Responses["petResponse"]) - assert.Equal(t, petResponse, spec.Responses["anotherPet"]) - assert.Equal(t, pet, *spec.Responses["petResponse"].Schema) - assert.Equal(t, stringResponse, *spec.Paths.Paths["/"].Get.Responses.Default) - assert.Equal(t, petResponse, spec.Paths.Paths["/"].Get.Responses.StatusCodeResponses[200]) - assert.Equal(t, pet, *spec.Paths.Paths["/pets"].Get.Responses.StatusCodeResponses[200].Schema.Items.Schema) - assert.Equal(t, errorModel, *spec.Paths.Paths["/pets"].Get.Responses.Default.Schema) - assert.Equal(t, pet, spec.Definitions["petInput"].AllOf[0]) - assert.Equal(t, spec.Definitions["petInput"], *spec.Paths.Paths["/pets"].Post.Parameters[0].Schema) - assert.Equal(t, petResponse, spec.Paths.Paths["/pets"].Post.Responses.StatusCodeResponses[200]) - assert.Equal(t, errorModel, *spec.Paths.Paths["/pets"].Post.Responses.Default.Schema) - pi := spec.Paths.Paths["/pets/{id}"] - assert.Equal(t, idParam, pi.Get.Parameters[0]) - assert.Equal(t, petResponse, pi.Get.Responses.StatusCodeResponses[200]) - assert.Equal(t, errorModel, *pi.Get.Responses.Default.Schema) - assert.Equal(t, idParam, pi.Delete.Parameters[0]) - assert.Equal(t, errorModel, *pi.Delete.Responses.Default.Schema) -} - -func TestResolveRef(t *testing.T) { - var root interface{} - err := json.Unmarshal([]byte(PetStore20), &root) - assert.NoError(t, err) - ref, err := NewRef("#/definitions/Category") - assert.NoError(t, err) - sch, err := ResolveRef(root, &ref) - assert.NoError(t, err) - b, _ := sch.MarshalJSON() - assert.JSONEq(t, `{"id":"Category","properties":{"id":{"type":"integer","format":"int64"},"name":{"type":"string"}}}`, string(b)) -} - -func TestResponseExpansion(t *testing.T) { - specDoc, err := jsonDoc("fixtures/expansion/all-the-things.json") - assert.NoError(t, err) - - basePath, err := absPath("fixtures/expansion/all-the-things.json") - assert.NoError(t, err) - - spec := new(Swagger) - err = json.Unmarshal(specDoc, spec) - assert.NoError(t, err) - - resolver, err := defaultSchemaLoader(spec, nil, nil) - assert.NoError(t, err) - - resp := spec.Responses["anotherPet"] - r := spec.Responses["petResponse"] - err = expandResponse(&r, resolver, basePath) - assert.NoError(t, err) - expected := r - - err = expandResponse(&resp, resolver, basePath) - b, _ := resp.MarshalJSON() - log.Printf(string(b)) - b, _ = expected.MarshalJSON() - log.Printf(string(b)) - assert.NoError(t, err) - assert.Equal(t, expected, resp) - - resp2 := spec.Paths.Paths["/"].Get.Responses.Default - expected = spec.Responses["stringResponse"] - - err = expandResponse(resp2, resolver, basePath) - assert.NoError(t, err) - assert.Equal(t, expected, *resp2) - - resp = spec.Paths.Paths["/"].Get.Responses.StatusCodeResponses[200] - expected = spec.Responses["petResponse"] - - err = expandResponse(&resp, resolver, basePath) - assert.NoError(t, err) - // assert.Equal(t, expected, resp) -} - -// test the exported version of ExpandResponse -func TestExportedResponseExpansion(t *testing.T) { - specDoc, err := jsonDoc("fixtures/expansion/all-the-things.json") - assert.NoError(t, err) - - basePath, err := absPath("fixtures/expansion/all-the-things.json") - assert.NoError(t, err) - - spec := new(Swagger) - err = json.Unmarshal(specDoc, spec) - assert.NoError(t, err) - - resp := spec.Responses["anotherPet"] - r := spec.Responses["petResponse"] - err = ExpandResponse(&r, basePath) - assert.NoError(t, err) - expected := r - - err = ExpandResponse(&resp, basePath) - b, _ := resp.MarshalJSON() - log.Printf(string(b)) - b, _ = expected.MarshalJSON() - log.Printf(string(b)) - assert.NoError(t, err) - assert.Equal(t, expected, resp) - - resp2 := spec.Paths.Paths["/"].Get.Responses.Default - expected = spec.Responses["stringResponse"] - - err = ExpandResponse(resp2, basePath) - assert.NoError(t, err) - assert.Equal(t, expected, *resp2) - - resp = spec.Paths.Paths["/"].Get.Responses.StatusCodeResponses[200] - expected = spec.Responses["petResponse"] - - err = ExpandResponse(&resp, basePath) - assert.NoError(t, err) - // assert.Equal(t, expected, resp) -} - -func TestIssue3(t *testing.T) { - spec := new(Swagger) - specDoc, err := jsonDoc("fixtures/expansion/overflow.json") - assert.NoError(t, err) - - specPath, _ := absPath("fixtures/expansion/overflow.json") - opts := &ExpandOptions{ - RelativeBase: specPath, - } - - err = json.Unmarshal(specDoc, spec) - assert.NoError(t, err) - - assert.NotPanics(t, func() { - err = ExpandSpec(spec, opts) - assert.NoError(t, err) - }, "Calling expand spec with circular refs, should not panic!") -} - -func TestParameterExpansion(t *testing.T) { - paramDoc, err := jsonDoc("fixtures/expansion/params.json") - assert.NoError(t, err) - - spec := new(Swagger) - err = json.Unmarshal(paramDoc, spec) - assert.NoError(t, err) - - basePath, err := absPath("fixtures/expansion/params.json") - assert.NoError(t, err) - - resolver, err := defaultSchemaLoader(spec, nil, nil) - assert.NoError(t, err) - - param := spec.Parameters["query"] - expected := spec.Parameters["tag"] - - err = expandParameter(¶m, resolver, basePath) - assert.NoError(t, err) - assert.Equal(t, expected, param) - - param = spec.Paths.Paths["/cars/{id}"].Parameters[0] - expected = spec.Parameters["id"] - - err = expandParameter(¶m, resolver, basePath) - assert.NoError(t, err) - assert.Equal(t, expected, param) -} - -func TestExportedParameterExpansion(t *testing.T) { - paramDoc, err := jsonDoc("fixtures/expansion/params.json") - assert.NoError(t, err) - - spec := new(Swagger) - err = json.Unmarshal(paramDoc, spec) - assert.NoError(t, err) - - basePath, err := absPath("fixtures/expansion/params.json") - assert.NoError(t, err) - - param := spec.Parameters["query"] - expected := spec.Parameters["tag"] - - err = ExpandParameter(¶m, basePath) - assert.NoError(t, err) - assert.Equal(t, expected, param) - - param = spec.Paths.Paths["/cars/{id}"].Parameters[0] - expected = spec.Parameters["id"] - - err = ExpandParameter(¶m, basePath) - assert.NoError(t, err) - assert.Equal(t, expected, param) -} - -func TestCircularRefsExpansion(t *testing.T) { - carsDoc, err := jsonDoc("fixtures/expansion/circularRefs.json") - assert.NoError(t, err) - - basePath, _ := absPath("fixtures/expansion/circularRefs.json") - - spec := new(Swagger) - err = json.Unmarshal(carsDoc, spec) - assert.NoError(t, err) - - resolver, err := defaultSchemaLoader(spec, nil, nil) - assert.NoError(t, err) - schema := spec.Definitions["car"] - - assert.NotPanics(t, func() { - _, err = expandSchema(schema, []string{"#/definitions/car"}, resolver, basePath) - assert.NoError(t, err) - }, "Calling expand schema with circular refs, should not panic!") -} - -func TestContinueOnErrorExpansion(t *testing.T) { - missingRefDoc, err := jsonDoc("fixtures/expansion/missingRef.json") - assert.NoError(t, err) - - specPath, _ := absPath("fixtures/expansion/missingRef.json") - - testCase := struct { - Input *Swagger `json:"input"` - Expected *Swagger `json:"expected"` - }{} - err = json.Unmarshal(missingRefDoc, &testCase) - assert.NoError(t, err) - - opts := &ExpandOptions{ - ContinueOnError: true, - RelativeBase: specPath, - } - err = ExpandSpec(testCase.Input, opts) - assert.NoError(t, err) - b, _ := testCase.Input.MarshalJSON() - log.Printf(string(b)) - assert.Equal(t, testCase.Input, testCase.Expected, "Should continue expanding spec when a definition can't be found.") - - doc, err := jsonDoc("fixtures/expansion/missingItemRef.json") - spec := new(Swagger) - err = json.Unmarshal(doc, spec) - assert.NoError(t, err) - - assert.NotPanics(t, func() { - err = ExpandSpec(spec, opts) - assert.NoError(t, err) - }, "Array of missing refs should not cause a panic, and continue to expand spec.") -} - -func TestIssue415(t *testing.T) { - doc, err := jsonDoc("fixtures/expansion/clickmeter.json") - assert.NoError(t, err) - - specPath, _ := absPath("fixtures/expansion/clickmeter.json") - - opts := &ExpandOptions{ - RelativeBase: specPath, - } - - spec := new(Swagger) - err = json.Unmarshal(doc, spec) - assert.NoError(t, err) - - assert.NotPanics(t, func() { - err = ExpandSpec(spec, opts) - assert.NoError(t, err) - }, "Calling expand spec with response schemas that have circular refs, should not panic!") -} - -func TestCircularSpecExpansion(t *testing.T) { - doc, err := jsonDoc("fixtures/expansion/circularSpec.json") - assert.NoError(t, err) - - specPath, _ := absPath("fixtures/expansion/circularSpec.json") - - opts := &ExpandOptions{ - RelativeBase: specPath, - } - - spec := new(Swagger) - err = json.Unmarshal(doc, spec) - assert.NoError(t, err) - - assert.NotPanics(t, func() { - err = ExpandSpec(spec, opts) - assert.NoError(t, err) - }, "Calling expand spec with circular refs, should not panic!") -} - -func TestItemsExpansion(t *testing.T) { - carsDoc, err := jsonDoc("fixtures/expansion/schemas2.json") - assert.NoError(t, err) - - basePath, _ := absPath("fixtures/expansion/schemas2.json") - - spec := new(Swagger) - err = json.Unmarshal(carsDoc, spec) - assert.NoError(t, err) - - resolver, err := defaultSchemaLoader(spec, nil, nil) - assert.NoError(t, err) - - schema := spec.Definitions["car"] - oldBrand := schema.Properties["brand"] - assert.NotEmpty(t, oldBrand.Items.Schema.Ref.String()) - assert.NotEqual(t, spec.Definitions["brand"], oldBrand) - - _, err = expandSchema(schema, []string{"#/definitions/car"}, resolver, basePath) - assert.NoError(t, err) - - newBrand := schema.Properties["brand"] - assert.Empty(t, newBrand.Items.Schema.Ref.String()) - assert.Equal(t, spec.Definitions["brand"], *newBrand.Items.Schema) - - schema = spec.Definitions["truck"] - assert.NotEmpty(t, schema.Items.Schema.Ref.String()) - - s, err := expandSchema(schema, []string{"#/definitions/truck"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Items.Schema.Ref.String()) - assert.Equal(t, spec.Definitions["car"], *schema.Items.Schema) - - sch := new(Schema) - _, err = expandSchema(*sch, []string{""}, resolver, basePath) - assert.NoError(t, err) - - schema = spec.Definitions["batch"] - s, err = expandSchema(schema, []string{"#/definitions/batch"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Items.Schema.Items.Schema.Ref.String()) - assert.Equal(t, *schema.Items.Schema.Items.Schema, spec.Definitions["brand"]) - - schema = spec.Definitions["batch2"] - s, err = expandSchema(schema, []string{"#/definitions/batch2"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Items.Schemas[0].Items.Schema.Ref.String()) - assert.Empty(t, schema.Items.Schemas[1].Items.Schema.Ref.String()) - assert.Equal(t, *schema.Items.Schemas[0].Items.Schema, spec.Definitions["brand"]) - assert.Equal(t, *schema.Items.Schemas[1].Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["allofBoth"] - s, err = expandSchema(schema, []string{"#/definitions/allofBoth"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AllOf[0].Items.Schema.Ref.String()) - assert.Empty(t, schema.AllOf[1].Items.Schema.Ref.String()) - assert.Equal(t, *schema.AllOf[0].Items.Schema, spec.Definitions["brand"]) - assert.Equal(t, *schema.AllOf[1].Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["anyofBoth"] - s, err = expandSchema(schema, []string{"#/definitions/anyofBoth"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AnyOf[0].Items.Schema.Ref.String()) - assert.Empty(t, schema.AnyOf[1].Items.Schema.Ref.String()) - assert.Equal(t, *schema.AnyOf[0].Items.Schema, spec.Definitions["brand"]) - assert.Equal(t, *schema.AnyOf[1].Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["oneofBoth"] - s, err = expandSchema(schema, []string{"#/definitions/oneofBoth"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.OneOf[0].Items.Schema.Ref.String()) - assert.Empty(t, schema.OneOf[1].Items.Schema.Ref.String()) - assert.Equal(t, *schema.OneOf[0].Items.Schema, spec.Definitions["brand"]) - assert.Equal(t, *schema.OneOf[1].Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["notSomething"] - s, err = expandSchema(schema, []string{"#/definitions/notSomething"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Not.Items.Schema.Ref.String()) - assert.Equal(t, *schema.Not.Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["withAdditional"] - s, err = expandSchema(schema, []string{"#/definitions/withAdditional"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AdditionalProperties.Schema.Items.Schema.Ref.String()) - assert.Equal(t, *schema.AdditionalProperties.Schema.Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["withAdditionalItems"] - s, err = expandSchema(schema, []string{"#/definitions/withAdditionalItems"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AdditionalItems.Schema.Items.Schema.Ref.String()) - assert.Equal(t, *schema.AdditionalItems.Schema.Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["withPattern"] - s, err = expandSchema(schema, []string{"#/definitions/withPattern"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - prop := schema.PatternProperties["^x-ab"] - assert.Empty(t, prop.Items.Schema.Ref.String()) - assert.Equal(t, *prop.Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["deps"] - s, err = expandSchema(schema, []string{"#/definitions/deps"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - prop2 := schema.Dependencies["something"] - assert.Empty(t, prop2.Schema.Items.Schema.Ref.String()) - assert.Equal(t, *prop2.Schema.Items.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["defined"] - s, err = expandSchema(schema, []string{"#/definitions/defined"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - prop = schema.Definitions["something"] - assert.Empty(t, prop.Items.Schema.Ref.String()) - assert.Equal(t, *prop.Items.Schema, spec.Definitions["tag"]) -} - -func TestSchemaExpansion(t *testing.T) { - carsDoc, err := jsonDoc("fixtures/expansion/schemas1.json") - assert.NoError(t, err) - - basePath, _ := absPath("fixtures/expansion/schemas1.json") - - spec := new(Swagger) - err = json.Unmarshal(carsDoc, spec) - assert.NoError(t, err) - - resolver, err := defaultSchemaLoader(spec, nil, nil) - assert.NoError(t, err) - - schema := spec.Definitions["car"] - oldBrand := schema.Properties["brand"] - assert.NotEmpty(t, oldBrand.Ref.String()) - assert.NotEqual(t, spec.Definitions["brand"], oldBrand) - - s, err := expandSchema(schema, []string{"#/definitions/car"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - - newBrand := schema.Properties["brand"] - assert.Empty(t, newBrand.Ref.String()) - assert.Equal(t, spec.Definitions["brand"], newBrand) - - schema = spec.Definitions["truck"] - assert.NotEmpty(t, schema.Ref.String()) - - s, err = expandSchema(schema, []string{"#/definitions/truck"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Ref.String()) - assert.Equal(t, spec.Definitions["car"], schema) - - sch := new(Schema) - _, err = expandSchema(*sch, []string{""}, resolver, basePath) - assert.NoError(t, err) - - schema = spec.Definitions["batch"] - s, err = expandSchema(schema, []string{"#/definitions/batch"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Items.Schema.Ref.String()) - assert.Equal(t, *schema.Items.Schema, spec.Definitions["brand"]) - - schema = spec.Definitions["batch2"] - s, err = expandSchema(schema, []string{"#/definitions/batch2"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Items.Schemas[0].Ref.String()) - assert.Empty(t, schema.Items.Schemas[1].Ref.String()) - assert.Equal(t, schema.Items.Schemas[0], spec.Definitions["brand"]) - assert.Equal(t, schema.Items.Schemas[1], spec.Definitions["tag"]) - - schema = spec.Definitions["allofBoth"] - s, err = expandSchema(schema, []string{"#/definitions/allofBoth"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AllOf[0].Ref.String()) - assert.Empty(t, schema.AllOf[1].Ref.String()) - assert.Equal(t, schema.AllOf[0], spec.Definitions["brand"]) - assert.Equal(t, schema.AllOf[1], spec.Definitions["tag"]) - - schema = spec.Definitions["anyofBoth"] - s, err = expandSchema(schema, []string{"#/definitions/anyofBoth"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AnyOf[0].Ref.String()) - assert.Empty(t, schema.AnyOf[1].Ref.String()) - assert.Equal(t, schema.AnyOf[0], spec.Definitions["brand"]) - assert.Equal(t, schema.AnyOf[1], spec.Definitions["tag"]) - - schema = spec.Definitions["oneofBoth"] - s, err = expandSchema(schema, []string{"#/definitions/oneofBoth"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.OneOf[0].Ref.String()) - assert.Empty(t, schema.OneOf[1].Ref.String()) - assert.Equal(t, schema.OneOf[0], spec.Definitions["brand"]) - assert.Equal(t, schema.OneOf[1], spec.Definitions["tag"]) - - schema = spec.Definitions["notSomething"] - s, err = expandSchema(schema, []string{"#/definitions/notSomething"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.Not.Ref.String()) - assert.Equal(t, *schema.Not, spec.Definitions["tag"]) - - schema = spec.Definitions["withAdditional"] - s, err = expandSchema(schema, []string{"#/definitions/withAdditional"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AdditionalProperties.Schema.Ref.String()) - assert.Equal(t, *schema.AdditionalProperties.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["withAdditionalItems"] - s, err = expandSchema(schema, []string{"#/definitions/withAdditionalItems"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - assert.Empty(t, schema.AdditionalItems.Schema.Ref.String()) - assert.Equal(t, *schema.AdditionalItems.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["withPattern"] - s, err = expandSchema(schema, []string{"#/definitions/withPattern"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - prop := schema.PatternProperties["^x-ab"] - assert.Empty(t, prop.Ref.String()) - assert.Equal(t, prop, spec.Definitions["tag"]) - - schema = spec.Definitions["deps"] - s, err = expandSchema(schema, []string{"#/definitions/deps"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - prop2 := schema.Dependencies["something"] - assert.Empty(t, prop2.Schema.Ref.String()) - assert.Equal(t, *prop2.Schema, spec.Definitions["tag"]) - - schema = spec.Definitions["defined"] - s, err = expandSchema(schema, []string{"#/definitions/defined"}, resolver, basePath) - schema = *s - assert.NoError(t, err) - prop = schema.Definitions["something"] - assert.Empty(t, prop.Ref.String()) - assert.Equal(t, prop, spec.Definitions["tag"]) - -} - -func TestDefaultResolutionCache(t *testing.T) { - - cache := initResolutionCache() - - sch, ok := cache.Get("not there") - assert.False(t, ok) - assert.Nil(t, sch) - - sch, ok = cache.Get("http://swagger.io/v2/schema.json") - assert.True(t, ok) - assert.Equal(t, swaggerSchema, sch) - - sch, ok = cache.Get("http://json-schema.org/draft-04/schema") - assert.True(t, ok) - assert.Equal(t, jsonSchema, sch) - - cache.Set("something", "here") - sch, ok = cache.Get("something") - assert.True(t, ok) - assert.Equal(t, "here", sch) -} - -func TestRelativeBaseURI(t *testing.T) { - server := httptest.NewServer(http.FileServer(http.Dir("fixtures/remote"))) - defer server.Close() - - spec := new(Swagger) - // resolver, err := defaultSchemaLoader(spec, nil, nil) - // assert.NoError(t, err) - - err := ExpandSpec(spec, nil) - assert.NoError(t, err) - - specDoc, err := jsonDoc("fixtures/remote/all-the-things.json") - assert.NoError(t, err) - - opts := &ExpandOptions{ - RelativeBase: server.URL + "/all-the-things.json", - } - - spec = new(Swagger) - err = json.Unmarshal(specDoc, spec) - assert.NoError(t, err) - - pet := spec.Definitions["pet"] - errorModel := spec.Definitions["errorModel"] - petResponse := spec.Responses["petResponse"] - petResponse.Schema = &pet - stringResponse := spec.Responses["stringResponse"] - tagParam := spec.Parameters["tag"] - idParam := spec.Parameters["idParam"] - - anotherPet := spec.Responses["anotherPet"] - anotherPet.Ref = MustCreateRef(server.URL + "/" + anotherPet.Ref.String()) - err = ExpandResponse(&anotherPet, opts.RelativeBase) - assert.NoError(t, err) - spec.Responses["anotherPet"] = anotherPet - - circularA := spec.Responses["circularA"] - circularA.Ref = MustCreateRef(server.URL + "/" + circularA.Ref.String()) - err = ExpandResponse(&circularA, opts.RelativeBase) - assert.NoError(t, err) - spec.Responses["circularA"] = circularA - - err = ExpandSpec(spec, opts) - assert.NoError(t, err) - - assert.Equal(t, tagParam, spec.Parameters["query"]) - assert.Equal(t, petResponse, spec.Responses["petResponse"]) - assert.Equal(t, petResponse, spec.Responses["anotherPet"]) - assert.Equal(t, pet, *spec.Responses["petResponse"].Schema) - assert.Equal(t, stringResponse, *spec.Paths.Paths["/"].Get.Responses.Default) - assert.Equal(t, petResponse, spec.Paths.Paths["/"].Get.Responses.StatusCodeResponses[200]) - assert.Equal(t, pet, *spec.Paths.Paths["/pets"].Get.Responses.StatusCodeResponses[200].Schema.Items.Schema) - assert.Equal(t, errorModel, *spec.Paths.Paths["/pets"].Get.Responses.Default.Schema) - assert.Equal(t, pet, spec.Definitions["petInput"].AllOf[0]) - assert.Equal(t, spec.Definitions["petInput"], *spec.Paths.Paths["/pets"].Post.Parameters[0].Schema) - assert.Equal(t, petResponse, spec.Paths.Paths["/pets"].Post.Responses.StatusCodeResponses[200]) - assert.Equal(t, errorModel, *spec.Paths.Paths["/pets"].Post.Responses.Default.Schema) - pi := spec.Paths.Paths["/pets/{id}"] - assert.Equal(t, idParam, pi.Get.Parameters[0]) - assert.Equal(t, petResponse, pi.Get.Responses.StatusCodeResponses[200]) - assert.Equal(t, errorModel, *pi.Get.Responses.Default.Schema) - assert.Equal(t, idParam, pi.Delete.Parameters[0]) - assert.Equal(t, errorModel, *pi.Delete.Responses.Default.Schema) -} - -func resolutionContextServer() *httptest.Server { - var servedAt string - server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - // fmt.Println("got a request for", req.URL.String()) - if req.URL.Path == "/resolution.json" { - - b, _ := ioutil.ReadFile("fixtures/specs/resolution.json") - var ctnt map[string]interface{} - json.Unmarshal(b, &ctnt) - ctnt["id"] = servedAt - - rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(200) - bb, _ := json.Marshal(ctnt) - rw.Write(bb) - return - } - if req.URL.Path == "/resolution2.json" { - b, _ := ioutil.ReadFile("fixtures/specs/resolution2.json") - var ctnt map[string]interface{} - json.Unmarshal(b, &ctnt) - ctnt["id"] = servedAt - - rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(200) - bb, _ := json.Marshal(ctnt) - rw.Write(bb) - return - } - - if req.URL.Path == "/boolProp.json" { - rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(200) - b, _ := json.Marshal(map[string]interface{}{ - "type": "boolean", - }) - _, _ = rw.Write(b) - return - } - - if req.URL.Path == "/deeper/stringProp.json" { - rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(200) - b, _ := json.Marshal(map[string]interface{}{ - "type": "string", - }) - rw.Write(b) - return - } - - if req.URL.Path == "/deeper/arrayProp.json" { - rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(200) - b, _ := json.Marshal(map[string]interface{}{ - "type": "array", - "items": map[string]interface{}{ - "type": "file", - }, - }) - rw.Write(b) - return - } - - rw.WriteHeader(http.StatusNotFound) - })) - servedAt = server.URL - return server -} - -func TestResolveRemoteRef_RootSame(t *testing.T) { - specs := "fixtures/specs/" - fileserver := http.FileServer(http.Dir(specs)) - server := httptest.NewServer(fileserver) - defer server.Close() - - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - // the filename doesn't matter because ref will eventually point to refed.json - specBase, _ := absPath("fixtures/specs/anyotherfile.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var result_0 Swagger - ref_0, _ := NewRef(server.URL + "/refed.json#") - resolver_0, _ := defaultSchemaLoader(rootDoc, nil, nil) - if assert.NoError(t, resolver_0.Resolve(&ref_0, &result_0, "")) { - assertSpecs(t, result_0, *rootDoc) - } - - var result_1 Swagger - ref_1, _ := NewRef("./refed.json") - resolver_1, _ := defaultSchemaLoader(rootDoc, &ExpandOptions{ - RelativeBase: specBase, - }, nil) - if assert.NoError(t, resolver_1.Resolve(&ref_1, &result_1, specBase)) { - assertSpecs(t, result_1, *rootDoc) - } - } -} - -func TestResolveRemoteRef_FromFragment(t *testing.T) { - specs := "fixtures/specs" - fileserver := http.FileServer(http.Dir(specs)) - server := httptest.NewServer(fileserver) - defer server.Close() - - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt Schema - ref, err := NewRef(server.URL + "/refed.json#/definitions/pet") - if assert.NoError(t, err) { - resolver := &schemaLoader{root: rootDoc, cache: initResolutionCache(), loadDoc: jsonDoc} - if assert.NoError(t, resolver.Resolve(&ref, &tgt, "")) { - assert.Equal(t, []string{"id", "name"}, tgt.Required) - } - } - } -} - -func TestResolveRemoteRef_FromInvalidFragment(t *testing.T) { - specs := "fixtures/specs" - fileserver := http.FileServer(http.Dir(specs)) - server := httptest.NewServer(fileserver) - defer server.Close() - - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt Schema - ref, err := NewRef(server.URL + "/refed.json#/definitions/NotThere") - if assert.NoError(t, err) { - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) - assert.Error(t, resolver.Resolve(&ref, &tgt, "")) - } - } -} - -func TestResolveRemoteRef_WithResolutionContext(t *testing.T) { - server := resolutionContextServer() - defer server.Close() - - var tgt Schema - ref, err := NewRef(server.URL + "/resolution.json#/definitions/bool") - if assert.NoError(t, err) { - tgt.Ref = ref - ExpandSchema(&tgt, nil, nil) - assert.Equal(t, StringOrArray([]string{"boolean"}), tgt.Type) - } - -} - -func TestResolveRemoteRef_WithNestedResolutionContext(t *testing.T) { - server := resolutionContextServer() - defer server.Close() - - var tgt Schema - ref, err := NewRef(server.URL + "/resolution.json#/items") - if assert.NoError(t, err) { - tgt.Ref = ref - ExpandSchema(&tgt, nil, nil) - assert.Equal(t, StringOrArray([]string{"string"}), tgt.Items.Schema.Type) - } -} - -/* This next test will have to wait until we do full $ID analysis for every subschema on every file that is referenced */ -/* For now, TestResolveRemoteRef_WithNestedResolutionContext replaces this next test */ -// func TestResolveRemoteRef_WithNestedResolutionContext_WithParentID(t *testing.T) { -// server := resolutionContextServer() -// defer server.Close() - -// var tgt Schema -// ref, err := NewRef(server.URL + "/resolution.json#/items/items") -// if assert.NoError(t, err) { -// tgt.Ref = ref -// ExpandSchema(&tgt, nil, nil) -// assert.Equal(t, StringOrArray([]string{"string"}), tgt.Type) -// } -// } - -func TestResolveRemoteRef_WithNestedResolutionContextWithFragment(t *testing.T) { - server := resolutionContextServer() - defer server.Close() - - var tgt Schema - ref, err := NewRef(server.URL + "/resolution2.json#/items") - if assert.NoError(t, err) { - tgt.Ref = ref - ExpandSchema(&tgt, nil, nil) - assert.Equal(t, StringOrArray([]string{"file"}), tgt.Items.Schema.Type) - } - -} - -/* This next test will have to wait until we do full $ID analysis for every subschema on every file that is referenced */ -/* For now, TestResolveRemoteRef_WithNestedResolutionContext replaces this next test */ -// func TestResolveRemoteRef_WithNestedResolutionContextWithFragment_WithParentID(t *testing.T) { -// server := resolutionContextServer() -// defer server.Close() - -// rootDoc := new(Swagger) -// b, err := ioutil.ReadFile("fixtures/specs/refed.json") -// if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { -// var tgt Schema -// ref, err := NewRef(server.URL + "/resolution2.json#/items/items") -// if assert.NoError(t, err) { -// resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) -// if assert.NoError(t, resolver.Resolve(&ref, &tgt, "")) { -// assert.Equal(t, StringOrArray([]string{"file"}), tgt.Type) -// } -// } -// } -// } - -func TestResolveRemoteRef_ToParameter(t *testing.T) { - specs := "fixtures/specs" - fileserver := http.FileServer(http.Dir(specs)) - server := httptest.NewServer(fileserver) - defer server.Close() - - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt Parameter - ref, err := NewRef(server.URL + "/refed.json#/parameters/idParam") - if assert.NoError(t, err) { - - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) - if assert.NoError(t, resolver.Resolve(&ref, &tgt, "")) { - assert.Equal(t, "id", tgt.Name) - assert.Equal(t, "path", tgt.In) - assert.Equal(t, "ID of pet to fetch", tgt.Description) - assert.True(t, tgt.Required) - assert.Equal(t, "integer", tgt.Type) - assert.Equal(t, "int64", tgt.Format) - } - } - } -} - -func TestResolveRemoteRef_ToPathItem(t *testing.T) { - specs := "fixtures/specs" - fileserver := http.FileServer(http.Dir(specs)) - server := httptest.NewServer(fileserver) - defer server.Close() - - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt PathItem - ref, err := NewRef(server.URL + "/refed.json#/paths/" + jsonpointer.Escape("/pets/{id}")) - if assert.NoError(t, err) { - - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) - if assert.NoError(t, resolver.Resolve(&ref, &tgt, "")) { - assert.Equal(t, rootDoc.Paths.Paths["/pets/{id}"].Get, tgt.Get) - } - } - } -} - -func TestResolveRemoteRef_ToResponse(t *testing.T) { - specs := "fixtures/specs" - fileserver := http.FileServer(http.Dir(specs)) - server := httptest.NewServer(fileserver) - defer server.Close() - - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt Response - ref, err := NewRef(server.URL + "/refed.json#/responses/petResponse") - if assert.NoError(t, err) { - - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) - if assert.NoError(t, resolver.Resolve(&ref, &tgt, "")) { - assert.Equal(t, rootDoc.Responses["petResponse"], tgt) - } - } - } -} - -func TestResolveLocalRef_SameRoot(t *testing.T) { - rootDoc := new(Swagger) - json.Unmarshal(PetStoreJSONMessage, rootDoc) - - result := new(Swagger) - ref, _ := NewRef("#") - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) - err := resolver.Resolve(&ref, result, "") - if assert.NoError(t, err) { - assert.Equal(t, rootDoc, result) - } -} - -func TestResolveLocalRef_FromFragment(t *testing.T) { - rootDoc := new(Swagger) - json.Unmarshal(PetStoreJSONMessage, rootDoc) - - var tgt Schema - ref, err := NewRef("#/definitions/Category") - if assert.NoError(t, err) { - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) - err := resolver.Resolve(&ref, &tgt, "") - if assert.NoError(t, err) { - assert.Equal(t, "Category", tgt.ID) - } - } -} - -func TestResolveLocalRef_FromInvalidFragment(t *testing.T) { - rootDoc := new(Swagger) - json.Unmarshal(PetStoreJSONMessage, rootDoc) - - var tgt Schema - ref, err := NewRef("#/definitions/NotThere") - if assert.NoError(t, err) { - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) - err := resolver.Resolve(&ref, &tgt, "") - assert.Error(t, err) - } -} - -func TestResolveLocalRef_Parameter(t *testing.T) { - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - basePath, _ := absPath("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt Parameter - ref, err := NewRef("#/parameters/idParam") - if assert.NoError(t, err) { - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) - if assert.NoError(t, resolver.Resolve(&ref, &tgt, basePath)) { - assert.Equal(t, "id", tgt.Name) - assert.Equal(t, "path", tgt.In) - assert.Equal(t, "ID of pet to fetch", tgt.Description) - assert.True(t, tgt.Required) - assert.Equal(t, "integer", tgt.Type) - assert.Equal(t, "int64", tgt.Format) - } - } - } -} - -func TestResolveLocalRef_PathItem(t *testing.T) { - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - basePath, _ := absPath("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt PathItem - ref, err := NewRef("#/paths/" + jsonpointer.Escape("/pets/{id}")) - if assert.NoError(t, err) { - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) - if assert.NoError(t, resolver.Resolve(&ref, &tgt, basePath)) { - assert.Equal(t, rootDoc.Paths.Paths["/pets/{id}"].Get, tgt.Get) - } - } - } -} - -func TestResolveLocalRef_Response(t *testing.T) { - rootDoc := new(Swagger) - b, err := ioutil.ReadFile("fixtures/specs/refed.json") - basePath, _ := absPath("fixtures/specs/refed.json") - if assert.NoError(t, err) && assert.NoError(t, json.Unmarshal(b, rootDoc)) { - var tgt Response - ref, err := NewRef("#/responses/petResponse") - if assert.NoError(t, err) { - resolver, _ := defaultSchemaLoader(rootDoc, nil, nil) - if assert.NoError(t, resolver.Resolve(&ref, &tgt, basePath)) { - assert.Equal(t, rootDoc.Responses["petResponse"], tgt) - } - } - } -} - -func TestResolveForTransitiveRefs(t *testing.T) { - var spec *Swagger - rawSpec, err := ioutil.ReadFile("fixtures/specs/todos.json") - assert.NoError(t, err) - - basePath, err := absPath("fixtures/specs/todos.json") - assert.NoError(t, err) - - opts := &ExpandOptions{ - RelativeBase: basePath, - } - - err = json.Unmarshal(rawSpec, &spec) - assert.NoError(t, err) - - err = ExpandSpec(spec, opts) - assert.NoError(t, err) -} - -// PetStoreJSONMessage json raw message for Petstore20 -var PetStoreJSONMessage = json.RawMessage([]byte(PetStore20)) - -// PetStore20 json doc for swagger 2.0 pet store -const PetStore20 = `{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "Swagger Petstore", - "contact": { - "name": "Wordnik API Team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "petstore.swagger.wordnik.com", - "basePath": "/api", - "schemes": [ - "http" - ], - "paths": { - "/pets": { - "get": { - "security": [ - { - "basic": [] - } - ], - "tags": [ "Pet Operations" ], - "operationId": "getAllPets", - "parameters": [ - { - "name": "status", - "in": "query", - "description": "The status to filter by", - "type": "string" - }, - { - "name": "limit", - "in": "query", - "description": "The maximum number of results to return", - "type": "integer", - "format": "int64" - } - ], - "summary": "Finds all pets in the system", - "responses": { - "200": { - "description": "Pet response", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/Pet" - } - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "post": { - "security": [ - { - "basic": [] - } - ], - "tags": [ "Pet Operations" ], - "operationId": "createPet", - "summary": "Creates a new pet", - "consumes": ["application/x-yaml"], - "produces": ["application/x-yaml"], - "parameters": [ - { - "name": "pet", - "in": "body", - "description": "The Pet to create", - "required": true, - "schema": { - "$ref": "#/definitions/newPet" - } - } - ], - "responses": { - "200": { - "description": "Created Pet response", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - } - }, - "/pets/{id}": { - "delete": { - "security": [ - { - "apiKey": [] - } - ], - "description": "Deletes the Pet by id", - "operationId": "deletePet", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to delete", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "204": { - "description": "pet deleted" - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "get": { - "tags": [ "Pet Operations" ], - "operationId": "getPetById", - "summary": "Finds the pet by id", - "responses": { - "200": { - "description": "Pet response", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "default": { - "description": "Unexpected error", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - }, - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet", - "required": true, - "type": "integer", - "format": "int64" - } - ] - } - }, - "definitions": { - "Category": { - "id": "Category", - "properties": { - "id": { - "format": "int64", - "type": "integer" - }, - "name": { - "type": "string" - } - } - }, - "Pet": { - "id": "Pet", - "properties": { - "category": { - "$ref": "#/definitions/Category" - }, - "id": { - "description": "unique identifier for the pet", - "format": "int64", - "maximum": 100.0, - "minimum": 0.0, - "type": "integer" - }, - "name": { - "type": "string" - }, - "photoUrls": { - "items": { - "type": "string" - }, - "type": "array" - }, - "status": { - "description": "pet status in the store", - "enum": [ - "available", - "pending", - "sold" - ], - "type": "string" - }, - "tags": { - "items": { - "$ref": "#/definitions/Tag" - }, - "type": "array" - } - }, - "required": [ - "id", - "name" - ] - }, - "newPet": { - "anyOf": [ - { - "$ref": "#/definitions/Pet" - }, - { - "required": [ - "name" - ] - } - ] - }, - "Tag": { - "id": "Tag", - "properties": { - "id": { - "format": "int64", - "type": "integer" - }, - "name": { - "type": "string" - } - } - }, - "Error": { - "required": [ - "code", - "message" - ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - }, - "consumes": [ - "application/json", - "application/xml" - ], - "produces": [ - "application/json", - "application/xml", - "text/plain", - "text/html" - ], - "securityDefinitions": { - "basic": { - "type": "basic" - }, - "apiKey": { - "type": "apiKey", - "in": "header", - "name": "X-API-KEY" - } - } -} -` diff --git a/vendor/github.com/go-openapi/spec/external_docs.go b/vendor/github.com/go-openapi/spec/external_docs.go deleted file mode 100644 index 88add91b2..000000000 --- a/vendor/github.com/go-openapi/spec/external_docs.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -// ExternalDocumentation allows referencing an external resource for -// extended documentation. -// -// For more information: http://goo.gl/8us55a#externalDocumentationObject -type ExternalDocumentation struct { - Description string `json:"description,omitempty"` - URL string `json:"url,omitempty"` -} diff --git a/vendor/github.com/go-openapi/spec/external_docs_test.go b/vendor/github.com/go-openapi/spec/external_docs_test.go deleted file mode 100644 index 14c5ef156..000000000 --- a/vendor/github.com/go-openapi/spec/external_docs_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "testing" -) - -func TestIntegrationExternalDocs(t *testing.T) { - var extDocs = ExternalDocumentation{"the name", "the url"} - const extDocsYAML = "description: the name\nurl: the url\n" - const extDocsJSON = `{"description":"the name","url":"the url"}` - assertSerializeJSON(t, extDocs, extDocsJSON) - assertSerializeYAML(t, extDocs, extDocsYAML) - assertParsesJSON(t, extDocsJSON, extDocs) - assertParsesYAML(t, extDocsYAML, extDocs) -} diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/all-the-things.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/all-the-things.json deleted file mode 100644 index 42e6f24e0..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/expansion/all-the-things.json +++ /dev/null @@ -1,254 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "Swagger Petstore", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "Wordnik API Team" - }, - "license": { - "name": "MIT" - } - }, - "host": "petstore.swagger.wordnik.com", - "basePath": "/api", - "schemes": [ - "http" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "parameters": { - "idParam": { - "name": "id", - "in": "path", - "description": "ID of pet to fetch", - "required": true, - "type": "integer", - "format": "int64" - }, - "tag": { - "type": "string", - "in": "query", - "required": false - }, - "query": { - "$ref": "#/parameters/tag" - } - }, - "responses": { - "petResponse": { - "description": "pet response", - "schema": { - "$ref": "#/definitions/pet" - } - }, - "stringResponse": { - "descripion": "string response", - "schema": { - "type": "string" - } - }, - "anotherPet": { - "$ref": "#/responses/petResponse" - } - }, - "paths": { - "/": { - "get": { - "operationId": "indexStuff", - "responses": { - "default": { - "$ref": "#/responses/stringResponse" - }, - "200": { - "$ref": "#/responses/anotherPet" - } - } - } - }, - "/pets": { - "get": { - "description": "Returns all pets from the system that the user has access to", - "operationId": "findPets", - "produces": [ - "application/json", - "application/xml", - "text/xml", - "text/html" - ], - "parameters": [ - { - "name": "tags", - "in": "query", - "description": "tags to filter by", - "required": false, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - }, - { - "name": "limit", - "in": "query", - "description": "maximum number of results to return", - "required": false, - "type": "integer", - "format": "int32" - } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/pet" - } - } - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - }, - "post": { - "description": "Creates a new pet in the store. Duplicates are allowed", - "operationId": "addPet", - "produces": [ - "application/json" - ], - "parameters": [ - { - "name": "pet", - "in": "body", - "description": "Pet to add to the store", - "required": true, - "schema": { - "$ref": "#/definitions/petInput" - } - } - ], - "responses": { - "200": { "$ref": "#/responses/petResponse" }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - } - }, - "/pets/{id}": { - "get": { - "description": "Returns a user based on a single ID, if the user does not have access to the pet", - "operationId": "findPetById", - "produces": [ - "application/json", - "application/xml", - "text/xml", - "text/html" - ], - "parameters": [ - { - "$ref": "#/parameters/idParam" - } - ], - "responses": { - "200": { - "$ref": "#/responses/petResponse" - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - }, - "delete": { - "description": "deletes a single pet based on the ID supplied", - "operationId": "deletePet", - "parameters": [ - { - "$ref": "#/parameters/idParam" - } - ], - "responses": { - "204": { - "description": "pet deleted" - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - } - } - }, - "definitions": { - "pet": { - "required": [ - "id", - "name" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "petInput": { - "allOf": [ - { - "$ref": "#/definitions/pet" - }, - { - "required": [ - "name" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - } - } - } - ] - }, - "errorModel": { - "required": [ - "code", - "message" - ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/circularRefs.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/circularRefs.json deleted file mode 100644 index f501aa143..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/expansion/circularRefs.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "definitions": { - "brand": { - "type": "object", - "properties": { - "name": { - "type": "string" - } - } - }, - "category": { - "type": "object", - "properties": { - "children": { - "type": "array", - "items": { - "$ref": "#/definitions/category" - } - } - } - }, - "car": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "make": { - "type": "string" - }, - "similar": { - "items": { - "$ref": "#/definitions/car" - } - }, - "notSimilar": { - "additionalProperties": { - "$ref": "#/definitions/car" - } - }, - "oneCar": { - "$ref": "#/definitions/car" - }, - "category": { - "$ref": "#/definitions/category" - }, - "brand": { - "$ref": "#/definitions/brand" - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/circularSpec.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/circularSpec.json deleted file mode 100644 index 7b39b999b..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/expansion/circularSpec.json +++ /dev/null @@ -1 +0,0 @@ -{"swagger":"2.0","info":{"title":"Swagger Sample","description":"Sample API Playground.","version":"1.0.0"},"basePath":"/v1","schemes":["http"],"consumes":["application/vdn.sample.v1+json"],"produces":["application/vdn.sample.v1+json"],"paths":{"/books":{"get":{"summary":"List all books","operationId":"listBooks","tags":["books"],"responses":{"200":{"headers":{"Link":{"type":"string"}},"description":"An array of books","schema":{"type":"array","items":{"$ref":"#/definitions/Book"}}},"default":{"description":"generic error response","schema":{"$ref":"#/definitions/Error"}}}}}},"definitions":{"Book":{"type":"object","required":["title","summary"],"properties":{"title":{"type":"string","example":"Winnie the Pooh"},"summary":{"type":"string","example":"Famous children's book"},"related_books":{"type":"array","items":{"$ref":"#/definitions/Book"}}}},"Error":{"type":"object","readOnly":true,"properties":{"code":{"type":"integer","format":"int64","example":400},"message":{"type":"string","example":"Unexpected error"}},"required":["message"]}}} diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/circularSpec.yaml b/vendor/github.com/go-openapi/spec/fixtures/expansion/circularSpec.yaml deleted file mode 100644 index d43bd4640..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/expansion/circularSpec.yaml +++ /dev/null @@ -1,67 +0,0 @@ ---- -swagger: "2.0" -info: - title: Swagger Sample - description: Sample API Playground. - version: 1.0.0 -basePath: /v1 -schemes: -- http -consumes: -- application/vdn.sample.v1+json -produces: -- application/vdn.sample.v1+json - -paths: - /books: - get: - summary: List all books - operationId: listBooks - tags: - - books - responses: - 200: - headers: - Link: - type: string - description: An array of books - schema: - type: array - items: - $ref: "#/definitions/Book" - default: - description: generic error response - schema: - $ref: "#/definitions/Error" - -definitions: - Book: - type: object - required: - - title - - summary - properties: - title: - type: string - example: Winnie the Pooh - summary: - type: string - example: Famous children's book - related_books: - type: array - items: - $ref: "#/definitions/Book" - - Error: - type: object - readOnly: true - properties: - code: - type: integer - format: int64 - example: 400 - message: - type: string - example: Unexpected error - required: - - message diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/clickmeter.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/clickmeter.json deleted file mode 100644 index 27e819aa5..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/expansion/clickmeter.json +++ /dev/null @@ -1 +0,0 @@ -{"swagger":"2.0","schemes":["http","https"],"host":"apiv2.clickmeter.com:80","info":{"contact":{"email":"api@clickmeter.com","name":"Api Support","url":"http://www.clickmeter.com/api"},"description":"Api dashboard for ClickMeter API","title":"ClickMeter","version":"v2","x-logo":{"url":"https://s3.amazonaws.com/clickmeter.com/Web/static/cmlogo.svg"},"x-origin":{"format":"swagger","url":"http://api.v2.clickmeter.com.s3.amazonaws.com/docs/api-docs-v2.json","version":"2.0"},"x-providerName":"clickmeter.com"},"securityDefinitions":{"api_key":{"description":"API Key Authentication","in":"header","name":"X-Clickmeter-AuthKey","type":"apiKey"}},"security":[{"api_key":[]}],"paths":{"/account":{"get":{"consumes":[],"deprecated":false,"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.User"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve current account data","tags":["Account"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.User"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.User"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Update current account data","tags":["Account"]}},"/account/domainwhitelist":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.DomainWhitelistEntry]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve list of a domains allowed to redirect in DDU mode","tags":["Account"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The entry to add","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Create an domain entry","tags":["Account"]}},"/account/domainwhitelist/{whitelistId}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"The id of the domain to delete","in":"path","name":"whitelistId","required":true,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Delete an domain entry","tags":["Account"]}},"/account/guests":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve list of a guest","tags":["Account"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Guest object to create","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.Guest"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.Guest"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Create a guest","tags":["Account"]}},"/account/guests/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve count of guests","tags":["Account"]}},"/account/guests/{guestId}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the guest","format":"int64","in":"path","name":"guestId","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Delete a guest","tags":["Account"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the guest","format":"int64","in":"path","name":"guestId","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.Guest"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a guest","tags":["Account"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the guest","format":"int64","in":"path","name":"guestId","required":true,"type":"integer"},{"description":"Guest object with field updated","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.Guest"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.Guest"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Update a guest","tags":["Account"]}},"/account/guests/{guestId}/permissions":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the guest","format":"int64","in":"path","name":"guestId","required":true,"type":"integer"},{"description":"Can be \"datapoint\" or \"group\"","enum":["datapoint","group"],"in":"query","name":"entityType","required":false,"type":"string"},{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Can be \"w\" or \"r\"","enum":["r","w"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Optional id of the datapoint/group entity to filter by","format":"int64","in":"query","name":"entityId","required":false,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Grants.Grant]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve permissions for a guest","tags":["Account"]}},"/account/guests/{guestId}/permissions/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the guest","format":"int64","in":"path","name":"guestId","required":true,"type":"integer"},{"description":"Can be \"datapoint\" or \"group\"","enum":["datapoint","group"],"in":"query","name":"entityType","required":false,"type":"string"},{"description":"Can be \"w\" or \"r\"","enum":["r","w"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Optional id of the datapoint/group entity to filter by","format":"int64","in":"query","name":"entityId","required":false,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve count of the permissions for a guest","tags":["Account"]}},"/account/guests/{guestId}/{type}/permissions/patch":{"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the guest","format":"int64","in":"path","name":"guestId","required":true,"type":"integer"},{"description":"Can be \"datapoint\" or \"group\"","enum":["datapoint","group"],"in":"path","name":"type","required":true,"type":"string"},{"description":"The patch permission request","in":"body","name":"body","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.PermissionPatchRequest"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Change the permission on a shared object","tags":["Account"]},"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the guest","format":"int64","in":"path","name":"guestId","required":true,"type":"integer"},{"description":"Can be \"datapoint\" or \"group\"","enum":["datapoint","group"],"in":"path","name":"type","required":true,"type":"string"},{"description":"The patch permission request","in":"body","name":"body","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.PermissionPatchRequest"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Change the permission on a shared object","tags":["Account"]}},"/account/ipblacklist":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.IpBlacklistEntry]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve list of a ip to exclude from event tracking","tags":["Account"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The entry to add","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Create an ip blacklist entry","tags":["Account"]}},"/account/ipblacklist/{blacklistId}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"The id of the ip to delete","in":"path","name":"blacklistId","required":true,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Delete an ip blacklist entry","tags":["Account"]}},"/account/plan":{"get":{"consumes":[],"deprecated":false,"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.Plan"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve current account plan","tags":["Account"]}},"/aggregated":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"If using \"yesterday\" or \"today\" timeframe you can ask for the hourly detail","in":"query","name":"hourly","required":false,"type":"boolean"},{"description":"","in":"query","name":"onlyFavorites","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this customer for a timeframe","tags":["Aggregated"]}},"/aggregated/list":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"The temporal entity you want to group by (\"week\"/\"month\"). If unspecified is \"day\".","enum":["week","month"],"in":"query","name":"groupBy","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this customer for a timeframe grouped by some temporal entity (day/week/month)","tags":["Aggregated"]}},"/aggregated/summary/conversions":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Status of conversion (\"deleted\"/\"active\")","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about a subset of conversions for a timeframe with conversions data","tags":["Aggregated"]}},"/aggregated/summary/datapoints":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"Type of datapoint (\"tl\"/\"tp\")","enum":["tp","tl"],"in":"query","name":"type","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Status of datapoint (\"deleted\"/\"active\"/\"paused\"/\"spam\")","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the datapoint marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Filter by this group id","format":"int64","in":"query","name":"groupId","required":false,"type":"integer"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about a subset of datapoints for a timeframe with datapoints data","tags":["Aggregated"]}},"/aggregated/summary/groups":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Status of group (\"deleted\"/\"active\")","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the group marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about a subset of groups for a timeframe with groups data","tags":["Aggregated"]}},"/clickstream":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Filter by this group id (mutually exclusive with \"datapoint\" and \"conversion\")","format":"int64","in":"query","name":"group","required":false,"type":"integer"},{"description":"Filter by this datapoint id (mutually exclusive with \"group\" and \"conversion\")","format":"int64","in":"query","name":"datapoint","required":false,"type":"integer"},{"description":"Filter by this conversion id (mutually exclusive with \"datapoint\" and \"group\")","format":"int64","in":"query","name":"conversion","required":false,"type":"integer"},{"default":50,"description":"Limit results to this number","format":"int32","in":"query","name":"pageSize","required":false,"type":"integer"},{"description":"Filter event type (\"spiders\"/\"uniques\"/\"nonuniques\"/\"conversions\")","enum":["","spiders","uniques","nonuniques","conversions"],"in":"query","name":"filter","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.ClickStream.Hit]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve the latest list of events of this account. Limited to last 100.","tags":["ClickStream"]}},"/conversions":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Status of conversion (\"deleted\"/\"active\")","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude conversions created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude conversions created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a list of conversions","tags":["Conversions"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The body of the conversion","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Conversions.Conversion"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Create a conversion","tags":["Conversions"]}},"/conversions/aggregated/list":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Status of conversion (\"deleted\"/\"active\")","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"The temporal entity you want to group by (\"week\"/\"month\"). If unspecified is \"day\".","enum":["week","month"],"in":"query","name":"groupBy","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this customer for a timeframe related to a subset of conversions grouped by some temporal entity (day/week/month)","tags":["Conversions"]}},"/conversions/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Status of conversion (\"deleted\"/\"active\")","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude conversions created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude conversions created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a count of conversions","tags":["Conversions"]}},"/conversions/{conversionId}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Delete conversion specified by id","tags":["Conversions"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Conversions.Conversion"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve conversion specified by id","tags":["Conversions"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Updated body of the conversion","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Conversions.Conversion"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Update conversion specified by id","tags":["Conversions"]}},"/conversions/{conversionId}/aggregated":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Filter by this tag name","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the datapoint marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"},{"description":"If using \"yesterday\" or \"today\" timeframe you can ask for the hourly detail","in":"query","name":"hourly","required":false,"type":"boolean"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this conversion for a timeframe","tags":["Conversions"]}},"/conversions/{conversionId}/aggregated/list":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"The temporal entity you want to group by (\"week\"/\"month\"). If unspecified is \"day\".","enum":["week","month"],"in":"query","name":"groupBy","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this conversion for a timeframe grouped by some temporal entity (day/week/month)","tags":["Conversions"]}},"/conversions/{conversionId}/datapoints":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Type of datapoint (\"tl\"/\"tp\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Status of datapoint (\"deleted\"/\"active\"/\"paused\"/\"spam\")","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Filter by this tag name","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a list of datapoints connected to this conversion","tags":["Conversions"]}},"/conversions/{conversionId}/datapoints/batch/patch":{"put":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Patch requests","in":"body","name":"data","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.PatchBodyBatch"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Modify the association between a conversion and multiple datapoints","tags":["Conversions"]}},"/conversions/{conversionId}/datapoints/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Type of datapoint (\"tl\"/\"tp\")","in":"query","name":"type","required":false,"type":"string"},{"description":"Status of datapoint (\"deleted\"/\"active\"/\"paused\"/\"spam\")","in":"query","name":"status","required":false,"type":"string"},{"description":"Filter by this tag name","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a count of datapoints connected to this conversion","tags":["Conversions"]}},"/conversions/{conversionId}/datapoints/patch":{"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Patch request","in":"body","name":"data","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.ConversionPatchBody"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Modify the association between a conversion and a datapoint","tags":["Conversions"]}},"/conversions/{conversionId}/hits":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Offset where to start from (it's the lastKey field in the response object)","in":"query","name":"offset","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Filter event type (\"spiders\"/\"uniques\"/\"nonuniques\"/\"conversions\")","enum":["spiders","uniques","nonuniques","conversions"],"in":"query","name":"filter","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitListPage"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve the list of events related to this conversion.","tags":["Conversions"]}},"/conversions/{conversionId}/notes":{"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Patch requests","in":"body","name":"note","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.GenericTextPatch"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Fast patch the \"notes\" field of a conversion","tags":["Conversions"]}},"/conversions/{conversionId}/reports":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the conversion","format":"int64","in":"path","name":"conversionId","required":true,"type":"integer"},{"description":"Type of the report.","enum":["datapoints","groups","browsers","browsersfamilies","platforms","cities","countries","keywords","referrers","convparameters","destinations","languages","params"],"in":"query","name":"type","required":true,"type":"string"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","beginning","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"Type of the event you want to filter this report with. By default no filter is applied.","enum":["clicks","views"],"in":"query","name":"hittype","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Tops.Top"}},"401":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a top report connected to this conversion","tags":["Conversions"]}},"/datapoints":{"get":{"consumes":[],"deprecated":false,"parameters":[{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Type of the datapoint (\"tp\"/\"tl\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Filter fields by favourite status","in":"query","name":"onlyFavorites","required":false,"type":"boolean"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the datapoints associated to the user","tags":["DataPoints"]},"post":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The body of the datapoint","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.Datapoint"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Create a datapoint","tags":["DataPoints"]}},"/datapoints/aggregated":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"Type of datapoint (\"tl\"/\"tp\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"If using \"yesterday\" or \"today\" timeframe you can ask for the hourly detail","in":"query","name":"hourly","required":false,"type":"boolean"},{"description":"Status of datapoint (\"deleted\"/\"active\"/\"paused\"/\"spam\")","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the datapoint is marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this customer for a timeframe by groups","tags":["DataPoints"]}},"/datapoints/aggregated/list":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Type of datapoint (\"tl\"/\"tp\")","enum":["tp","tl"],"in":"query","name":"type","required":true,"type":"string"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Status of datapoint (\"deleted\"/\"active\"/\"paused\"/\"spam\")","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the datapoint is marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"},{"description":"The temporal entity you want to group by (\"week\"/\"month\"). If unspecified is \"day\".","enum":["week","month"],"in":"query","name":"groupBy","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about all datapoints of this customer for a timeframe grouped by some temporal entity (day/week/month)","tags":["DataPoints"]}},"/datapoints/batch":{"delete":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"A json containing the datapoints to delete.","in":"body","name":"batch","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.DeleteBatch"}}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Delete multiple datapoints","tags":["DataPoints"]},"post":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"A json containing the datapoints to update.","in":"body","name":"batch","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.DatapointsBatch"}}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Update multiple datapoints","tags":["DataPoints"]},"put":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"A json containing the datapoints to create.","in":"body","name":"batch","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.DatapointsBatch"}}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Create multiple datapoints","tags":["DataPoints"]}},"/datapoints/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Type of the datapoint (\"tp\"/\"tl\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Filter fields by favourite status","in":"query","name":"onlyFavorites","required":false,"type":"boolean"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Count the datapoints associated to the user","tags":["DataPoints"]}},"/datapoints/{id}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"The id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Delete a datapoint","tags":["DataPoints"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"The id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.Datapoint"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Get a datapoint","tags":["DataPoints"]},"post":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"The body of the datapoint","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.Datapoint"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Update a datapoint","tags":["DataPoints"]}},"/datapoints/{id}/aggregated":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"If using \"yesterday\" or \"today\" timeframe you can ask for the hourly detail","in":"query","name":"hourly","required":false,"type":"boolean"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this datapoint for a timeframe","tags":["DataPoints"]}},"/datapoints/{id}/aggregated/list":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"The temporal entity you want to group by (\"week\"/\"month\"). If unspecified is \"day\".","enum":["week","month"],"in":"query","name":"groupBy","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this datapoint for a timeframe grouped by some temporal entity (day/week/month)","tags":["DataPoints"]}},"/datapoints/{id}/favourite":{"put":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Fast switch the \"favourite\" field of a datapoint","tags":["DataPoints"]}},"/datapoints/{id}/hits":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Offset where to start from (it's the lastKey field in the response object)","in":"query","name":"offset","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Filter event type (\"spiders\"/\"uniques\"/\"nonuniques\"/\"conversions\")","enum":["spiders","uniques","nonuniques","conversions"],"in":"query","name":"filter","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitListPage"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve the list of events related to this datapoint.","tags":["DataPoints"]}},"/datapoints/{id}/notes":{"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Patch requests","in":"body","name":"note","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.GenericTextPatch"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Fast patch the \"notes\" field of a datapoint","tags":["DataPoints"]}},"/datapoints/{id}/reports":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the datapoint","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Type of the report.","enum":["browsers","browsersfamilies","platforms","cities","countries","isps","ips","oss","ossfamilies","keywords","referrers","destinations","languages","params"],"in":"query","name":"type","required":true,"type":"string"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","beginning","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Tops.Top"}},"401":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a top report connected to this datapoint","tags":["DataPoints"]}},"/domains":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"default":"system","description":"Type of domain (\"system\"/\"go\"/\"personal\"/\"dedicated\"). If not specified default is \"system\"","enum":["system","go","personal","dedicated"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Filter domains with this anmen","in":"query","name":"name","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a list of domains","tags":["Domains"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The domain to create","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Domains.Domain"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Create a domain","tags":["Domains"]}},"/domains/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"default":"system","description":"Type of domain (\"system\"/\"go\"/\"personal\"/\"dedicated\"). If not specified default is \"system\"","enum":["system","go","personal","dedicated"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Filter domains with this anmen","in":"query","name":"name","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve count of domains","tags":["Domains"]}},"/domains/{id}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of domain","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Delete a domain","tags":["Domains"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of domain","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Domains.Domain"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Get a domain","tags":["Domains"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of domain","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"The domain to update","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Domains.Domain"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Update a domain","tags":["Domains"]}},"/groups":{"get":{"consumes":[],"deprecated":false,"parameters":[{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Status of the group","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude groups created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude groups created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"},{"description":"Write permission","in":"query","name":"write","required":false,"type":"boolean"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the groups associated to the user.","tags":["Groups"]},"post":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The body of the group","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Groups.Group"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Create a group","tags":["Groups"]}},"/groups/aggregated":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"If using \"yesterday\" or \"today\" timeframe you can ask for the hourly detail","in":"query","name":"hourly","required":false,"type":"boolean"},{"description":"Status of group (\"deleted\"/\"active\")","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the group is marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this customer for a timeframe by groups","tags":["Groups"]}},"/groups/aggregated/list":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Status of group (\"deleted\"/\"active\")","in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the group is marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"},{"description":"The temporal entity you want to group by (\"week\"/\"month\"). If unspecified is \"day\".","enum":["deleted","active"],"in":"query","name":"groupBy","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about all groups of this customer for a timeframe grouped by some temporal entity (day/week/month)","tags":["Groups"]}},"/groups/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Status of the datapoint","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude groups created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude groups created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"},{"description":"Write permission","in":"query","name":"write","required":false,"type":"boolean"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Count the groups associated to the user.","tags":["Groups"]}},"/groups/{id}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Delete group specified by id","tags":["Groups"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"The id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Groups.Group"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Get a group","tags":["Groups"]},"post":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"The body of the group","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Groups.Group"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Update a group","tags":["Groups"]}},"/groups/{id}/aggregated":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"If using \"yesterday\" or \"today\" timeframe you can ask for the hourly detail","in":"query","name":"hourly","required":false,"type":"boolean"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this group for a timeframe","tags":["Groups"]}},"/groups/{id}/aggregated/list":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"The temporal entity you want to group by (\"week\"/\"month\"). If unspecified is \"day\".","enum":["week","month"],"in":"query","name":"groupBy","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about this group for a timeframe grouped by some temporal entity (day/week/month)","tags":["Groups"]}},"/groups/{id}/aggregated/summary":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Filter by this group id","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["today","yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","last12months","lastyear","currentyear","beginning","custom"],"in":"query","name":"timeFrame","required":true,"type":"string"},{"description":"Type of datapoint (\"tl\"/\"tp\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Status of datapoint (\"deleted\"/\"active\"/\"paused\"/\"spam\")","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tag","required":false,"type":"string"},{"description":"Is the datapoint marked as favourite","in":"query","name":"favourite","required":false,"type":"boolean"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"default":0,"description":"Offset where to start from","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve statistics about a subset of datapoints for a timeframe with datapoints data","tags":["Groups"]}},"/groups/{id}/datapoints":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Type of the datapoint (\"tp\"/\"tl\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Filter fields by favourite status","in":"query","name":"onlyFavorites","required":false,"type":"boolean"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the datapoints associated to the user in this group.","tags":["Groups"]},"post":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"The body of the datapoint","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.Datapoint"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Create a datapoint in this group","tags":["Groups"]}},"/groups/{id}/datapoints/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Type of the datapoint (\"tp\"/\"tl\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Filter fields by favourite status","in":"query","name":"onlyFavorites","required":false,"type":"boolean"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Count the datapoints associated to the user in this group.","tags":["Groups"]}},"/groups/{id}/favourite":{"put":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Fast switch the \"favourite\" field of a group","tags":["Groups"]}},"/groups/{id}/hits":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"Limit results to this number","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Offset where to start from (it's the lastKey field in the response object)","in":"query","name":"offset","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Filter event type (\"spiders\"/\"uniques\"/\"nonuniques\"/\"conversions\")","enum":["spiders","uniques","nonuniques","conversions"],"in":"query","name":"filter","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitListPage"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve the list of events related to this group.","tags":["Groups"]}},"/groups/{id}/notes":{"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Patch requests","in":"body","name":"note","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.GenericTextPatch"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Fast patch the \"notes\" field of a group","tags":["Groups"]}},"/groups/{id}/reports":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Type of the report.","enum":["browsers","browsersfamilies","platforms","cities","countries","isps","ips","oss","ossfamilies","keywords","referrers","destinations","languages","params"],"in":"query","name":"type","required":true,"type":"string"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","beginning","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"Type of the event you want to filter this report with. By default no filter is applied.","enum":["clicks","views"],"in":"query","name":"hittype","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Tops.Top"}},"401":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a top report connected to this group","tags":["Groups"]}},"/hits":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"Limit results to this number","format":"int32","in":"query","name":"limit","required":false,"type":"integer"},{"description":"Offset where to start from (it's the lastKey field in the response object)","in":"query","name":"offset","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"},{"description":"Filter event type (\"spiders\"/\"uniques\"/\"nonuniques\"/\"conversions\")","enum":["spiders","uniques","nonuniques","conversions"],"in":"query","name":"filter","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitListPage"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve the list of events related to this account.","tags":["Hits"]}},"/me":{"get":{"consumes":[],"deprecated":false,"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.User"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve current account data","tags":["Me"]}},"/me/plan":{"get":{"consumes":[],"deprecated":false,"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Accounting.Plan"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve current account plan","tags":["Me"]}},"/reports":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Type of the report.","enum":["browsers","browsersfamilies","platforms","cities","countries","isps","ips","oss","ossfamilies","keywords","referrers","destinations","languages","params"],"in":"query","name":"type","required":true,"type":"string"},{"description":"Timeframe of the request. See list at $timeframeList","enum":["yesterday","last7","last30","lastmonth","currentmonth","previousmonth","last90","last120","last180","beginning","custom"],"in":"query","name":"timeframe","required":true,"type":"string"},{"description":"Type of the event you want to filter this report with. By default no filter is applied.","in":"query","name":"hittype","required":false,"type":"string"},{"description":"Filter by this group id (mutually exclusive with \"datapoint\" and \"conversion\")","format":"int64","in":"query","name":"group","required":false,"type":"integer"},{"description":"Filter by this datapoint id (mutually exclusive with \"group\" and \"conversion\")","format":"int64","in":"query","name":"datapoint","required":false,"type":"integer"},{"description":"Filter by this conversion id (mutually exclusive with \"datapoint\" and \"group\")","format":"int64","in":"query","name":"conversion","required":false,"type":"integer"},{"description":"If using a \"custom\" timeFrame you can specify the starting day (YYYYMMDD)","in":"query","name":"fromDay","required":false,"type":"string"},{"description":"If using a \"custom\" timeFrame you can specify the ending day (YYYYMMDD)","in":"query","name":"toDay","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Tops.Top"}},"401":{"description":"Forbidden"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a top report","tags":["Reports"]}},"/retargeting":{"get":{"consumes":[],"deprecated":false,"parameters":[{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the retargeting scripts associated to the user","tags":["Retargeting"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The body of the retargeting script","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Retargeting.RetargetingScript"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Creates a retargeting script","tags":["Retargeting"]}},"/retargeting/count":{"get":{"consumes":[],"deprecated":false,"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve count of retargeting scripts","tags":["Retargeting"]}},"/retargeting/{id}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"The id of the retargeting script","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Deletes a retargeting script (and remove associations)","tags":["Retargeting"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"The id of the retargeting script","format":"int64","in":"path","name":"id","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Retargeting.RetargetingScript"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Get a retargeting script object","tags":["Retargeting"]},"post":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The id of the retargeting script","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"The body of the retargeting script","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Retargeting.RetargetingScript"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Updates a retargeting script","tags":["Retargeting"]}},"/retargeting/{id}/datapoints":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the retargeting script","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Filter fields by favourite status","in":"query","name":"onlyFavorites","required":false,"type":"boolean"},{"description":"Field to sort by","in":"query","name":"sortBy","required":false,"type":"string"},{"description":"Direction of sort \"asc\" or \"desc\"","enum":["asc","desc"],"in":"query","name":"sortDirection","required":false,"type":"string"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the datapoints associated to the retargeting script.","tags":["Retargeting"]}},"/retargeting/{id}/datapoints/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the group","format":"int64","in":"path","name":"id","required":true,"type":"integer"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"A comma separated list of tags you want to filter with.","in":"query","name":"tags","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Filter fields by favourite status","in":"query","name":"onlyFavorites","required":false,"type":"boolean"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Count the datapoints associated to the retargeting script.","tags":["Retargeting"]}},"/tags":{"get":{"consumes":[],"deprecated":false,"parameters":[{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Name of the tag","in":"query","name":"name","required":false,"type":"string"},{"description":"Comma separated list of datapoints id to filter by","in":"query","name":"datapoints","required":false,"type":"string"},{"description":"Comma separated list of groups id to filter by","in":"query","name":"groups","required":false,"type":"string"},{"description":"Type of entity related to the tag","enum":["tp","tl","dp","gr"],"in":"query","name":"type","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the groups associated to the user filtered by this tag.","tags":["Tags"]},"post":{"consumes":["application/json","text/json","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"The body of the tag","in":"body","name":"value","required":true,"schema":{"$ref":"#/definitions/Api.Core.Dto.Tags.Tag"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Create a tag","tags":["Tags"]}},"/tags/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Name of the tag","in":"query","name":"name","required":false,"type":"string"},{"description":"Comma separated list of datapoints id to filter by","in":"query","name":"datapoints","required":false,"type":"string"},{"description":"Comma separated list of groups id to filter by","in":"query","name":"groups","required":false,"type":"string"},{"description":"Type of entity related to the tag","enum":["tp","tl","dp","gr"],"in":"query","name":"type","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/System.Object"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the groups associated to the user filtered by this tag.","tags":["Tags"]}},"/tags/{tagId}":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/System.Object"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Delete a tag","tags":["Tags"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Dto.Tags.Tag"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Retrieve a tag","tags":["Tags"]}},"/tags/{tagId}/datapoints":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Delete the association of this tag with all datapoints","tags":["Tags"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag.","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"},{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Type of the datapoint (\"tp\"/\"tl\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the datapoints associated to the user filtered by this tag","tags":["Tags"]}},"/tags/{tagId}/datapoints/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag.","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"},{"description":"Type of the datapoint (\"tp\"/\"tl\")","enum":["tp","tl"],"in":"query","name":"type","required":false,"type":"string"},{"description":"Status of the datapoint","enum":["deleted","active","paused","spam"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude datapoints created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude datapoints created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Count the datapoints associated to the user filtered by this tag","tags":["Tags"]}},"/tags/{tagId}/datapoints/patch":{"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the tag","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"},{"description":"The body patch","in":"body","name":"data","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.PatchBody"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Associate/Deassociate a tag with a datapoint","tags":["Tags"]}},"/tags/{tagId}/groups":{"delete":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Delete the association of this tag with all groups","tags":["Tags"]},"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag.","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"},{"default":0,"description":"Where to start when retrieving elements. Default is 0 if not specified.","format":"int32","in":"query","minLength":0,"name":"offset","required":false,"type":"integer"},{"default":20,"description":"Maximum elements to retrieve. Default to 20 if not specified.","format":"int32","in":"query","maxLength":0,"minLength":0,"name":"limit","required":false,"type":"integer"},{"description":"Status of the datapoint","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude groups created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude groups created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"List of all the groups associated to the user filtered by this tag.","tags":["Tags"]}},"/tags/{tagId}/groups/count":{"get":{"consumes":[],"deprecated":false,"parameters":[{"description":"Id of the tag.","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"},{"description":"Status of the datapoint","enum":["deleted","active"],"in":"query","name":"status","required":false,"type":"string"},{"description":"Filter fields by this pattern","in":"query","name":"textSearch","required":false,"type":"string"},{"description":"Exclude groups created before this date (YYYYMMDD)","in":"query","name":"createdAfter","required":false,"type":"string"},{"description":"Exclude groups created after this date (YYYYMMDD)","in":"query","name":"createdBefore","required":false,"type":"string"}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.CountResponce"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Count the groups associated to the user filtered by this tag","tags":["Tags"]}},"/tags/{tagId}/groups/patch":{"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the tag","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"},{"description":"The body patch","in":"body","name":"data","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.PatchBody"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"404":{"description":"Not found"},"500":{"description":"Internal Server Error"}},"summary":"Associate/Deassociate a tag with a group","tags":["Tags"]}},"/tags/{tagId}/name":{"put":{"consumes":["application/json","text/json","application/xml","text/xml","application/x-www-form-urlencoded"],"deprecated":false,"parameters":[{"description":"Id of the tag","format":"int64","in":"path","name":"tagId","required":true,"type":"integer"},{"description":"The body patch","in":"body","name":"data","required":true,"schema":{"$ref":"#/definitions/Api.Core.Requests.GenericTextPatch"}}],"produces":["application/json","text/json","application/xml","text/xml"],"responses":{"200":{"description":"","schema":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"}},"401":{"description":"Unauthorized"},"500":{"description":"Internal Server Error"}},"summary":"Fast patch a tag name","tags":["Tags"]}}},"definitions":{"Api.Core.Dto.Accounting.ConversionOptions":{"properties":{"hideComCost":{"type":"boolean"},"hideCost":{"type":"boolean"},"hideCount":{"type":"boolean"},"hideParams":{"type":"boolean"},"hideValue":{"type":"boolean"},"percentCommission":{"format":"int32","type":"integer"},"percentValue":{"format":"int32","type":"integer"}},"type":"object"},"Api.Core.Dto.Accounting.DomainWhitelistEntry":{"properties":{"id":{"type":"string"},"name":{"type":"string"}},"type":"object"},"Api.Core.Dto.Accounting.ExtendedGrants":{"properties":{"allowAllGrants":{"type":"boolean"},"allowGroupCreation":{"type":"boolean"}},"type":"object"},"Api.Core.Dto.Accounting.Guest":{"properties":{"apiKey":{"type":"string"},"conversionOptions":{"$ref":"#/definitions/Api.Core.Dto.Accounting.ConversionOptions"},"creationDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"currentGrant":{"$ref":"#/definitions/Api.Core.Dto.Grants.Grant"},"dateFormat":{"type":"string"},"decimalSeparator":{"type":"string"},"email":{"type":"string"},"extendedGrants":{"$ref":"#/definitions/Api.Core.Dto.Accounting.ExtendedGrants"},"groupGrants":{"format":"int64","type":"integer"},"hitOptions":{"$ref":"#/definitions/Api.Core.Dto.Accounting.HitOptions"},"id":{"format":"int64","type":"integer"},"key":{"type":"string"},"language":{"type":"string"},"loginCount":{"format":"int32","type":"integer"},"name":{"type":"string"},"notes":{"type":"string"},"numberGroupSeparator":{"type":"string"},"password":{"type":"string"},"timeFormat":{"enum":["AmPm","H24"],"type":"string"},"timeZone":{"format":"int32","type":"integer"},"timeframeMinDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"timezonename":{"type":"string"},"tlGrants":{"format":"int64","type":"integer"},"tpGrants":{"format":"int64","type":"integer"},"userName":{"type":"string"}},"type":"object"},"Api.Core.Dto.Accounting.HitOptions":{"properties":{"hideReferrer":{"type":"boolean"}},"type":"object"},"Api.Core.Dto.Accounting.IpBlacklistEntry":{"properties":{"id":{"type":"string"},"ip":{"type":"string"}},"type":"object"},"Api.Core.Dto.Accounting.Plan":{"properties":{"allowedPersonalDomains":{"format":"int32","type":"integer"},"allowedPersonalUrls":{"format":"int32","type":"integer"},"billingPeriodEnd":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"billingPeriodStart":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"bonusMonthlyEvents":{"format":"int64","type":"integer"},"maximumDatapoints":{"format":"int64","type":"integer"},"maximumGuests":{"format":"int64","type":"integer"},"monthlyEvents":{"format":"int64","type":"integer"},"name":{"type":"string"},"price":{"format":"double","type":"number"},"profileId":{"format":"int64","type":"integer"},"recurring":{"type":"boolean"},"recurringPeriod":{"format":"int32","type":"integer"},"usedDatapoints":{"format":"int64","type":"integer"},"usedMonthlyEvents":{"format":"int64","type":"integer"}},"type":"object"},"Api.Core.Dto.Accounting.User":{"properties":{"boGoVal":{"type":"string"},"bonusClicks":{"format":"int64","type":"integer"},"companyName":{"type":"string"},"companyRole":{"type":"string"},"email":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"phone":{"type":"string"},"redirectOnly":{"type":"boolean"},"registrationDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"timeframeMinDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"timezone":{"format":"int32","type":"integer"},"timezonename":{"type":"string"}},"type":"object"},"Api.Core.Dto.Aggregated.AggregatedResult":{"properties":{"activityDay":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"commissionsCost":{"format":"double","type":"number"},"conversionsCost":{"format":"double","type":"number"},"conversionsValue":{"format":"double","type":"number"},"convertedClicks":{"format":"int64","type":"integer"},"entityData":{"$ref":"#/definitions/System.Object"},"entityId":{"type":"string"},"fromDay":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"hourlyBreakDown":{"additionalProperties":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"},"type":"object"},"lastHitDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"spiderHitsCount":{"format":"int64","type":"integer"},"toDay":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"totalClicks":{"format":"int64","type":"integer"},"totalViews":{"format":"int64","type":"integer"},"uniqueClicks":{"format":"int64","type":"integer"},"uniqueConversions":{"format":"int64","type":"integer"},"uniqueViews":{"format":"int64","type":"integer"}},"type":"object"},"Api.Core.Dto.Aggregated.AggregatedSummaryResult":{"properties":{"count":{"format":"int64","type":"integer"},"limit":{"format":"int32","type":"integer"},"offset":{"format":"int64","type":"integer"},"result":{"items":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"},"type":"array"}},"type":"object"},"Api.Core.Dto.ClickStream.Hit":{"properties":{"accessTime":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"browser":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitBrowserInfo"},"clientLanguage":{"type":"string"},"conversion1":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo"},"conversion2":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo"},"conversion3":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo"},"conversion4":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo"},"conversion5":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo"},"conversions":{"items":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo"},"type":"array"},"entity":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitDatapointInfo"},"ip":{"type":"string"},"isProxy":{"type":"string"},"isSpider":{"type":"string"},"isUnique":{"type":"string"},"location":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitLocationInfo"},"org":{"type":"string"},"os":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitOsInfo"},"queryParams":{"type":"string"},"realDestinationUrl":{"type":"string"},"referer":{"type":"string"},"source":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.HitSource"},"type":{"type":"string"}},"type":"object"},"Api.Core.Dto.ClickStream.HitBrowserInfo":{"properties":{"browserType":{"type":"string"},"familyId":{"format":"int64","type":"integer"},"familyName":{"type":"string"},"id":{"format":"int64","type":"integer"},"name":{"type":"string"}},"type":"object"},"Api.Core.Dto.ClickStream.HitConversionInfo":{"properties":{"accessTime":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"comcost":{"format":"double","type":"number"},"cost":{"format":"double","type":"number"},"date":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"deleted":{"type":"boolean"},"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"parameter":{"type":"string"},"value":{"format":"double","type":"number"}},"type":"object"},"Api.Core.Dto.ClickStream.HitDatapointInfo":{"properties":{"creationDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"datapointFavourite":{"type":"boolean"},"datapointId":{"format":"int64","type":"integer"},"datapointName":{"type":"string"},"datapointTitle":{"type":"string"},"datapointType":{"type":"string"},"destinationUrl":{"type":"string"},"groupId":{"format":"int64","type":"integer"},"groupName":{"type":"string"},"isABTest":{"type":"boolean"},"isPrivateShared":{"type":"boolean"},"isPublic":{"type":"boolean"},"notes":{"type":"string"},"status":{"enum":["Active","Paused","Abuse","Deleted"],"type":"string"},"tags":{"items":{"$ref":"#/definitions/Api.Core.Dto.Tags.Tag"},"type":"array"},"trackingCode":{"type":"string"}},"type":"object"},"Api.Core.Dto.ClickStream.HitListPage":{"properties":{"hits":{"items":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.Hit"},"type":"array"},"lastKey":{"type":"string"}},"type":"object"},"Api.Core.Dto.ClickStream.HitLocationInfo":{"properties":{"areacode":{"type":"string"},"city":{"type":"string"},"country":{"type":"string"},"latitude":{"format":"double","type":"number"},"longitude":{"format":"double","type":"number"},"metrocode":{"type":"string"},"organization":{"type":"string"},"postalcode":{"type":"string"},"region":{"type":"string"},"regionName":{"type":"string"}},"type":"object"},"Api.Core.Dto.ClickStream.HitOsInfo":{"properties":{"familyId":{"format":"int64","type":"integer"},"familyName":{"type":"string"},"id":{"format":"int64","type":"integer"},"name":{"type":"string"}},"type":"object"},"Api.Core.Dto.ClickStream.HitSource":{"properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"param":{"type":"string"}},"type":"object"},"Api.Core.Dto.Conversions.Conversion":{"properties":{"code":{"type":"string"},"creationDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"deleted":{"type":"boolean"},"description":{"type":"string"},"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"protocol":{"enum":["Http","Https"],"type":"string"},"value":{"format":"double","type":"number"}},"type":"object"},"Api.Core.Dto.Datapoints.BrowserBaseDestinationItem":{"properties":{"emailDestinationUrl":{"type":"string"},"mobileDestinationUrl":{"type":"string"},"spidersDestinationUrl":{"type":"string"}},"type":"object"},"Api.Core.Dto.Datapoints.Datapoint":{"properties":{"creationDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"encodeIp":{"type":"boolean"},"fifthConversionId":{"format":"int64","type":"integer"},"fifthConversionName":{"type":"string"},"firstConversionId":{"format":"int64","type":"integer"},"firstConversionName":{"type":"string"},"fourthConversionId":{"format":"int64","type":"integer"},"fourthConversionName":{"type":"string"},"groupId":{"format":"int64","type":"integer"},"groupName":{"type":"string"},"id":{"format":"int64","type":"integer"},"isPublic":{"type":"boolean"},"isSecured":{"type":"boolean"},"lightTracking":{"type":"boolean"},"name":{"type":"string"},"notes":{"type":"string"},"preferred":{"type":"boolean"},"redirectOnly":{"type":"boolean"},"secondConversionId":{"format":"int64","type":"integer"},"secondConversionName":{"type":"string"},"status":{"enum":["Active","Paused","Abuse","Deleted"],"type":"string"},"tags":{"items":{"$ref":"#/definitions/Api.Core.Dto.Tags.Tag"},"type":"array"},"thirdConversionId":{"format":"int64","type":"integer"},"thirdConversionName":{"type":"string"},"title":{"type":"string"},"trackingCode":{"type":"string"},"type":{"enum":["TrackingLink","TrackingPixel"],"type":"string"},"typeTL":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.TrackingLinkSpecifics"},"typeTP":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.TrackingPixelSpecifics"},"writePermited":{"type":"boolean"}},"type":"object"},"Api.Core.Dto.Datapoints.DatapointRetargetingInfo":{"properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"}},"type":"object"},"Api.Core.Dto.Datapoints.MultipleDestinationItem":{"properties":{"url":{"type":"string"}},"type":"object"},"Api.Core.Dto.Datapoints.TrackingLinkSpecifics":{"properties":{"appendQuery":{"type":"boolean"},"browserDestinationItem":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.BrowserBaseDestinationItem"},"destinationMode":{"enum":["Simple","RandomDestination","DestinationByLanguage","SpilloverDestination","DynamicUrl","BrowserDestination","DestinationByNation","UniqueDestination","SequentialDestination","WeightedDestination"],"type":"string"},"domainId":{"format":"int32","type":"integer"},"encodeUrl":{"type":"boolean"},"expirationClicks":{"format":"int64","type":"integer"},"expirationDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"firstUrl":{"type":"string"},"goDomainId":{"format":"int32","type":"integer"},"hideUrl":{"type":"boolean"},"hideUrlTitle":{"type":"string"},"isABTest":{"type":"boolean"},"password":{"type":"string"},"pauseAfterClicksExpiration":{"type":"boolean"},"pauseAfterDateExpiration":{"type":"boolean"},"randomDestinationItems":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.MultipleDestinationItem"},"type":"array"},"redirectType":{"enum":["PermanentRedirect","TemporaryRedirect"],"type":"string"},"referrerClean":{"enum":["None","Clean","Myself"],"type":"string"},"scripts":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.DatapointRetargetingInfo"},"type":"array"},"sequentialDestinationItems":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.MultipleDestinationItem"},"type":"array"},"spilloverDestinationItems":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.MultipleDestinationItem"},"type":"array"},"uniqueDestinationItem":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.UniqueDestinationItem"},"url":{"type":"string"},"urlAfterClicksExpiration":{"type":"string"},"urlAfterDateExpiration":{"type":"string"},"urlsByLanguage":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.UrlByLanguageItem"},"type":"array"},"urlsByNation":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.UrlByNationItem"},"type":"array"},"weightedDestinationItems":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.WeightedDestinationItem"},"type":"array"}},"type":"object"},"Api.Core.Dto.Datapoints.TrackingPixelSpecifics":{"properties":{"parameterNote":{"type":"string"}},"type":"object"},"Api.Core.Dto.Datapoints.UniqueDestinationItem":{"properties":{"firstDestinationUrl":{"type":"string"}},"type":"object"},"Api.Core.Dto.Datapoints.UrlByLanguageItem":{"properties":{"languageCode":{"type":"string"},"url":{"type":"string"}},"type":"object"},"Api.Core.Dto.Datapoints.UrlByNationItem":{"properties":{"nation":{"type":"string"},"url":{"type":"string"}},"type":"object"},"Api.Core.Dto.Datapoints.WeightedDestinationItem":{"properties":{"url":{"type":"string"},"weight":{"format":"int32","type":"integer"}},"type":"object"},"Api.Core.Dto.Domains.Domain":{"properties":{"custom404":{"type":"string"},"customHomepage":{"type":"string"},"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"type":{"enum":["System","Go","Dedicated","Personal"],"type":"string"}},"type":"object"},"Api.Core.Dto.EntityUriLong":{"properties":{"id":{"format":"int64","type":"integer"},"uri":{"type":"string"}},"type":"object"},"Api.Core.Dto.Grants.Grant":{"properties":{"DatapointType":{"type":"string"},"Entity":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"},"EntityName":{"type":"string"},"EntityType":{"type":"string"},"Type":{"type":"string"}},"type":"object"},"Api.Core.Dto.Groups.Group":{"properties":{"creationDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"deleted":{"type":"boolean"},"id":{"format":"int64","type":"integer"},"isPublic":{"type":"boolean"},"name":{"type":"string"},"notes":{"type":"string"},"preferred":{"type":"boolean"},"redirectOnly":{"type":"boolean"},"tags":{"items":{"$ref":"#/definitions/Api.Core.Dto.Tags.Tag"},"type":"array"},"writePermited":{"type":"boolean"}},"type":"object"},"Api.Core.Dto.Retargeting.RetargetingScript":{"properties":{"id":{"format":"int64","type":"integer"},"name":{"type":"string"},"script":{"type":"string"}},"type":"object"},"Api.Core.Dto.Tags.Tag":{"properties":{"datapoints":{"items":{"format":"int64","type":"integer"},"type":"array"},"groups":{"items":{"format":"int64","type":"integer"},"type":"array"},"id":{"format":"int64","type":"integer"},"name":{"type":"string"}},"type":"object"},"Api.Core.Dto.Tops.Top":{"properties":{"createdAt":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"data":{"items":{"$ref":"#/definitions/Api.Core.Dto.Tops.TopItem"},"type":"array"},"key":{"type":"string"}},"type":"object"},"Api.Core.Dto.Tops.TopItem":{"properties":{"entityData":{"$ref":"#/definitions/System.Object"},"id":{"type":"string"},"lastHitDate":{"description":" (A date in \"YmdHis\" format)","example":"20120203120530","type":"string"},"spiderClicks":{"format":"int64","type":"integer"},"spiderHits":{"format":"int64","type":"integer"},"spiderViews":{"format":"int64","type":"integer"},"totalClicks":{"format":"int64","type":"integer"},"totalCommissionsCost":{"format":"double","type":"number"},"totalConversions":{"format":"int64","type":"integer"},"totalConversionsCost":{"format":"double","type":"number"},"totalConversionsValue":{"format":"double","type":"number"},"totalHits":{"format":"int64","type":"integer"},"totalViews":{"format":"int64","type":"integer"},"uniqueClicks":{"format":"int64","type":"integer"},"uniqueHits":{"format":"int64","type":"integer"},"uniqueViews":{"format":"int64","type":"integer"}},"type":"object"},"Api.Core.Requests.ConversionPatchBody":{"properties":{"Action":{"type":"string"},"Id":{"format":"int64","type":"integer"},"ReplaceId":{"format":"int64","type":"integer"}},"type":"object"},"Api.Core.Requests.DatapointsBatch":{"properties":{"List":{"items":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.Datapoint"},"type":"array"}},"type":"object"},"Api.Core.Requests.DeleteBatch":{"properties":{"Entities":{"items":{"$ref":"#/definitions/Api.Core.Dto.EntityUriLong"},"type":"array"}},"type":"object"},"Api.Core.Requests.GenericTextPatch":{"properties":{"Text":{"type":"string"}},"type":"object"},"Api.Core.Requests.PatchBody":{"properties":{"Action":{"type":"string"},"Id":{"format":"int64","type":"integer"}},"type":"object"},"Api.Core.Requests.PatchBodyBatch":{"properties":{"PatchRequests":{"items":{"$ref":"#/definitions/Api.Core.Requests.PatchBody"},"type":"array"}},"type":"object"},"Api.Core.Requests.PermissionPatchRequest":{"properties":{"Action":{"type":"string"},"Id":{"format":"int64","type":"integer"},"Verb":{"type":"string"}},"type":"object"},"Api.Core.Responses.CountResponce":{"properties":{"count":{"format":"int64","type":"integer"}},"type":"object"},"Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.DomainWhitelistEntry]":{"properties":{"entities":{"items":{"$ref":"#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry"},"type":"array"}},"type":"object"},"Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.IpBlacklistEntry]":{"properties":{"entities":{"items":{"$ref":"#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry"},"type":"array"}},"type":"object"},"Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]":{"properties":{"entities":{"items":{"$ref":"#/definitions/Api.Core.Dto.Aggregated.AggregatedResult"},"type":"array"}},"type":"object"},"Api.Core.Responses.EntitiesResponse[Api.Core.Dto.ClickStream.Hit]":{"properties":{"entities":{"items":{"$ref":"#/definitions/Api.Core.Dto.ClickStream.Hit"},"type":"array"}},"type":"object"},"Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Grants.Grant]":{"properties":{"entities":{"items":{"$ref":"#/definitions/Api.Core.Dto.Grants.Grant"},"type":"array"}},"type":"object"},"Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]":{"properties":{"entities":{"items":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"},"type":"array"}},"type":"object"},"Api.Core.Responses.EntityUri[System.Int64]":{"properties":{"id":{"format":"int64","type":"integer"},"uri":{"type":"string"}},"type":"object"},"Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]":{"properties":{"entityData":{"$ref":"#/definitions/Api.Core.Dto.Datapoints.Datapoint"},"errors":{"items":{"$ref":"#/definitions/ClickMeter.Infrastructure.Validation.ValidationFailure"},"type":"array"},"result":{"$ref":"#/definitions/Api.Core.Responses.EntityUri[System.Int64]"},"status":{"type":"string"}},"type":"object"},"ClickMeter.Infrastructure.Validation.ValidationFailure":{"properties":{"code":{"$ref":"#/definitions/System.Object"},"errorMessage":{"type":"string"},"errorValue":{"$ref":"#/definitions/System.Object"},"property":{"type":"string"}},"type":"object"},"System.Object":{"properties":{},"type":"object"}}} diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/clickmeter.yaml b/vendor/github.com/go-openapi/spec/fixtures/expansion/clickmeter.yaml deleted file mode 100644 index 0ce32b1a9..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/expansion/clickmeter.yaml +++ /dev/null @@ -1,6461 +0,0 @@ -swagger: '2.0' -schemes: - - http - - https -host: 'apiv2.clickmeter.com:80' -info: - contact: - email: api@clickmeter.com - name: Api Support - url: 'http://www.clickmeter.com/api' - description: Api dashboard for ClickMeter API - title: ClickMeter - version: v2 - x-logo: - url: 'https://s3.amazonaws.com/clickmeter.com/Web/static/cmlogo.svg' - x-origin: - format: swagger - url: 'http://api.v2.clickmeter.com.s3.amazonaws.com/docs/api-docs-v2.json' - version: '2.0' - x-providerName: clickmeter.com -securityDefinitions: - api_key: - description: API Key Authentication - in: header - name: X-Clickmeter-AuthKey - type: apiKey -security: - - api_key: [] -paths: - /account: - get: - consumes: [] - deprecated: false - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.User' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve current account data - tags: - - Account - post: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.User' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.User' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Update current account data - tags: - - Account - /account/domainwhitelist: - get: - consumes: [] - deprecated: false - parameters: - - description: Offset where to start from - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - description: Limit results to this number - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.DomainWhitelistEntry]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve list of a domains allowed to redirect in DDU mode - tags: - - Account - post: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: The entry to add - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Create an domain entry - tags: - - Account - '/account/domainwhitelist/{whitelistId}': - delete: - consumes: [] - deprecated: false - parameters: - - description: The id of the domain to delete - in: path - name: whitelistId - required: true - type: string - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Delete an domain entry - tags: - - Account - /account/guests: - get: - consumes: [] - deprecated: false - parameters: - - description: Offset where to start from - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - description: Limit results to this number - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: Field to sort by - in: query - name: sortBy - required: false - type: string - - description: 'Direction of sort "asc" or "desc"' - enum: - - asc - - desc - in: query - name: sortDirection - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve list of a guest - tags: - - Account - post: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: Guest object to create - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.Guest' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.Guest' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Create a guest - tags: - - Account - /account/guests/count: - get: - consumes: [] - deprecated: false - parameters: - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.CountResponce' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve count of guests - tags: - - Account - '/account/guests/{guestId}': - delete: - consumes: [] - deprecated: false - parameters: - - description: Id of the guest - format: int64 - in: path - name: guestId - required: true - type: integer - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Delete a guest - tags: - - Account - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the guest - format: int64 - in: path - name: guestId - required: true - type: integer - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.Guest' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve a guest - tags: - - Account - post: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: Id of the guest - format: int64 - in: path - name: guestId - required: true - type: integer - - description: Guest object with field updated - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.Guest' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.Guest' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Update a guest - tags: - - Account - '/account/guests/{guestId}/permissions': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the guest - format: int64 - in: path - name: guestId - required: true - type: integer - - description: 'Can be "datapoint" or "group"' - enum: - - datapoint - - group - in: query - name: entityType - required: false - type: string - - description: Offset where to start from - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - description: Limit results to this number - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: 'Can be "w" or "r"' - enum: - - r - - w - in: query - name: type - required: false - type: string - - description: Optional id of the datapoint/group entity to filter by - format: int64 - in: query - name: entityId - required: false - type: integer - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Grants.Grant]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve permissions for a guest - tags: - - Account - '/account/guests/{guestId}/permissions/count': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the guest - format: int64 - in: path - name: guestId - required: true - type: integer - - description: 'Can be "datapoint" or "group"' - enum: - - datapoint - - group - in: query - name: entityType - required: false - type: string - - description: 'Can be "w" or "r"' - enum: - - r - - w - in: query - name: type - required: false - type: string - - description: Optional id of the datapoint/group entity to filter by - format: int64 - in: query - name: entityId - required: false - type: integer - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.CountResponce' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve count of the permissions for a guest - tags: - - Account - '/account/guests/{guestId}/{type}/permissions/patch': - post: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: Id of the guest - format: int64 - in: path - name: guestId - required: true - type: integer - - description: 'Can be "datapoint" or "group"' - enum: - - datapoint - - group - in: path - name: type - required: true - type: string - - description: The patch permission request - in: body - name: body - required: true - schema: - $ref: '#/definitions/Api.Core.Requests.PermissionPatchRequest' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Change the permission on a shared object - tags: - - Account - put: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: Id of the guest - format: int64 - in: path - name: guestId - required: true - type: integer - - description: 'Can be "datapoint" or "group"' - enum: - - datapoint - - group - in: path - name: type - required: true - type: string - - description: The patch permission request - in: body - name: body - required: true - schema: - $ref: '#/definitions/Api.Core.Requests.PermissionPatchRequest' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Change the permission on a shared object - tags: - - Account - /account/ipblacklist: - get: - consumes: [] - deprecated: false - parameters: - - description: Offset where to start from - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - description: Limit results to this number - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.IpBlacklistEntry]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve list of a ip to exclude from event tracking - tags: - - Account - post: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: The entry to add - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Create an ip blacklist entry - tags: - - Account - '/account/ipblacklist/{blacklistId}': - delete: - consumes: [] - deprecated: false - parameters: - - description: The id of the ip to delete - in: path - name: blacklistId - required: true - type: string - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Delete an ip blacklist entry - tags: - - Account - /account/plan: - get: - consumes: [] - deprecated: false - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.Plan' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve current account plan - tags: - - Account - /aggregated: - get: - consumes: [] - deprecated: false - parameters: - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'If using "yesterday" or "today" timeframe you can ask for the hourly detail' - in: query - name: hourly - required: false - type: boolean - - description: '' - in: query - name: onlyFavorites - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about this customer for a timeframe - tags: - - Aggregated - /aggregated/list: - get: - consumes: [] - deprecated: false - parameters: - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'The temporal entity you want to group by ("week"/"month"). If unspecified is "day".' - enum: - - week - - month - in: query - name: groupBy - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about this customer for a timeframe grouped by some temporal entity (day/week/month) - tags: - - Aggregated - /aggregated/summary/conversions: - get: - consumes: [] - deprecated: false - parameters: - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'Status of conversion ("deleted"/"active")' - enum: - - deleted - - active - in: query - name: status - required: false - type: string - - description: Field to sort by - in: query - name: sortBy - required: false - type: string - - description: 'Direction of sort "asc" or "desc"' - enum: - - asc - - desc - in: query - name: sortDirection - required: false - type: string - - description: Offset where to start from - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - description: Limit results to this number - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about a subset of conversions for a timeframe with conversions data - tags: - - Aggregated - /aggregated/summary/datapoints: - get: - consumes: [] - deprecated: false - parameters: - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'Type of datapoint ("tl"/"tp")' - enum: - - tp - - tl - in: query - name: type - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'Status of datapoint ("deleted"/"active"/"paused"/"spam")' - enum: - - deleted - - active - - paused - - spam - in: query - name: status - required: false - type: string - - description: A comma separated list of tags you want to filter with. - in: query - name: tag - required: false - type: string - - description: Is the datapoint marked as favourite - in: query - name: favourite - required: false - type: boolean - - description: Field to sort by - in: query - name: sortBy - required: false - type: string - - description: 'Direction of sort "asc" or "desc"' - enum: - - asc - - desc - in: query - name: sortDirection - required: false - type: string - - description: Offset where to start from - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - description: Limit results to this number - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: Filter by this group id - format: int64 - in: query - name: groupId - required: false - type: integer - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about a subset of datapoints for a timeframe with datapoints data - tags: - - Aggregated - /aggregated/summary/groups: - get: - consumes: [] - deprecated: false - parameters: - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'Status of group ("deleted"/"active")' - enum: - - deleted - - active - in: query - name: status - required: false - type: string - - description: A comma separated list of tags you want to filter with. - in: query - name: tag - required: false - type: string - - description: Is the group marked as favourite - in: query - name: favourite - required: false - type: boolean - - description: Field to sort by - in: query - name: sortBy - required: false - type: string - - description: 'Direction of sort "asc" or "desc"' - enum: - - asc - - desc - in: query - name: sortDirection - required: false - type: string - - description: Offset where to start from - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - description: Limit results to this number - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about a subset of groups for a timeframe with groups data - tags: - - Aggregated - /clickstream: - get: - consumes: [] - deprecated: false - parameters: - - description: 'Filter by this group id (mutually exclusive with "datapoint" and "conversion")' - format: int64 - in: query - name: group - required: false - type: integer - - description: 'Filter by this datapoint id (mutually exclusive with "group" and "conversion")' - format: int64 - in: query - name: datapoint - required: false - type: integer - - description: 'Filter by this conversion id (mutually exclusive with "datapoint" and "group")' - format: int64 - in: query - name: conversion - required: false - type: integer - - default: 50 - description: Limit results to this number - format: int32 - in: query - name: pageSize - required: false - type: integer - - description: 'Filter event type ("spiders"/"uniques"/"nonuniques"/"conversions")' - enum: - - '' - - spiders - - uniques - - nonuniques - - conversions - in: query - name: filter - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.ClickStream.Hit]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve the latest list of events of this account. Limited to last 100. - tags: - - ClickStream - /conversions: - get: - consumes: [] - deprecated: false - parameters: - - description: Offset where to start from - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - description: Limit results to this number - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: 'Status of conversion ("deleted"/"active")' - enum: - - deleted - - active - in: query - name: status - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Exclude conversions created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude conversions created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve a list of conversions - tags: - - Conversions - post: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: The body of the conversion - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Conversions.Conversion' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Create a conversion - tags: - - Conversions - /conversions/aggregated/list: - get: - consumes: [] - deprecated: false - parameters: - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'Status of conversion ("deleted"/"active")' - enum: - - deleted - - active - in: query - name: status - required: false - type: string - - description: 'The temporal entity you want to group by ("week"/"month"). If unspecified is "day".' - enum: - - week - - month - in: query - name: groupBy - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about this customer for a timeframe related to a subset of conversions grouped by some temporal entity (day/week/month) - tags: - - Conversions - /conversions/count: - get: - consumes: [] - deprecated: false - parameters: - - description: 'Status of conversion ("deleted"/"active")' - enum: - - deleted - - active - in: query - name: status - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Exclude conversions created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude conversions created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.CountResponce' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve a count of conversions - tags: - - Conversions - '/conversions/{conversionId}': - delete: - consumes: [] - deprecated: false - parameters: - - description: Id of the conversion - format: int64 - in: path - name: conversionId - required: true - type: integer - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Delete conversion specified by id - tags: - - Conversions - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the conversion - format: int64 - in: path - name: conversionId - required: true - type: integer - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Conversions.Conversion' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Retrieve conversion specified by id - tags: - - Conversions - post: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: Id of the conversion - format: int64 - in: path - name: conversionId - required: true - type: integer - - description: Updated body of the conversion - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Conversions.Conversion' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Update conversion specified by id - tags: - - Conversions - '/conversions/{conversionId}/aggregated': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the conversion - format: int64 - in: path - name: conversionId - required: true - type: integer - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: Filter by this tag name - in: query - name: tag - required: false - type: string - - description: Is the datapoint marked as favourite - in: query - name: favourite - required: false - type: boolean - - description: 'If using "yesterday" or "today" timeframe you can ask for the hourly detail' - in: query - name: hourly - required: false - type: boolean - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about this conversion for a timeframe - tags: - - Conversions - '/conversions/{conversionId}/aggregated/list': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the conversion - format: int64 - in: path - name: conversionId - required: true - type: integer - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'The temporal entity you want to group by ("week"/"month"). If unspecified is "day".' - enum: - - week - - month - in: query - name: groupBy - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about this conversion for a timeframe grouped by some temporal entity (day/week/month) - tags: - - Conversions - '/conversions/{conversionId}/datapoints': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the conversion - format: int64 - in: path - name: conversionId - required: true - type: integer - - description: Offset where to start from - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - description: Limit results to this number - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: 'Type of datapoint ("tl"/"tp")' - enum: - - tp - - tl - in: query - name: type - required: false - type: string - - description: 'Status of datapoint ("deleted"/"active"/"paused"/"spam")' - enum: - - deleted - - active - - paused - - spam - in: query - name: status - required: false - type: string - - description: Filter by this tag name - in: query - name: tags - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Exclude datapoints created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude datapoints created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve a list of datapoints connected to this conversion - tags: - - Conversions - '/conversions/{conversionId}/datapoints/batch/patch': - put: - consumes: - - application/json - - text/json - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: Id of the conversion - format: int64 - in: path - name: conversionId - required: true - type: integer - - description: Patch requests - in: body - name: data - required: true - schema: - $ref: '#/definitions/Api.Core.Requests.PatchBodyBatch' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Modify the association between a conversion and multiple datapoints - tags: - - Conversions - '/conversions/{conversionId}/datapoints/count': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the conversion - format: int64 - in: path - name: conversionId - required: true - type: integer - - description: 'Type of datapoint ("tl"/"tp")' - in: query - name: type - required: false - type: string - - description: 'Status of datapoint ("deleted"/"active"/"paused"/"spam")' - in: query - name: status - required: false - type: string - - description: Filter by this tag name - in: query - name: tags - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Exclude datapoints created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude datapoints created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.CountResponce' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve a count of datapoints connected to this conversion - tags: - - Conversions - '/conversions/{conversionId}/datapoints/patch': - put: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: Id of the conversion - format: int64 - in: path - name: conversionId - required: true - type: integer - - description: Patch request - in: body - name: data - required: true - schema: - $ref: '#/definitions/Api.Core.Requests.ConversionPatchBody' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Modify the association between a conversion and a datapoint - tags: - - Conversions - '/conversions/{conversionId}/hits': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the conversion - format: int64 - in: path - name: conversionId - required: true - type: integer - - description: Timeframe of the request. See list at $timeframeList - enum: - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - custom - in: query - name: timeframe - required: true - type: string - - description: Limit results to this number - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: "Offset where to start from (it's the lastKey field in the response object)" - in: query - name: offset - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'Filter event type ("spiders"/"uniques"/"nonuniques"/"conversions")' - enum: - - spiders - - uniques - - nonuniques - - conversions - in: query - name: filter - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.ClickStream.HitListPage' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve the list of events related to this conversion. - tags: - - Conversions - '/conversions/{conversionId}/notes': - put: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: Id of the conversion - format: int64 - in: path - name: conversionId - required: true - type: integer - - description: Patch requests - in: body - name: note - required: true - schema: - $ref: '#/definitions/Api.Core.Requests.GenericTextPatch' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '403': - description: Forbidden - '404': - description: Not found - '500': - description: Internal Server Error - summary: 'Fast patch the "notes" field of a conversion' - tags: - - Conversions - '/conversions/{conversionId}/reports': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the conversion - format: int64 - in: path - name: conversionId - required: true - type: integer - - description: Type of the report. - enum: - - datapoints - - groups - - browsers - - browsersfamilies - - platforms - - cities - - countries - - keywords - - referrers - - convparameters - - destinations - - languages - - params - in: query - name: type - required: true - type: string - - description: Timeframe of the request. See list at $timeframeList - enum: - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - beginning - - custom - in: query - name: timeframe - required: true - type: string - - description: Type of the event you want to filter this report with. By default no filter is applied. - enum: - - clicks - - views - in: query - name: hittype - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Tops.Top' - '401': - description: Forbidden - '404': - description: Not found - '500': - description: Internal Server Error - summary: Retrieve a top report connected to this conversion - tags: - - Conversions - /datapoints: - get: - consumes: [] - deprecated: false - parameters: - - default: 0 - description: Where to start when retrieving elements. Default is 0 if not specified. - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - default: 20 - description: Maximum elements to retrieve. Default to 20 if not specified. - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: 'Type of the datapoint ("tp"/"tl")' - enum: - - tp - - tl - in: query - name: type - required: false - type: string - - description: Status of the datapoint - enum: - - deleted - - active - - paused - - spam - in: query - name: status - required: false - type: string - - description: A comma separated list of tags you want to filter with. - in: query - name: tags - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Filter fields by favourite status - in: query - name: onlyFavorites - required: false - type: boolean - - description: Field to sort by - in: query - name: sortBy - required: false - type: string - - description: 'Direction of sort "asc" or "desc"' - enum: - - asc - - desc - in: query - name: sortDirection - required: false - type: string - - description: Exclude datapoints created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude datapoints created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: List of all the datapoints associated to the user - tags: - - DataPoints - post: - consumes: - - application/json - - text/json - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: The body of the datapoint - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Datapoints.Datapoint' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Create a datapoint - tags: - - DataPoints - /datapoints/aggregated: - get: - consumes: [] - deprecated: false - parameters: - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'Type of datapoint ("tl"/"tp")' - enum: - - tp - - tl - in: query - name: type - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'If using "yesterday" or "today" timeframe you can ask for the hourly detail' - in: query - name: hourly - required: false - type: boolean - - description: 'Status of datapoint ("deleted"/"active"/"paused"/"spam")' - enum: - - deleted - - active - - paused - - spam - in: query - name: status - required: false - type: string - - description: A comma separated list of tags you want to filter with. - in: query - name: tag - required: false - type: string - - description: Is the datapoint is marked as favourite - in: query - name: favourite - required: false - type: boolean - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about this customer for a timeframe by groups - tags: - - DataPoints - /datapoints/aggregated/list: - get: - consumes: [] - deprecated: false - parameters: - - description: 'Type of datapoint ("tl"/"tp")' - enum: - - tp - - tl - in: query - name: type - required: true - type: string - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'Status of datapoint ("deleted"/"active"/"paused"/"spam")' - enum: - - deleted - - active - - paused - - spam - in: query - name: status - required: false - type: string - - description: A comma separated list of tags you want to filter with. - in: query - name: tag - required: false - type: string - - description: Is the datapoint is marked as favourite - in: query - name: favourite - required: false - type: boolean - - description: 'The temporal entity you want to group by ("week"/"month"). If unspecified is "day".' - enum: - - week - - month - in: query - name: groupBy - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about all datapoints of this customer for a timeframe grouped by some temporal entity (day/week/month) - tags: - - DataPoints - /datapoints/batch: - delete: - consumes: - - application/json - - text/json - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: A json containing the datapoints to delete. - in: body - name: batch - required: true - schema: - $ref: '#/definitions/Api.Core.Requests.DeleteBatch' - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Delete multiple datapoints - tags: - - DataPoints - post: - consumes: - - application/json - - text/json - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: A json containing the datapoints to update. - in: body - name: batch - required: true - schema: - $ref: '#/definitions/Api.Core.Requests.DatapointsBatch' - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Update multiple datapoints - tags: - - DataPoints - put: - consumes: - - application/json - - text/json - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: A json containing the datapoints to create. - in: body - name: batch - required: true - schema: - $ref: '#/definitions/Api.Core.Requests.DatapointsBatch' - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Create multiple datapoints - tags: - - DataPoints - /datapoints/count: - get: - consumes: [] - deprecated: false - parameters: - - description: 'Type of the datapoint ("tp"/"tl")' - enum: - - tp - - tl - in: query - name: type - required: false - type: string - - description: Status of the datapoint - enum: - - deleted - - active - - paused - - spam - in: query - name: status - required: false - type: string - - description: A comma separated list of tags you want to filter with. - in: query - name: tags - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Filter fields by favourite status - in: query - name: onlyFavorites - required: false - type: boolean - - description: Exclude datapoints created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude datapoints created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.CountResponce' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Count the datapoints associated to the user - tags: - - DataPoints - '/datapoints/{id}': - delete: - consumes: [] - deprecated: false - parameters: - - description: The id of the datapoint - format: int64 - in: path - name: id - required: true - type: integer - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Delete a datapoint - tags: - - DataPoints - get: - consumes: [] - deprecated: false - parameters: - - description: The id of the datapoint - format: int64 - in: path - name: id - required: true - type: integer - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Datapoints.Datapoint' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Get a datapoint - tags: - - DataPoints - post: - consumes: - - application/json - - text/json - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: The id of the datapoint - format: int64 - in: path - name: id - required: true - type: integer - - description: The body of the datapoint - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Datapoints.Datapoint' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Update a datapoint - tags: - - DataPoints - '/datapoints/{id}/aggregated': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the datapoint - format: int64 - in: path - name: id - required: true - type: integer - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'If using "yesterday" or "today" timeframe you can ask for the hourly detail' - in: query - name: hourly - required: false - type: boolean - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about this datapoint for a timeframe - tags: - - DataPoints - '/datapoints/{id}/aggregated/list': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the datapoint - format: int64 - in: path - name: id - required: true - type: integer - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'The temporal entity you want to group by ("week"/"month"). If unspecified is "day".' - enum: - - week - - month - in: query - name: groupBy - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about this datapoint for a timeframe grouped by some temporal entity (day/week/month) - tags: - - DataPoints - '/datapoints/{id}/favourite': - put: - consumes: [] - deprecated: false - parameters: - - description: Id of the datapoint - format: int64 - in: path - name: id - required: true - type: integer - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '403': - description: Forbidden - '404': - description: Not found - '500': - description: Internal Server Error - summary: 'Fast switch the "favourite" field of a datapoint' - tags: - - DataPoints - '/datapoints/{id}/hits': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the datapoint - format: int64 - in: path - name: id - required: true - type: integer - - description: Timeframe of the request. See list at $timeframeList - enum: - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - custom - in: query - name: timeframe - required: true - type: string - - description: Limit results to this number - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: "Offset where to start from (it's the lastKey field in the response object)" - in: query - name: offset - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'Filter event type ("spiders"/"uniques"/"nonuniques"/"conversions")' - enum: - - spiders - - uniques - - nonuniques - - conversions - in: query - name: filter - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.ClickStream.HitListPage' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve the list of events related to this datapoint. - tags: - - DataPoints - '/datapoints/{id}/notes': - put: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: Id of the datapoint - format: int64 - in: path - name: id - required: true - type: integer - - description: Patch requests - in: body - name: note - required: true - schema: - $ref: '#/definitions/Api.Core.Requests.GenericTextPatch' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '403': - description: Forbidden - '404': - description: Not found - '500': - description: Internal Server Error - summary: 'Fast patch the "notes" field of a datapoint' - tags: - - DataPoints - '/datapoints/{id}/reports': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the datapoint - format: int64 - in: path - name: id - required: true - type: integer - - description: Type of the report. - enum: - - browsers - - browsersfamilies - - platforms - - cities - - countries - - isps - - ips - - oss - - ossfamilies - - keywords - - referrers - - destinations - - languages - - params - in: query - name: type - required: true - type: string - - description: Timeframe of the request. See list at $timeframeList - enum: - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - beginning - - custom - in: query - name: timeframe - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Tops.Top' - '401': - description: Forbidden - '404': - description: Not found - '500': - description: Internal Server Error - summary: Retrieve a top report connected to this datapoint - tags: - - DataPoints - /domains: - get: - consumes: [] - deprecated: false - parameters: - - description: Offset where to start from - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - description: Limit results to this number - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - default: system - description: 'Type of domain ("system"/"go"/"personal"/"dedicated"). If not specified default is "system"' - enum: - - system - - go - - personal - - dedicated - in: query - name: type - required: false - type: string - - description: Filter domains with this anmen - in: query - name: name - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve a list of domains - tags: - - Domains - post: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: The domain to create - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Domains.Domain' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Create a domain - tags: - - Domains - /domains/count: - get: - consumes: [] - deprecated: false - parameters: - - default: system - description: 'Type of domain ("system"/"go"/"personal"/"dedicated"). If not specified default is "system"' - enum: - - system - - go - - personal - - dedicated - in: query - name: type - required: false - type: string - - description: Filter domains with this anmen - in: query - name: name - required: false - type: string - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.CountResponce' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve count of domains - tags: - - Domains - '/domains/{id}': - delete: - consumes: [] - deprecated: false - parameters: - - description: Id of domain - format: int64 - in: path - name: id - required: true - type: integer - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Delete a domain - tags: - - Domains - get: - consumes: [] - deprecated: false - parameters: - - description: Id of domain - format: int64 - in: path - name: id - required: true - type: integer - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Domains.Domain' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Get a domain - tags: - - Domains - post: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: Id of domain - format: int64 - in: path - name: id - required: true - type: integer - - description: The domain to update - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Domains.Domain' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Update a domain - tags: - - Domains - /groups: - get: - consumes: [] - deprecated: false - parameters: - - default: 0 - description: Where to start when retrieving elements. Default is 0 if not specified. - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - default: 20 - description: Maximum elements to retrieve. Default to 20 if not specified. - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: Status of the group - enum: - - deleted - - active - in: query - name: status - required: false - type: string - - description: A comma separated list of tags you want to filter with. - in: query - name: tags - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Exclude groups created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude groups created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - - description: Write permission - in: query - name: write - required: false - type: boolean - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: List of all the groups associated to the user. - tags: - - Groups - post: - consumes: - - application/json - - text/json - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: The body of the group - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Groups.Group' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Create a group - tags: - - Groups - /groups/aggregated: - get: - consumes: [] - deprecated: false - parameters: - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'If using "yesterday" or "today" timeframe you can ask for the hourly detail' - in: query - name: hourly - required: false - type: boolean - - description: 'Status of group ("deleted"/"active")' - enum: - - deleted - - active - in: query - name: status - required: false - type: string - - description: A comma separated list of tags you want to filter with. - in: query - name: tag - required: false - type: string - - description: Is the group is marked as favourite - in: query - name: favourite - required: false - type: boolean - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about this customer for a timeframe by groups - tags: - - Groups - /groups/aggregated/list: - get: - consumes: [] - deprecated: false - parameters: - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'Status of group ("deleted"/"active")' - in: query - name: status - required: false - type: string - - description: A comma separated list of tags you want to filter with. - in: query - name: tag - required: false - type: string - - description: Is the group is marked as favourite - in: query - name: favourite - required: false - type: boolean - - description: 'The temporal entity you want to group by ("week"/"month"). If unspecified is "day".' - enum: - - deleted - - active - in: query - name: groupBy - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about all groups of this customer for a timeframe grouped by some temporal entity (day/week/month) - tags: - - Groups - /groups/count: - get: - consumes: [] - deprecated: false - parameters: - - description: Status of the datapoint - enum: - - deleted - - active - in: query - name: status - required: false - type: string - - description: A comma separated list of tags you want to filter with. - in: query - name: tags - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Exclude groups created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude groups created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - - description: Write permission - in: query - name: write - required: false - type: boolean - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.CountResponce' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Count the groups associated to the user. - tags: - - Groups - '/groups/{id}': - delete: - consumes: [] - deprecated: false - parameters: - - description: Id of the group - format: int64 - in: path - name: id - required: true - type: integer - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Delete group specified by id - tags: - - Groups - get: - consumes: [] - deprecated: false - parameters: - - description: The id of the group - format: int64 - in: path - name: id - required: true - type: integer - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Groups.Group' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Get a group - tags: - - Groups - post: - consumes: - - application/json - - text/json - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: The id of the group - format: int64 - in: path - name: id - required: true - type: integer - - description: The body of the group - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Groups.Group' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Update a group - tags: - - Groups - '/groups/{id}/aggregated': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the group - format: int64 - in: path - name: id - required: true - type: integer - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'If using "yesterday" or "today" timeframe you can ask for the hourly detail' - in: query - name: hourly - required: false - type: boolean - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about this group for a timeframe - tags: - - Groups - '/groups/{id}/aggregated/list': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the group - format: int64 - in: path - name: id - required: true - type: integer - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'The temporal entity you want to group by ("week"/"month"). If unspecified is "day".' - enum: - - week - - month - in: query - name: groupBy - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about this group for a timeframe grouped by some temporal entity (day/week/month) - tags: - - Groups - '/groups/{id}/aggregated/summary': - get: - consumes: [] - deprecated: false - parameters: - - description: Filter by this group id - format: int64 - in: path - name: id - required: true - type: integer - - description: Timeframe of the request. See list at $timeframeList - enum: - - today - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - last12months - - lastyear - - currentyear - - beginning - - custom - in: query - name: timeFrame - required: true - type: string - - description: 'Type of datapoint ("tl"/"tp")' - enum: - - tp - - tl - in: query - name: type - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'Status of datapoint ("deleted"/"active"/"paused"/"spam")' - enum: - - deleted - - active - in: query - name: status - required: false - type: string - - description: A comma separated list of tags you want to filter with. - in: query - name: tag - required: false - type: string - - description: Is the datapoint marked as favourite - in: query - name: favourite - required: false - type: boolean - - description: Field to sort by - in: query - name: sortBy - required: false - type: string - - description: 'Direction of sort "asc" or "desc"' - enum: - - asc - - desc - in: query - name: sortDirection - required: false - type: string - - default: 0 - description: Offset where to start from - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - default: 20 - description: Limit results to this number - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedSummaryResult' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve statistics about a subset of datapoints for a timeframe with datapoints data - tags: - - Groups - '/groups/{id}/datapoints': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the group - format: int64 - in: path - name: id - required: true - type: integer - - default: 0 - description: Where to start when retrieving elements. Default is 0 if not specified. - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - default: 20 - description: Maximum elements to retrieve. Default to 20 if not specified. - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: 'Type of the datapoint ("tp"/"tl")' - enum: - - tp - - tl - in: query - name: type - required: false - type: string - - description: Status of the datapoint - enum: - - deleted - - active - - paused - - spam - in: query - name: status - required: false - type: string - - description: A comma separated list of tags you want to filter with. - in: query - name: tags - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Filter fields by favourite status - in: query - name: onlyFavorites - required: false - type: boolean - - description: Field to sort by - in: query - name: sortBy - required: false - type: string - - description: 'Direction of sort "asc" or "desc"' - enum: - - asc - - desc - in: query - name: sortDirection - required: false - type: string - - description: Exclude datapoints created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude datapoints created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: List of all the datapoints associated to the user in this group. - tags: - - Groups - post: - consumes: - - application/json - - text/json - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: The id of the group - format: int64 - in: path - name: id - required: true - type: integer - - description: The body of the datapoint - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Datapoints.Datapoint' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Create a datapoint in this group - tags: - - Groups - '/groups/{id}/datapoints/count': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the group - format: int64 - in: path - name: id - required: true - type: integer - - description: 'Type of the datapoint ("tp"/"tl")' - enum: - - tp - - tl - in: query - name: type - required: false - type: string - - description: Status of the datapoint - enum: - - deleted - - active - - paused - - spam - in: query - name: status - required: false - type: string - - description: A comma separated list of tags you want to filter with. - in: query - name: tags - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Filter fields by favourite status - in: query - name: onlyFavorites - required: false - type: boolean - - description: Exclude datapoints created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude datapoints created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.CountResponce' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Count the datapoints associated to the user in this group. - tags: - - Groups - '/groups/{id}/favourite': - put: - consumes: [] - deprecated: false - parameters: - - description: Id of the group - format: int64 - in: path - name: id - required: true - type: integer - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '403': - description: Forbidden - '404': - description: Not found - '500': - description: Internal Server Error - summary: 'Fast switch the "favourite" field of a group' - tags: - - Groups - '/groups/{id}/hits': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the group - format: int64 - in: path - name: id - required: true - type: integer - - description: Timeframe of the request. See list at $timeframeList - enum: - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - custom - in: query - name: timeframe - required: true - type: string - - description: Limit results to this number - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: "Offset where to start from (it's the lastKey field in the response object)" - in: query - name: offset - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'Filter event type ("spiders"/"uniques"/"nonuniques"/"conversions")' - enum: - - spiders - - uniques - - nonuniques - - conversions - in: query - name: filter - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.ClickStream.HitListPage' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve the list of events related to this group. - tags: - - Groups - '/groups/{id}/notes': - put: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: Id of the group - format: int64 - in: path - name: id - required: true - type: integer - - description: Patch requests - in: body - name: note - required: true - schema: - $ref: '#/definitions/Api.Core.Requests.GenericTextPatch' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '403': - description: Forbidden - '404': - description: Not found - '500': - description: Internal Server Error - summary: 'Fast patch the "notes" field of a group' - tags: - - Groups - '/groups/{id}/reports': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the group - format: int64 - in: path - name: id - required: true - type: integer - - description: Type of the report. - enum: - - browsers - - browsersfamilies - - platforms - - cities - - countries - - isps - - ips - - oss - - ossfamilies - - keywords - - referrers - - destinations - - languages - - params - in: query - name: type - required: true - type: string - - description: Timeframe of the request. See list at $timeframeList - enum: - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - beginning - - custom - in: query - name: timeframe - required: true - type: string - - description: Type of the event you want to filter this report with. By default no filter is applied. - enum: - - clicks - - views - in: query - name: hittype - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Tops.Top' - '401': - description: Forbidden - '404': - description: Not found - '500': - description: Internal Server Error - summary: Retrieve a top report connected to this group - tags: - - Groups - /hits: - get: - consumes: [] - deprecated: false - parameters: - - description: Timeframe of the request. See list at $timeframeList - enum: - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - custom - in: query - name: timeframe - required: true - type: string - - description: Limit results to this number - format: int32 - in: query - name: limit - required: false - type: integer - - description: "Offset where to start from (it's the lastKey field in the response object)" - in: query - name: offset - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - - description: 'Filter event type ("spiders"/"uniques"/"nonuniques"/"conversions")' - enum: - - spiders - - uniques - - nonuniques - - conversions - in: query - name: filter - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.ClickStream.HitListPage' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve the list of events related to this account. - tags: - - Hits - /me: - get: - consumes: [] - deprecated: false - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.User' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve current account data - tags: - - Me - /me/plan: - get: - consumes: [] - deprecated: false - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Accounting.Plan' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve current account plan - tags: - - Me - /reports: - get: - consumes: [] - deprecated: false - parameters: - - description: Type of the report. - enum: - - browsers - - browsersfamilies - - platforms - - cities - - countries - - isps - - ips - - oss - - ossfamilies - - keywords - - referrers - - destinations - - languages - - params - in: query - name: type - required: true - type: string - - description: Timeframe of the request. See list at $timeframeList - enum: - - yesterday - - last7 - - last30 - - lastmonth - - currentmonth - - previousmonth - - last90 - - last120 - - last180 - - beginning - - custom - in: query - name: timeframe - required: true - type: string - - description: Type of the event you want to filter this report with. By default no filter is applied. - in: query - name: hittype - required: false - type: string - - description: 'Filter by this group id (mutually exclusive with "datapoint" and "conversion")' - format: int64 - in: query - name: group - required: false - type: integer - - description: 'Filter by this datapoint id (mutually exclusive with "group" and "conversion")' - format: int64 - in: query - name: datapoint - required: false - type: integer - - description: 'Filter by this conversion id (mutually exclusive with "datapoint" and "group")' - format: int64 - in: query - name: conversion - required: false - type: integer - - description: 'If using a "custom" timeFrame you can specify the starting day (YYYYMMDD)' - in: query - name: fromDay - required: false - type: string - - description: 'If using a "custom" timeFrame you can specify the ending day (YYYYMMDD)' - in: query - name: toDay - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Tops.Top' - '401': - description: Forbidden - '404': - description: Not found - '500': - description: Internal Server Error - summary: Retrieve a top report - tags: - - Reports - /retargeting: - get: - consumes: [] - deprecated: false - parameters: - - default: 0 - description: Where to start when retrieving elements. Default is 0 if not specified. - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - default: 20 - description: Maximum elements to retrieve. Default to 20 if not specified. - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: List of all the retargeting scripts associated to the user - tags: - - Retargeting - post: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: The body of the retargeting script - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Retargeting.RetargetingScript' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Creates a retargeting script - tags: - - Retargeting - /retargeting/count: - get: - consumes: [] - deprecated: false - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.CountResponce' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve count of retargeting scripts - tags: - - Retargeting - '/retargeting/{id}': - delete: - consumes: [] - deprecated: false - parameters: - - description: The id of the retargeting script - format: int64 - in: path - name: id - required: true - type: integer - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Deletes a retargeting script (and remove associations) - tags: - - Retargeting - get: - consumes: [] - deprecated: false - parameters: - - description: The id of the retargeting script - format: int64 - in: path - name: id - required: true - type: integer - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Retargeting.RetargetingScript' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Get a retargeting script object - tags: - - Retargeting - post: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: The id of the retargeting script - format: int64 - in: path - name: id - required: true - type: integer - - description: The body of the retargeting script - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Retargeting.RetargetingScript' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Updates a retargeting script - tags: - - Retargeting - '/retargeting/{id}/datapoints': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the retargeting script - format: int64 - in: path - name: id - required: true - type: integer - - default: 0 - description: Where to start when retrieving elements. Default is 0 if not specified. - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - default: 20 - description: Maximum elements to retrieve. Default to 20 if not specified. - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: Status of the datapoint - enum: - - deleted - - active - - paused - - spam - in: query - name: status - required: false - type: string - - description: A comma separated list of tags you want to filter with. - in: query - name: tags - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Filter fields by favourite status - in: query - name: onlyFavorites - required: false - type: boolean - - description: Field to sort by - in: query - name: sortBy - required: false - type: string - - description: 'Direction of sort "asc" or "desc"' - enum: - - asc - - desc - in: query - name: sortDirection - required: false - type: string - - description: Exclude datapoints created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude datapoints created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: List of all the datapoints associated to the retargeting script. - tags: - - Retargeting - '/retargeting/{id}/datapoints/count': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the group - format: int64 - in: path - name: id - required: true - type: integer - - description: Status of the datapoint - enum: - - deleted - - active - - paused - - spam - in: query - name: status - required: false - type: string - - description: A comma separated list of tags you want to filter with. - in: query - name: tags - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Filter fields by favourite status - in: query - name: onlyFavorites - required: false - type: boolean - - description: Exclude datapoints created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude datapoints created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.CountResponce' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Count the datapoints associated to the retargeting script. - tags: - - Retargeting - /tags: - get: - consumes: [] - deprecated: false - parameters: - - default: 0 - description: Where to start when retrieving elements. Default is 0 if not specified. - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - default: 20 - description: Maximum elements to retrieve. Default to 20 if not specified. - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: Name of the tag - in: query - name: name - required: false - type: string - - description: Comma separated list of datapoints id to filter by - in: query - name: datapoints - required: false - type: string - - description: Comma separated list of groups id to filter by - in: query - name: groups - required: false - type: string - - description: Type of entity related to the tag - enum: - - tp - - tl - - dp - - gr - in: query - name: type - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: List of all the groups associated to the user filtered by this tag. - tags: - - Tags - post: - consumes: - - application/json - - text/json - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: The body of the tag - in: body - name: value - required: true - schema: - $ref: '#/definitions/Api.Core.Dto.Tags.Tag' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Create a tag - tags: - - Tags - /tags/count: - get: - consumes: [] - deprecated: false - parameters: - - description: Name of the tag - in: query - name: name - required: false - type: string - - description: Comma separated list of datapoints id to filter by - in: query - name: datapoints - required: false - type: string - - description: Comma separated list of groups id to filter by - in: query - name: groups - required: false - type: string - - description: Type of entity related to the tag - enum: - - tp - - tl - - dp - - gr - in: query - name: type - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/System.Object' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: List of all the groups associated to the user filtered by this tag. - tags: - - Tags - '/tags/{tagId}': - delete: - consumes: [] - deprecated: false - parameters: - - description: Id of the tag - format: int64 - in: path - name: tagId - required: true - type: integer - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/System.Object' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Delete a tag - tags: - - Tags - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the tag - format: int64 - in: path - name: tagId - required: true - type: integer - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Dto.Tags.Tag' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Retrieve a tag - tags: - - Tags - '/tags/{tagId}/datapoints': - delete: - consumes: [] - deprecated: false - parameters: - - description: Id of the tag - format: int64 - in: path - name: tagId - required: true - type: integer - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Delete the association of this tag with all datapoints - tags: - - Tags - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the tag. - format: int64 - in: path - name: tagId - required: true - type: integer - - default: 0 - description: Where to start when retrieving elements. Default is 0 if not specified. - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - default: 20 - description: Maximum elements to retrieve. Default to 20 if not specified. - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: 'Type of the datapoint ("tp"/"tl")' - enum: - - tp - - tl - in: query - name: type - required: false - type: string - - description: Status of the datapoint - enum: - - deleted - - active - - paused - - spam - in: query - name: status - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Exclude datapoints created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude datapoints created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: List of all the datapoints associated to the user filtered by this tag - tags: - - Tags - '/tags/{tagId}/datapoints/count': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the tag. - format: int64 - in: path - name: tagId - required: true - type: integer - - description: 'Type of the datapoint ("tp"/"tl")' - enum: - - tp - - tl - in: query - name: type - required: false - type: string - - description: Status of the datapoint - enum: - - deleted - - active - - paused - - spam - in: query - name: status - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Exclude datapoints created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude datapoints created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.CountResponce' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Count the datapoints associated to the user filtered by this tag - tags: - - Tags - '/tags/{tagId}/datapoints/patch': - put: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: Id of the tag - format: int64 - in: path - name: tagId - required: true - type: integer - - description: The body patch - in: body - name: data - required: true - schema: - $ref: '#/definitions/Api.Core.Requests.PatchBody' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Associate/Deassociate a tag with a datapoint - tags: - - Tags - '/tags/{tagId}/groups': - delete: - consumes: [] - deprecated: false - parameters: - - description: Id of the tag - format: int64 - in: path - name: tagId - required: true - type: integer - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Delete the association of this tag with all groups - tags: - - Tags - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the tag. - format: int64 - in: path - name: tagId - required: true - type: integer - - default: 0 - description: Where to start when retrieving elements. Default is 0 if not specified. - format: int32 - in: query - minLength: 0 - name: offset - required: false - type: integer - - default: 20 - description: Maximum elements to retrieve. Default to 20 if not specified. - format: int32 - in: query - maxLength: 0 - minLength: 0 - name: limit - required: false - type: integer - - description: Status of the datapoint - enum: - - deleted - - active - in: query - name: status - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Exclude groups created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude groups created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - produces: - - application/json - - text/json - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: List of all the groups associated to the user filtered by this tag. - tags: - - Tags - '/tags/{tagId}/groups/count': - get: - consumes: [] - deprecated: false - parameters: - - description: Id of the tag. - format: int64 - in: path - name: tagId - required: true - type: integer - - description: Status of the datapoint - enum: - - deleted - - active - in: query - name: status - required: false - type: string - - description: Filter fields by this pattern - in: query - name: textSearch - required: false - type: string - - description: Exclude groups created before this date (YYYYMMDD) - in: query - name: createdAfter - required: false - type: string - - description: Exclude groups created after this date (YYYYMMDD) - in: query - name: createdBefore - required: false - type: string - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.CountResponce' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Count the groups associated to the user filtered by this tag - tags: - - Tags - '/tags/{tagId}/groups/patch': - put: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: Id of the tag - format: int64 - in: path - name: tagId - required: true - type: integer - - description: The body patch - in: body - name: data - required: true - schema: - $ref: '#/definitions/Api.Core.Requests.PatchBody' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '404': - description: Not found - '500': - description: Internal Server Error - summary: Associate/Deassociate a tag with a group - tags: - - Tags - '/tags/{tagId}/name': - put: - consumes: - - application/json - - text/json - - application/xml - - text/xml - - application/x-www-form-urlencoded - deprecated: false - parameters: - - description: Id of the tag - format: int64 - in: path - name: tagId - required: true - type: integer - - description: The body patch - in: body - name: data - required: true - schema: - $ref: '#/definitions/Api.Core.Requests.GenericTextPatch' - produces: - - application/json - - text/json - - application/xml - - text/xml - responses: - '200': - description: '' - schema: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - '401': - description: Unauthorized - '500': - description: Internal Server Error - summary: Fast patch a tag name - tags: - - Tags -definitions: - Api.Core.Dto.Accounting.ConversionOptions: - properties: - hideComCost: - type: boolean - hideCost: - type: boolean - hideCount: - type: boolean - hideParams: - type: boolean - hideValue: - type: boolean - percentCommission: - format: int32 - type: integer - percentValue: - format: int32 - type: integer - type: object - Api.Core.Dto.Accounting.DomainWhitelistEntry: - properties: - id: - type: string - name: - type: string - type: object - Api.Core.Dto.Accounting.ExtendedGrants: - properties: - allowAllGrants: - type: boolean - allowGroupCreation: - type: boolean - type: object - Api.Core.Dto.Accounting.Guest: - properties: - apiKey: - type: string - conversionOptions: - $ref: '#/definitions/Api.Core.Dto.Accounting.ConversionOptions' - creationDate: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - currentGrant: - $ref: '#/definitions/Api.Core.Dto.Grants.Grant' - dateFormat: - type: string - decimalSeparator: - type: string - email: - type: string - extendedGrants: - $ref: '#/definitions/Api.Core.Dto.Accounting.ExtendedGrants' - groupGrants: - format: int64 - type: integer - hitOptions: - $ref: '#/definitions/Api.Core.Dto.Accounting.HitOptions' - id: - format: int64 - type: integer - key: - type: string - language: - type: string - loginCount: - format: int32 - type: integer - name: - type: string - notes: - type: string - numberGroupSeparator: - type: string - password: - type: string - timeFormat: - enum: - - AmPm - - H24 - type: string - timeZone: - format: int32 - type: integer - timeframeMinDate: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - timezonename: - type: string - tlGrants: - format: int64 - type: integer - tpGrants: - format: int64 - type: integer - userName: - type: string - type: object - Api.Core.Dto.Accounting.HitOptions: - properties: - hideReferrer: - type: boolean - type: object - Api.Core.Dto.Accounting.IpBlacklistEntry: - properties: - id: - type: string - ip: - type: string - type: object - Api.Core.Dto.Accounting.Plan: - properties: - allowedPersonalDomains: - format: int32 - type: integer - allowedPersonalUrls: - format: int32 - type: integer - billingPeriodEnd: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - billingPeriodStart: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - bonusMonthlyEvents: - format: int64 - type: integer - maximumDatapoints: - format: int64 - type: integer - maximumGuests: - format: int64 - type: integer - monthlyEvents: - format: int64 - type: integer - name: - type: string - price: - format: double - type: number - profileId: - format: int64 - type: integer - recurring: - type: boolean - recurringPeriod: - format: int32 - type: integer - usedDatapoints: - format: int64 - type: integer - usedMonthlyEvents: - format: int64 - type: integer - type: object - Api.Core.Dto.Accounting.User: - properties: - boGoVal: - type: string - bonusClicks: - format: int64 - type: integer - companyName: - type: string - companyRole: - type: string - email: - type: string - firstName: - type: string - lastName: - type: string - phone: - type: string - redirectOnly: - type: boolean - registrationDate: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - timeframeMinDate: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - timezone: - format: int32 - type: integer - timezonename: - type: string - type: object - Api.Core.Dto.Aggregated.AggregatedResult: - properties: - activityDay: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - commissionsCost: - format: double - type: number - conversionsCost: - format: double - type: number - conversionsValue: - format: double - type: number - convertedClicks: - format: int64 - type: integer - entityData: - $ref: '#/definitions/System.Object' - entityId: - type: string - fromDay: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - hourlyBreakDown: - additionalProperties: - $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' - type: object - lastHitDate: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - spiderHitsCount: - format: int64 - type: integer - toDay: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - totalClicks: - format: int64 - type: integer - totalViews: - format: int64 - type: integer - uniqueClicks: - format: int64 - type: integer - uniqueConversions: - format: int64 - type: integer - uniqueViews: - format: int64 - type: integer - type: object - Api.Core.Dto.Aggregated.AggregatedSummaryResult: - properties: - count: - format: int64 - type: integer - limit: - format: int32 - type: integer - offset: - format: int64 - type: integer - result: - items: - $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' - type: array - type: object - Api.Core.Dto.ClickStream.Hit: - properties: - accessTime: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - browser: - $ref: '#/definitions/Api.Core.Dto.ClickStream.HitBrowserInfo' - clientLanguage: - type: string - conversion1: - $ref: '#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo' - conversion2: - $ref: '#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo' - conversion3: - $ref: '#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo' - conversion4: - $ref: '#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo' - conversion5: - $ref: '#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo' - conversions: - items: - $ref: '#/definitions/Api.Core.Dto.ClickStream.HitConversionInfo' - type: array - entity: - $ref: '#/definitions/Api.Core.Dto.ClickStream.HitDatapointInfo' - ip: - type: string - isProxy: - type: string - isSpider: - type: string - isUnique: - type: string - location: - $ref: '#/definitions/Api.Core.Dto.ClickStream.HitLocationInfo' - org: - type: string - os: - $ref: '#/definitions/Api.Core.Dto.ClickStream.HitOsInfo' - queryParams: - type: string - realDestinationUrl: - type: string - referer: - type: string - source: - $ref: '#/definitions/Api.Core.Dto.ClickStream.HitSource' - type: - type: string - type: object - Api.Core.Dto.ClickStream.HitBrowserInfo: - properties: - browserType: - type: string - familyId: - format: int64 - type: integer - familyName: - type: string - id: - format: int64 - type: integer - name: - type: string - type: object - Api.Core.Dto.ClickStream.HitConversionInfo: - properties: - accessTime: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - comcost: - format: double - type: number - cost: - format: double - type: number - date: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - deleted: - type: boolean - id: - format: int64 - type: integer - name: - type: string - parameter: - type: string - value: - format: double - type: number - type: object - Api.Core.Dto.ClickStream.HitDatapointInfo: - properties: - creationDate: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - datapointFavourite: - type: boolean - datapointId: - format: int64 - type: integer - datapointName: - type: string - datapointTitle: - type: string - datapointType: - type: string - destinationUrl: - type: string - groupId: - format: int64 - type: integer - groupName: - type: string - isABTest: - type: boolean - isPrivateShared: - type: boolean - isPublic: - type: boolean - notes: - type: string - status: - enum: - - Active - - Paused - - Abuse - - Deleted - type: string - tags: - items: - $ref: '#/definitions/Api.Core.Dto.Tags.Tag' - type: array - trackingCode: - type: string - type: object - Api.Core.Dto.ClickStream.HitListPage: - properties: - hits: - items: - $ref: '#/definitions/Api.Core.Dto.ClickStream.Hit' - type: array - lastKey: - type: string - type: object - Api.Core.Dto.ClickStream.HitLocationInfo: - properties: - areacode: - type: string - city: - type: string - country: - type: string - latitude: - format: double - type: number - longitude: - format: double - type: number - metrocode: - type: string - organization: - type: string - postalcode: - type: string - region: - type: string - regionName: - type: string - type: object - Api.Core.Dto.ClickStream.HitOsInfo: - properties: - familyId: - format: int64 - type: integer - familyName: - type: string - id: - format: int64 - type: integer - name: - type: string - type: object - Api.Core.Dto.ClickStream.HitSource: - properties: - id: - format: int64 - type: integer - name: - type: string - param: - type: string - type: object - Api.Core.Dto.Conversions.Conversion: - properties: - code: - type: string - creationDate: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - deleted: - type: boolean - description: - type: string - id: - format: int64 - type: integer - name: - type: string - protocol: - enum: - - Http - - Https - type: string - value: - format: double - type: number - type: object - Api.Core.Dto.Datapoints.BrowserBaseDestinationItem: - properties: - emailDestinationUrl: - type: string - mobileDestinationUrl: - type: string - spidersDestinationUrl: - type: string - type: object - Api.Core.Dto.Datapoints.Datapoint: - properties: - creationDate: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - encodeIp: - type: boolean - fifthConversionId: - format: int64 - type: integer - fifthConversionName: - type: string - firstConversionId: - format: int64 - type: integer - firstConversionName: - type: string - fourthConversionId: - format: int64 - type: integer - fourthConversionName: - type: string - groupId: - format: int64 - type: integer - groupName: - type: string - id: - format: int64 - type: integer - isPublic: - type: boolean - isSecured: - type: boolean - lightTracking: - type: boolean - name: - type: string - notes: - type: string - preferred: - type: boolean - redirectOnly: - type: boolean - secondConversionId: - format: int64 - type: integer - secondConversionName: - type: string - status: - enum: - - Active - - Paused - - Abuse - - Deleted - type: string - tags: - items: - $ref: '#/definitions/Api.Core.Dto.Tags.Tag' - type: array - thirdConversionId: - format: int64 - type: integer - thirdConversionName: - type: string - title: - type: string - trackingCode: - type: string - type: - enum: - - TrackingLink - - TrackingPixel - type: string - typeTL: - $ref: '#/definitions/Api.Core.Dto.Datapoints.TrackingLinkSpecifics' - typeTP: - $ref: '#/definitions/Api.Core.Dto.Datapoints.TrackingPixelSpecifics' - writePermited: - type: boolean - type: object - Api.Core.Dto.Datapoints.DatapointRetargetingInfo: - properties: - id: - format: int64 - type: integer - name: - type: string - type: object - Api.Core.Dto.Datapoints.MultipleDestinationItem: - properties: - url: - type: string - type: object - Api.Core.Dto.Datapoints.TrackingLinkSpecifics: - properties: - appendQuery: - type: boolean - browserDestinationItem: - $ref: '#/definitions/Api.Core.Dto.Datapoints.BrowserBaseDestinationItem' - destinationMode: - enum: - - Simple - - RandomDestination - - DestinationByLanguage - - SpilloverDestination - - DynamicUrl - - BrowserDestination - - DestinationByNation - - UniqueDestination - - SequentialDestination - - WeightedDestination - type: string - domainId: - format: int32 - type: integer - encodeUrl: - type: boolean - expirationClicks: - format: int64 - type: integer - expirationDate: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - firstUrl: - type: string - goDomainId: - format: int32 - type: integer - hideUrl: - type: boolean - hideUrlTitle: - type: string - isABTest: - type: boolean - password: - type: string - pauseAfterClicksExpiration: - type: boolean - pauseAfterDateExpiration: - type: boolean - randomDestinationItems: - items: - $ref: '#/definitions/Api.Core.Dto.Datapoints.MultipleDestinationItem' - type: array - redirectType: - enum: - - PermanentRedirect - - TemporaryRedirect - type: string - referrerClean: - enum: - - None - - Clean - - Myself - type: string - scripts: - items: - $ref: '#/definitions/Api.Core.Dto.Datapoints.DatapointRetargetingInfo' - type: array - sequentialDestinationItems: - items: - $ref: '#/definitions/Api.Core.Dto.Datapoints.MultipleDestinationItem' - type: array - spilloverDestinationItems: - items: - $ref: '#/definitions/Api.Core.Dto.Datapoints.MultipleDestinationItem' - type: array - uniqueDestinationItem: - $ref: '#/definitions/Api.Core.Dto.Datapoints.UniqueDestinationItem' - url: - type: string - urlAfterClicksExpiration: - type: string - urlAfterDateExpiration: - type: string - urlsByLanguage: - items: - $ref: '#/definitions/Api.Core.Dto.Datapoints.UrlByLanguageItem' - type: array - urlsByNation: - items: - $ref: '#/definitions/Api.Core.Dto.Datapoints.UrlByNationItem' - type: array - weightedDestinationItems: - items: - $ref: '#/definitions/Api.Core.Dto.Datapoints.WeightedDestinationItem' - type: array - type: object - Api.Core.Dto.Datapoints.TrackingPixelSpecifics: - properties: - parameterNote: - type: string - type: object - Api.Core.Dto.Datapoints.UniqueDestinationItem: - properties: - firstDestinationUrl: - type: string - type: object - Api.Core.Dto.Datapoints.UrlByLanguageItem: - properties: - languageCode: - type: string - url: - type: string - type: object - Api.Core.Dto.Datapoints.UrlByNationItem: - properties: - nation: - type: string - url: - type: string - type: object - Api.Core.Dto.Datapoints.WeightedDestinationItem: - properties: - url: - type: string - weight: - format: int32 - type: integer - type: object - Api.Core.Dto.Domains.Domain: - properties: - custom404: - type: string - customHomepage: - type: string - id: - format: int64 - type: integer - name: - type: string - type: - enum: - - System - - Go - - Dedicated - - Personal - type: string - type: object - Api.Core.Dto.EntityUriLong: - properties: - id: - format: int64 - type: integer - uri: - type: string - type: object - Api.Core.Dto.Grants.Grant: - properties: - DatapointType: - type: string - Entity: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - EntityName: - type: string - EntityType: - type: string - Type: - type: string - type: object - Api.Core.Dto.Groups.Group: - properties: - creationDate: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - deleted: - type: boolean - id: - format: int64 - type: integer - isPublic: - type: boolean - name: - type: string - notes: - type: string - preferred: - type: boolean - redirectOnly: - type: boolean - tags: - items: - $ref: '#/definitions/Api.Core.Dto.Tags.Tag' - type: array - writePermited: - type: boolean - type: object - Api.Core.Dto.Retargeting.RetargetingScript: - properties: - id: - format: int64 - type: integer - name: - type: string - script: - type: string - type: object - Api.Core.Dto.Tags.Tag: - properties: - datapoints: - items: - format: int64 - type: integer - type: array - groups: - items: - format: int64 - type: integer - type: array - id: - format: int64 - type: integer - name: - type: string - type: object - Api.Core.Dto.Tops.Top: - properties: - createdAt: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - data: - items: - $ref: '#/definitions/Api.Core.Dto.Tops.TopItem' - type: array - key: - type: string - type: object - Api.Core.Dto.Tops.TopItem: - properties: - entityData: - $ref: '#/definitions/System.Object' - id: - type: string - lastHitDate: - description: ' (A date in "YmdHis" format)' - example: '20120203120530' - type: string - spiderClicks: - format: int64 - type: integer - spiderHits: - format: int64 - type: integer - spiderViews: - format: int64 - type: integer - totalClicks: - format: int64 - type: integer - totalCommissionsCost: - format: double - type: number - totalConversions: - format: int64 - type: integer - totalConversionsCost: - format: double - type: number - totalConversionsValue: - format: double - type: number - totalHits: - format: int64 - type: integer - totalViews: - format: int64 - type: integer - uniqueClicks: - format: int64 - type: integer - uniqueHits: - format: int64 - type: integer - uniqueViews: - format: int64 - type: integer - type: object - Api.Core.Requests.ConversionPatchBody: - properties: - Action: - type: string - Id: - format: int64 - type: integer - ReplaceId: - format: int64 - type: integer - type: object - Api.Core.Requests.DatapointsBatch: - properties: - List: - items: - $ref: '#/definitions/Api.Core.Dto.Datapoints.Datapoint' - type: array - type: object - Api.Core.Requests.DeleteBatch: - properties: - Entities: - items: - $ref: '#/definitions/Api.Core.Dto.EntityUriLong' - type: array - type: object - Api.Core.Requests.GenericTextPatch: - properties: - Text: - type: string - type: object - Api.Core.Requests.PatchBody: - properties: - Action: - type: string - Id: - format: int64 - type: integer - type: object - Api.Core.Requests.PatchBodyBatch: - properties: - PatchRequests: - items: - $ref: '#/definitions/Api.Core.Requests.PatchBody' - type: array - type: object - Api.Core.Requests.PermissionPatchRequest: - properties: - Action: - type: string - Id: - format: int64 - type: integer - Verb: - type: string - type: object - Api.Core.Responses.CountResponce: - properties: - count: - format: int64 - type: integer - type: object - 'Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.DomainWhitelistEntry]': - properties: - entities: - items: - $ref: '#/definitions/Api.Core.Dto.Accounting.DomainWhitelistEntry' - type: array - type: object - 'Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Accounting.IpBlacklistEntry]': - properties: - entities: - items: - $ref: '#/definitions/Api.Core.Dto.Accounting.IpBlacklistEntry' - type: array - type: object - 'Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Aggregated.AggregatedResult]': - properties: - entities: - items: - $ref: '#/definitions/Api.Core.Dto.Aggregated.AggregatedResult' - type: array - type: object - 'Api.Core.Responses.EntitiesResponse[Api.Core.Dto.ClickStream.Hit]': - properties: - entities: - items: - $ref: '#/definitions/Api.Core.Dto.ClickStream.Hit' - type: array - type: object - 'Api.Core.Responses.EntitiesResponse[Api.Core.Dto.Grants.Grant]': - properties: - entities: - items: - $ref: '#/definitions/Api.Core.Dto.Grants.Grant' - type: array - type: object - 'Api.Core.Responses.EntitiesResponse[Api.Core.Responses.EntityUri[System.Int64]]': - properties: - entities: - items: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - type: array - type: object - 'Api.Core.Responses.EntityUri[System.Int64]': - properties: - id: - format: int64 - type: integer - uri: - type: string - type: object - 'Api.Core.Responses.ModifyBatchItemResponce[Api.Core.Dto.Datapoints.Datapoint,System.Int64]': - properties: - entityData: - $ref: '#/definitions/Api.Core.Dto.Datapoints.Datapoint' - errors: - items: - $ref: '#/definitions/ClickMeter.Infrastructure.Validation.ValidationFailure' - type: array - result: - $ref: '#/definitions/Api.Core.Responses.EntityUri[System.Int64]' - status: - type: string - type: object - ClickMeter.Infrastructure.Validation.ValidationFailure: - properties: - code: - $ref: '#/definitions/System.Object' - errorMessage: - type: string - errorValue: - $ref: '#/definitions/System.Object' - property: - type: string - type: object - System.Object: - properties: {} - type: object diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/invalid-refs.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/invalid-refs.json deleted file mode 100644 index d636d4589..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/expansion/invalid-refs.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "Swagger Petstore", - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - } - }, - "host": "petstore.swagger.wordnik.com", - "basePath": "/api", - "schemes": [ - "http" - ], - "paths": { - "/pets": { - "get": { - "tags": [ "Pet Operations" ], - "summary": "finds pets in the system", - "responses": { - "200": { - "description": "pet response", - "schema": { - "type": "array", - "items": { - "$ref": "NotCorrectRef" - } - }, - "headers": { - "x-expires": { - "type": "string" - } - } - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "NotCorrectRef" - } - } - } - } - } - }, - "definitions": { - "Pet": { - "required": [ - "id", - "name" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "Error": { - "required": [ - "code", - "message" - ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/missingItemRef.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/missingItemRef.json deleted file mode 100644 index f3908d52f..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/expansion/missingItemRef.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "2.1.0", - "title": "Missing Item API" - }, - "host": "item.com", - "basePath": "/missing/ref", - "schemes": [ - "http" - ], - "paths": { - "/employees": { - "get": { - "operationId": "LIST-Employees", - "summary": "List Employee Types", - "responses": { - "200": { - "description": "", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/employees-output" - } - } - } - } - } - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/missingRef.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/missingRef.json deleted file mode 100644 index d59794696..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/expansion/missingRef.json +++ /dev/null @@ -1,165 +0,0 @@ -{ - "input": { - "swagger": "2.0", - "info": { - "version": "1.0", - "title": "Continue On Error" - }, - "paths": { - "/todos": { - "get": { - "responses": { - "200": { - "description": "List Todos", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/todo-full" - } - } - }, - "404": { - "$ref": "#/responses/404" - } - } - } - } - }, - "definitions": { - "todo-partial": { - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "completed": { - "type": "boolean" - } - } - }, - "todo-full": { - "allOf": [ - { - "$ref": "#/definitions/todo-partial" - }, - { - "type": "object", - "properties": { - "id": { - "type": "integer" - }, - "completed_at": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "updated_at": { - "type": "string" - } - } - } - ] - } - } - }, - "expected": { - "swagger": "2.0", - "info": { - "title": "Continue On Error", - "version": "1.0" - }, - "paths": { - "/todos": { - "get": { - "responses": { - "200": { - "description": "List Todos", - "schema": { - "type": "array", - "items": { - "allOf": [ - { - "type": "object", - "properties": { - "completed": { - "type": "boolean" - }, - "name": { - "type": "string" - } - } - }, - { - "type": "object", - "properties": { - "completed_at": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "updated_at": { - "type": "string" - } - } - } - ] - } - } - }, - "404": {} - } - } - } - }, - "definitions": { - "todo-full": { - "allOf": [ - { - "type": "object", - "properties": { - "completed": { - "type": "boolean" - }, - "name": { - "type": "string" - } - } - }, - { - "type": "object", - "properties": { - "completed_at": { - "type": "string" - }, - "created_at": { - "type": "string" - }, - "id": { - "type": "integer" - }, - "updated_at": { - "type": "string" - } - } - } - ] - }, - "todo-partial": { - "type": "object", - "properties": { - "completed": { - "type": "boolean" - }, - "name": { - "type": "string" - } - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/overflow.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/overflow.json deleted file mode 100644 index 5a2a9f3dd..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/expansion/overflow.json +++ /dev/null @@ -1,124 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "title": "Swagger Sample", - "description": "Sample API Playground.", - "version": "1.0.0" - }, - "basePath": "/v1", - "schemes": [ - "http" - ], - "consumes": [ - "application/vdn.sample.v1+json" - ], - "produces": [ - "application/vdn.sample.v1+json" - ], - "paths": { - "/books": { - "get": { - "summary": "List all books", - "operationId": "listBooks", - "tags": [ - "books" - ], - "responses": { - "200": { - "headers": { - "Link": { - "type": "string" - } - }, - "description": "An array of books", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/Book" - } - } - }, - "default": { - "description": "generic error response", - "schema": { - "$ref": "#/definitions/Error" - } - } - } - } - } - }, - "definitions": { - "Store": { - "type": "object", - "properties": { - "title": { - "type": "string", - "example": "Book Shop" - }, - "categories": { - "type": "array", - "items": { - "$ref": "#/definitions/Category" - } - } - } - }, - "Category": { - "type": "object", - "properties": { - "title": { - "type": "string", - "example": "Drama" - }, - "books": { - "type": "array", - "items": { - "$ref": "#/definitions/Book" - } - } - } - }, - "Book": { - "type": "object", - "required": [ - "title", - "summary" - ], - "properties": { - "title": { - "type": "string", - "example": "Winnie the Pooh" - }, - "summary": { - "type": "string", - "example": "Famous children's book" - }, - "related_books": { - "type": "array", - "items": { - "$ref": "#/definitions/Book" - } - } - } - }, - "Error": { - "type": "object", - "readOnly": true, - "properties": { - "code": { - "type": "integer", - "format": "int64", - "example": 400 - }, - "message": { - "type": "string", - "example": "Unexpected error" - } - }, - "required": [ - "message" - ] - } - } -} diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/params.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/params.json deleted file mode 100644 index 76e7b418e..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/expansion/params.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "parameters": { - "id": { - "type": "integer", - "format": "int64", - "in": "path", - "required": true - }, - "tag": { - "type": "string", - "in": "query", - "required": false - }, - "query": { - "$ref": "#/parameters/tag" - } - }, - "paths": { - "/cars/{id}": { - "parameters": [ - { "$ref": "#/parameters/id"} - ] - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/schemas1.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/schemas1.json deleted file mode 100644 index e53a412ef..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/expansion/schemas1.json +++ /dev/null @@ -1,127 +0,0 @@ -{ - "definitions": { - "car": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "make": { - "type": "string" - }, - "brand": { - "$ref": "#/definitions/brand" - } - } - }, - "tag": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "value": { - "type": "string" - } - } - }, - "brand": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - } - }, - "truck": { - "$ref": "#/definitions/car" - }, - "batch": { - "items": { - "$ref": "#/definitions/brand" - } - }, - "batch2": { - "items": [ - { - "$ref": "#/definitions/brand" - }, - { - "$ref": "#/definitions/tag" - } - ] - }, - "allofBoth": { - "allOf": [ - { - "$ref": "#/definitions/brand" - }, - { - "$ref": "#/definitions/tag" - } - ] - }, - "anyofBoth": { - "anyOf": [ - { - "$ref": "#/definitions/brand" - }, - { - "$ref": "#/definitions/tag" - } - ] - }, - "oneofBoth": { - "oneOf": [ - { - "$ref": "#/definitions/brand" - }, - { - "$ref": "#/definitions/tag" - } - ] - }, - "notSomething": { - "not": { - "$ref": "#/definitions/tag" - } - }, - "withAdditional": { - "additionalProperties": { - "$ref": "#/definitions/tag" - } - }, - "withPattern": { - "patternProperties": { - "^x-ab": { - "$ref": "#/definitions/tag" - } - } - }, - "withAdditionalItems": { - "additionalItems": { - "$ref": "#/definitions/tag" - } - }, - "deps": { - "dependencies": { - "something": { - "$ref": "#/definitions/tag" - } - } - }, - "defined": { - "definitions": { - "something": { - "$ref": "#/definitions/tag" - } - } - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/expansion/schemas2.json b/vendor/github.com/go-openapi/spec/fixtures/expansion/schemas2.json deleted file mode 100644 index fe885fd98..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/expansion/schemas2.json +++ /dev/null @@ -1,161 +0,0 @@ -{ - "definitions": { - "car": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "make": { - "type": "string" - }, - "brand": { - "items": { - "$ref": "#/definitions/brand" - } - } - } - }, - "tag": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "value": { - "type": "string" - } - } - }, - "brand": { - "type": "object", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - } - }, - "truck": { - "items": { - "$ref": "#/definitions/car" - } - }, - "batch": { - "items": { - "items": { - "$ref": "#/definitions/brand" - } - } - }, - "batch2": { - "items": [ - { - "items": { - "$ref": "#/definitions/brand" - } - }, - { - "items": { - "$ref": "#/definitions/tag" - } - } - ] - }, - "allofBoth": { - "allOf": [ - { - "items": { - "$ref": "#/definitions/brand" - } - }, - { - "items": { - "$ref": "#/definitions/tag" - } - } - ] - }, - "anyofBoth": { - "anyOf": [ - { - "items": { - "$ref": "#/definitions/brand" - } - }, - { - "items": { - "$ref": "#/definitions/tag" - } - } - ] - }, - "oneofBoth": { - "oneOf": [ - { - "items": { - "$ref": "#/definitions/brand" - } - }, - { - "items": { - "$ref": "#/definitions/tag" - } - } - ] - }, - "notSomething": { - "not": { - "items": { - "$ref": "#/definitions/tag" - } - } - }, - "withAdditional": { - "additionalProperties": { - "items": { - "$ref": "#/definitions/tag" - } - } - }, - "withPattern": { - "patternProperties": { - "^x-ab": { - "items": { - "$ref": "#/definitions/tag" - } - } - } - }, - "withAdditionalItems": { - "additionalItems": { - "items": { - "$ref": "#/definitions/tag" - } - } - }, - "deps": { - "dependencies": { - "something": { - "items": { - "$ref": "#/definitions/tag" - } - } - } - }, - "defined": { - "definitions": { - "something": { - "items": { - "$ref": "#/definitions/tag" - } - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/spec/fixtures/local_expansion/item.json b/vendor/github.com/go-openapi/spec/fixtures/local_expansion/item.json deleted file mode 100644 index f042fdd7a..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/local_expansion/item.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "properties": { - "id": { - "format": "int64", - "readOnly": true, - "type": "integer" - }, - "title": { - "maxLength": 80, - "minLength": 2, - "type": "string" - } - }, - "required": [ - "title" - ], - "type": "object" -} diff --git a/vendor/github.com/go-openapi/spec/fixtures/local_expansion/spec.json b/vendor/github.com/go-openapi/spec/fixtures/local_expansion/spec.json deleted file mode 100644 index 5c653bca8..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/local_expansion/spec.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "basePath": "/v1", - "consumes": [ - "application/json" - ], - "host": "item.api.local", - "info": { - "description": "Item API", - "title": "Item API", - "version": "1.0.0" - }, - "paths": { - "/item": { - "get": { - "operationId": "GetItem", - "responses": { - "200": { - "description": "item detail response", - "schema": { - "$ref": "item.json" - } - } - } - } - } - }, - "produces": [ - "application/json" - ], - "schemes": [ - "http" - ], - "security": [ - { - "key": [] - } - ], - "securityDefinitions": { - "key": { - "in": "header", - "name": "x-item-token", - "type": "apiKey" - } - }, - "swagger": "2.0" -} diff --git a/vendor/github.com/go-openapi/spec/fixtures/remote/all-the-things.json b/vendor/github.com/go-openapi/spec/fixtures/remote/all-the-things.json deleted file mode 100644 index f8e615d3b..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/remote/all-the-things.json +++ /dev/null @@ -1,245 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "Swagger Petstore", - "description": - "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "Wordnik API Team" - }, - "license": { - "name": "MIT" - } - }, - "host": "petstore.swagger.wordnik.com", - "basePath": "/api", - "schemes": ["http"], - "consumes": ["application/json"], - "produces": ["application/json"], - "parameters": { - "idParam": { - "name": "id", - "in": "path", - "description": "ID of pet to fetch", - "required": true, - "type": "integer", - "format": "int64" - }, - "tag": { - "type": "string", - "in": "query", - "required": false - }, - "query": { - "$ref": "#/parameters/tag" - } - }, - "responses": { - "petResponse": { - "description": "pet response", - "schema": { - "$ref": "pet/pet.json#/definitions/pet" - } - }, - "stringResponse": { - "descripion": "string response", - "schema": { - "type": "string" - } - }, - "anotherPet": { - "$ref": "pet/pet.json#/responses/anotherPet" - }, - "circularA": { - "$ref": "pet/pet.json#/responses/circularB" - } - }, - "paths": { - "/": { - "get": { - "operationId": "indexStuff", - "responses": { - "default": { - "$ref": "#/responses/stringResponse" - }, - "200": { - "$ref": "#/responses/anotherPet" - } - } - } - }, - "/pets": { - "get": { - "description": - "Returns all pets from the system that the user has access to", - "operationId": "findPets", - "produces": [ - "application/json", - "application/xml", - "text/xml", - "text/html" - ], - "parameters": [ - { - "name": "tags", - "in": "query", - "description": "tags to filter by", - "required": false, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - }, - { - "name": "limit", - "in": "query", - "description": "maximum number of results to return", - "required": false, - "type": "integer", - "format": "int32" - } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "type": "array", - "items": { - "$ref": "pet/pet.json#/definitions/pet" - } - } - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - }, - "post": { - "description": - "Creates a new pet in the store. Duplicates are allowed", - "operationId": "addPet", - "produces": ["application/json"], - "parameters": [ - { - "name": "pet", - "in": "body", - "description": "Pet to add to the store", - "required": true, - "schema": { - "$ref": "#/definitions/petInput" - } - } - ], - "responses": { - "200": { "$ref": "#/responses/petResponse" }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - } - }, - "/pets/{id}": { - "get": { - "description": - "Returns a user based on a single ID, if the user does not have access to the pet", - "operationId": "findPetById", - "produces": [ - "application/json", - "application/xml", - "text/xml", - "text/html" - ], - "parameters": [ - { - "$ref": "#/parameters/idParam" - } - ], - "responses": { - "200": { - "$ref": "#/responses/petResponse" - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - }, - "delete": { - "description": "deletes a single pet based on the ID supplied", - "operationId": "deletePet", - "parameters": [ - { - "$ref": "#/parameters/idParam" - } - ], - "responses": { - "204": { - "description": "pet deleted" - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - } - } - }, - "definitions": { - "pet": { - "required": ["id", "name"], - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "petInput": { - "allOf": [ - { - "$ref": "pet/pet.json#/definitions/pet" - }, - { - "required": ["name"], - "properties": { - "id": { - "type": "integer", - "format": "int64" - } - } - } - ] - }, - "errorModel": { - "required": ["code", "message"], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/spec/fixtures/remote/pet/pet.json b/vendor/github.com/go-openapi/spec/fixtures/remote/pet/pet.json deleted file mode 100644 index 7b631f3e5..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/remote/pet/pet.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "responses": { - "petResponse": { - "description": "pet response", - "schema": { - "$ref": "#/definitions/pet" - } - }, - "stringResponse": { - "descripion": "string response", - "schema": { - "type": "string" - } - }, - "circularB": { - "$ref": "#/responses/circularC" - }, - "circularC": { - "$ref": "../all-the-things.json#/responses/circularA" - }, - "anotherPet": { - "$ref": "#/responses/petResponse" - } - }, - "definitions": { - "pet": { - "required": ["id", "name"], - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/spec/fixtures/specs/deeper/arrayProp.json b/vendor/github.com/go-openapi/spec/fixtures/specs/deeper/arrayProp.json deleted file mode 100644 index 8f8dbf6ba..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/specs/deeper/arrayProp.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "type":"array", - "items": { - "type": "string" - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/specs/deeper/stringProp.json b/vendor/github.com/go-openapi/spec/fixtures/specs/deeper/stringProp.json deleted file mode 100644 index 169a0d70f..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/specs/deeper/stringProp.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "type": "string" -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/specs/refed.json b/vendor/github.com/go-openapi/spec/fixtures/specs/refed.json deleted file mode 100644 index 142be8bb9..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/specs/refed.json +++ /dev/null @@ -1,224 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "Swagger Petstore", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "Wordnik API Team" - }, - "license": { - "name": "MIT" - } - }, - "host": "petstore.swagger.wordnik.com", - "basePath": "/api", - "schemes": [ - "http" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "parameters": { - "idParam": { - "name": "id", - "in": "path", - "description": "ID of pet to fetch", - "required": true, - "type": "integer", - "format": "int64" - } - }, - "responses": { - "petResponse": { - "description": "pet response", - "schema": { - "$ref": "#/definitions/pet" - } - } - }, - "paths": { - "/pets": { - "get": { - "description": "Returns all pets from the system that the user has access to", - "operationId": "findPets", - "produces": [ - "application/json", - "application/xml", - "text/xml", - "text/html" - ], - "parameters": [ - { - "name": "tags", - "in": "query", - "description": "tags to filter by", - "required": false, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - }, - { - "name": "limit", - "in": "query", - "description": "maximum number of results to return", - "required": false, - "type": "integer", - "format": "int32" - } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/pet" - } - } - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - }, - "post": { - "description": "Creates a new pet in the store. Duplicates are allowed", - "operationId": "addPet", - "produces": [ - "application/json" - ], - "parameters": [ - { - "name": "pet", - "in": "body", - "description": "Pet to add to the store", - "required": true, - "schema": { - "$ref": "#/definitions/petInput" - } - } - ], - "responses": { - "200": { "$ref": "#/responses/petResponse" }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - } - }, - "/pets/{id}": { - "get": { - "description": "Returns a user based on a single ID, if the user does not have access to the pet", - "operationId": "findPetById", - "produces": [ - "application/json", - "application/xml", - "text/xml", - "text/html" - ], - "parameters": [ - { - "$ref": "#/parameters/idParam" - } - ], - "responses": { - "200": { - "$ref": "#/responses/petResponse" - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - }, - "delete": { - "description": "deletes a single pet based on the ID supplied", - "operationId": "deletePet", - "parameters": [ - { - "$ref": "#/parameters/idParam" - } - ], - "responses": { - "204": { - "description": "pet deleted" - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/errorModel" - } - } - } - } - } - }, - "definitions": { - "pet": { - "required": [ - "id", - "name" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "petInput": { - "allOf": [ - { - "$ref": "pet" - }, - { - "required": [ - "name" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - } - } - } - ] - }, - "errorModel": { - "required": [ - "code", - "message" - ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/specs/resolution.json b/vendor/github.com/go-openapi/spec/fixtures/specs/resolution.json deleted file mode 100644 index 43cabe858..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/specs/resolution.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "id": "http://localhost:1234", - "items": { - "id": "deeper/", - "items": { - "$ref": "stringProp.json" - } - }, - "definitions": { - "bool": { - "$ref": "boolProp.json" - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/specs/resolution2.json b/vendor/github.com/go-openapi/spec/fixtures/specs/resolution2.json deleted file mode 100644 index 5d7a00560..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/specs/resolution2.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "id": "http://localhost:1234", - "items": { - "id": "deeper/", - "items": { - "$ref": "arrayProp.json#/items" - } - } -} \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/fixtures/specs/todos.common.json b/vendor/github.com/go-openapi/spec/fixtures/specs/todos.common.json deleted file mode 100644 index 1c43908a6..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/specs/todos.common.json +++ /dev/null @@ -1,103 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0", - "title": "To-do Demo", - "description": - "### Notes:\n\nThis OAS2 (Swagger 2) specification defines common models and responses, that other specifications may reference.\n\nFor example, check out the user poperty in the main.oas2 todo-partial model - it references the user model in this specification!\n\nLikewise, the main.oas2 operations reference the shared error responses in this common specification.", - "contact": { - "name": "Stoplight", - "url": "https://stoplight.io" - }, - "license": { - "name": "MIT" - } - }, - "host": "example.com", - "securityDefinitions": {}, - "paths": {}, - "responses": { - "401": { - "description": "", - "schema": { - "$ref": "#/definitions/error-response" - }, - "examples": { - "application/json": { - "status": "401", - "error": "Not Authorized" - } - } - }, - "403": { - "description": "", - "schema": { - "$ref": "#/definitions/error-response" - }, - "examples": { - "application/json": { - "status": "403", - "error": "Forbbiden" - } - } - }, - "404": { - "description": "", - "schema": { - "$ref": "#/definitions/error-response" - }, - "examples": { - "application/json": { - "status": "404", - "error": "Not Found" - } - } - }, - "500": { - "description": "", - "schema": { - "$ref": "#/definitions/error-response" - }, - "examples": { - "application/json": { - "status": "500", - "error": "Server Error" - } - } - } - }, - "definitions": { - "user": { - "title": "User", - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "The user's full name." - }, - "age": { - "type": "number", - "minimum": 0, - "maximum": 150 - }, - "error": { - "$ref": "#/definitions/error-response" - } - }, - "required": ["name", "age"] - }, - "error-response": { - "type": "object", - "title": "Error Response", - "properties": { - "status": { - "type": "string" - }, - "error": { - "type": "string" - } - }, - "required": ["status", "error"] - } - } -} diff --git a/vendor/github.com/go-openapi/spec/fixtures/specs/todos.json b/vendor/github.com/go-openapi/spec/fixtures/specs/todos.json deleted file mode 100644 index b9460bdc4..000000000 --- a/vendor/github.com/go-openapi/spec/fixtures/specs/todos.json +++ /dev/null @@ -1,346 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0", - "title": "To-do Demo", - "description": "This OAS2 (Swagger 2) file represents a real API that lives at http://todos.stoplight.io.\n\nFor authentication information, click the apikey security scheme in the editor sidebar.", - "contact": { - "name": "Stoplight", - "url": "https://stoplight.io" - }, - "license": { - "name": "MIT" - } - }, - "host": "todos.stoplight.io", - "schemes": ["http"], - "consumes": ["application/json"], - "produces": ["application/json"], - "securityDefinitions": { - "Basic": { - "type": "basic" - }, - "API Key": { - "type": "apiKey", - "name": "apikey", - "in": "query" - } - }, - "paths": { - "/todos/{todoId}": { - "parameters": [{ - "name": "todoId", - "in": "path", - "required": true, - "type": "string" - }], - "get": { - "operationId": "GET_todo", - "summary": "Get Todo", - "tags": ["Todos"], - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/todo-full" - }, - "examples": { - "application/json": { - "id": 1, - "name": "get food", - "completed": false, - "completed_at": "1955-04-23T13:22:52.685Z", - "created_at": "1994-11-05T03:26:51.471Z", - "updated_at": "1989-07-29T11:30:06.701Z" - }, - "/todos/foobar": "{\n\t\"foo\": \"bar\"\n}\n", - "/todos/chores": { - "id": 9000, - "name": "Do Chores", - "completed": false, - "created_at": "2014-08-28T14:14:28.494Z", - "updated_at": "2014-08-28T14:14:28.494Z" - }, - "new": { - "name": "esse qui proident labore", - "completed": null, - "id": 920778, - "completed_at": "2014-01-07T07:49:55.123Z", - "created_at": "1948-04-21T12:04:21.282Z", - "updated_at": "1951-12-19T11:10:34.039Z", - "user": { - "name": "irure deserunt fugiat", - "age": 121.45395681110494 - }, - "float": -47990796.228164576 - } - } - }, - "404": { - "$ref": "./todos.common.json#/responses/404" - }, - "500": { - "$ref": "./todos.common.json#/responses/500" - } - }, - "parameters": [{ - "in": "query", - "name": "", - "type": "string" - }] - }, - "put": { - "operationId": "PUT_todos", - "summary": "Update Todo", - "tags": ["Todos"], - "parameters": [{ - "name": "body", - "in": "body", - "schema": { - "$ref": "#/definitions/todo-partial", - "example": { - "name": "my todo's new name", - "completed": false - } - } - }], - "responses": { - "200": { - "description": "", - "schema": { - "$ref": "#/definitions/todo-full" - }, - "examples": { - "application/json": { - "id": 9000, - "name": "It's Over 9000!!!", - "completed": true, - "completed_at": null, - "created_at": "2014-08-28T14:14:28.494Z", - "updated_at": "2015-08-28T14:14:28.494Z" - } - } - }, - "401": { - "$ref": "./todos.common.json#/responses/401" - }, - "404": { - "$ref": "./todos.common.json#/responses/404" - }, - "500": { - "$ref": "./todos.common.json#/responses/500" - } - }, - "security": [{ - "Basic": [] - }, - { - "API Key": [] - } - ] - }, - "delete": { - "operationId": "DELETE_todo", - "summary": "Delete Todo", - "tags": ["Todos"], - "responses": { - "204": { - "description": "" - }, - "401": { - "$ref": "./todos.common.json#/responses/401" - }, - "404": { - "$ref": "./todos.common.json#/responses/404" - }, - "500": { - "$ref": "./todos.common.json#/responses/500" - } - }, - "security": [{ - "Basic": [] - }, - { - "API Key": [] - } - ] - } - }, - "/todos": { - "post": { - "operationId": "POST_todos", - "summary": "Create Todo", - "tags": ["Todos"], - "parameters": [{ - "name": "body", - "in": "body", - "schema": { - "$ref": "#/definitions/todo-partial", - "example": { - "name": "my todo's name", - "completed": false - } - } - }], - "responses": { - "201": { - "description": "", - "schema": { - "$ref": "#/definitions/todo-full" - }, - "examples": { - "application/json": { - "id": 9000, - "name": "It's Over 9000!!!", - "completed": null, - "completed_at": null, - "created_at": "2014-08-28T14:14:28.494Z", - "updated_at": "2014-08-28T14:14:28.494Z" - }, - "/todos/chores": { - "id": 9000, - "name": "Do Chores", - "completed": false, - "created_at": "2014-08-28T14:14:28.494Z", - "updated_at": "2014-08-28T14:14:28.494Z" - } - } - }, - "401": { - "$ref": "./todos.common.json#/responses/401" - }, - "500": { - "$ref": "./todos.common.json#/responses/500" - } - }, - "security": [{ - "API Key": [] - }, - { - "Basic": [] - } - ], - "description": "This creates a Todo object.\n\nTesting `inline code`." - }, - "get": { - "operationId": "GET_todos", - "summary": "List Todos", - "tags": ["Todos"], - "parameters": [{ - "$ref": "#/parameters/limit" - }, - { - "$ref": "#/parameters/skip" - } - ], - "responses": { - "200": { - "description": "", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/todo-full" - } - }, - "examples": { - "application/json": [{ - "id": 1, - "name": "design the thingz", - "completed": true - }, - { - "id": 2, - "name": "mock the thingz", - "completed": true - }, - { - "id": 3, - "name": "code the thingz", - "completed": false - } - ], - "empty": [] - }, - "headers": { - "foo": { - "type": "string", - "default": "bar" - } - } - }, - "500": { - "$ref": "./todos.common.json#/responses/500" - } - }, - "description": "​" - } - } - }, - "parameters": { - "limit": { - "name": "limit", - "in": "query", - "description": "This is how it works.", - "required": false, - "type": "integer", - "maximum": 100 - }, - "skip": { - "name": "skip", - "in": "query", - "required": false, - "type": "string" - } - }, - "definitions": { - "todo-partial": { - "title": "Todo Partial", - "type": "object", - "properties": { - "name": { - "type": "string" - }, - "completed": { - "type": ["boolean", "null"] - } - }, - "required": ["name", "completed"] - }, - "todo-full": { - "title": "Todo Full", - "allOf": [{ - "$ref": "#/definitions/todo-partial" - }, - { - "type": "object", - "properties": { - "id": { - "type": "integer", - "minimum": 0, - "maximum": 1000000 - }, - "completed_at": { - "type": ["string", "null"], - "format": "date-time" - }, - "created_at": { - "type": "string", - "format": "date-time" - }, - "updated_at": { - "type": "string", - "format": "date-time" - }, - "user": { - "$ref": "./todos.common.json#/definitions/user" - } - }, - "required": ["id", "user"] - } - ] - } - }, - "tags": [{ - "name": "Todos" - }] -} diff --git a/vendor/github.com/go-openapi/spec/header.go b/vendor/github.com/go-openapi/spec/header.go deleted file mode 100644 index 85c4d454c..000000000 --- a/vendor/github.com/go-openapi/spec/header.go +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "strings" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -type HeaderProps struct { - Description string `json:"description,omitempty"` -} - -// Header describes a header for a response of the API -// -// For more information: http://goo.gl/8us55a#headerObject -type Header struct { - CommonValidations - SimpleSchema - VendorExtensible - HeaderProps -} - -// ResponseHeader creates a new header instance for use in a response -func ResponseHeader() *Header { - return new(Header) -} - -// WithDescription sets the description on this response, allows for chaining -func (h *Header) WithDescription(description string) *Header { - h.Description = description - return h -} - -// Typed a fluent builder method for the type of parameter -func (h *Header) Typed(tpe, format string) *Header { - h.Type = tpe - h.Format = format - return h -} - -// CollectionOf a fluent builder method for an array item -func (h *Header) CollectionOf(items *Items, format string) *Header { - h.Type = "array" - h.Items = items - h.CollectionFormat = format - return h -} - -// WithDefault sets the default value on this item -func (h *Header) WithDefault(defaultValue interface{}) *Header { - h.Default = defaultValue - return h -} - -// WithMaxLength sets a max length value -func (h *Header) WithMaxLength(max int64) *Header { - h.MaxLength = &max - return h -} - -// WithMinLength sets a min length value -func (h *Header) WithMinLength(min int64) *Header { - h.MinLength = &min - return h -} - -// WithPattern sets a pattern value -func (h *Header) WithPattern(pattern string) *Header { - h.Pattern = pattern - return h -} - -// WithMultipleOf sets a multiple of value -func (h *Header) WithMultipleOf(number float64) *Header { - h.MultipleOf = &number - return h -} - -// WithMaximum sets a maximum number value -func (h *Header) WithMaximum(max float64, exclusive bool) *Header { - h.Maximum = &max - h.ExclusiveMaximum = exclusive - return h -} - -// WithMinimum sets a minimum number value -func (h *Header) WithMinimum(min float64, exclusive bool) *Header { - h.Minimum = &min - h.ExclusiveMinimum = exclusive - return h -} - -// WithEnum sets a the enum values (replace) -func (h *Header) WithEnum(values ...interface{}) *Header { - h.Enum = append([]interface{}{}, values...) - return h -} - -// WithMaxItems sets the max items -func (h *Header) WithMaxItems(size int64) *Header { - h.MaxItems = &size - return h -} - -// WithMinItems sets the min items -func (h *Header) WithMinItems(size int64) *Header { - h.MinItems = &size - return h -} - -// UniqueValues dictates that this array can only have unique items -func (h *Header) UniqueValues() *Header { - h.UniqueItems = true - return h -} - -// AllowDuplicates this array can have duplicates -func (h *Header) AllowDuplicates() *Header { - h.UniqueItems = false - return h -} - -// MarshalJSON marshal this to JSON -func (h Header) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(h.CommonValidations) - if err != nil { - return nil, err - } - b2, err := json.Marshal(h.SimpleSchema) - if err != nil { - return nil, err - } - b3, err := json.Marshal(h.HeaderProps) - if err != nil { - return nil, err - } - return swag.ConcatJSON(b1, b2, b3), nil -} - -// UnmarshalJSON marshal this from JSON -func (h *Header) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &h.CommonValidations); err != nil { - return err - } - if err := json.Unmarshal(data, &h.SimpleSchema); err != nil { - return err - } - if err := json.Unmarshal(data, &h.VendorExtensible); err != nil { - return err - } - if err := json.Unmarshal(data, &h.HeaderProps); err != nil { - return err - } - return nil -} - -// JSONLookup look up a value by the json property name -func (p Header) JSONLookup(token string) (interface{}, error) { - if ex, ok := p.Extensions[token]; ok { - return &ex, nil - } - - r, _, err := jsonpointer.GetForToken(p.CommonValidations, token) - if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { - return nil, err - } - if r != nil { - return r, nil - } - r, _, err = jsonpointer.GetForToken(p.SimpleSchema, token) - if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { - return nil, err - } - if r != nil { - return r, nil - } - r, _, err = jsonpointer.GetForToken(p.HeaderProps, token) - return r, err -} diff --git a/vendor/github.com/go-openapi/spec/header_test.go b/vendor/github.com/go-openapi/spec/header_test.go deleted file mode 100644 index a07d174fd..000000000 --- a/vendor/github.com/go-openapi/spec/header_test.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -func float64Ptr(f float64) *float64 { - return &f -} -func int64Ptr(f int64) *int64 { - return &f -} - -var header = Header{ - VendorExtensible: VendorExtensible{Extensions: map[string]interface{}{ - "x-framework": "swagger-go", - }}, - HeaderProps: HeaderProps{Description: "the description of this header"}, - SimpleSchema: SimpleSchema{ - Items: &Items{ - Refable: Refable{Ref: MustCreateRef("Cat")}, - }, - Type: "string", - Format: "date", - Default: "8", - }, - CommonValidations: CommonValidations{ - Maximum: float64Ptr(100), - ExclusiveMaximum: true, - ExclusiveMinimum: true, - Minimum: float64Ptr(5), - MaxLength: int64Ptr(100), - MinLength: int64Ptr(5), - Pattern: "\\w{1,5}\\w+", - MaxItems: int64Ptr(100), - MinItems: int64Ptr(5), - UniqueItems: true, - MultipleOf: float64Ptr(5), - Enum: []interface{}{"hello", "world"}, - }, -} - -var headerJSON = `{ - "items": { - "$ref": "Cat" - }, - "x-framework": "swagger-go", - "description": "the description of this header", - "maximum": 100, - "minimum": 5, - "exclusiveMaximum": true, - "exclusiveMinimum": true, - "maxLength": 100, - "minLength": 5, - "pattern": "\\w{1,5}\\w+", - "maxItems": 100, - "minItems": 5, - "uniqueItems": true, - "multipleOf": 5, - "enum": ["hello", "world"], - "type": "string", - "format": "date", - "default": "8" -}` - -func TestIntegrationHeader(t *testing.T) { - var actual Header - if assert.NoError(t, json.Unmarshal([]byte(headerJSON), &actual)) { - assert.EqualValues(t, actual, header) - } - - assertParsesJSON(t, headerJSON, header) -} diff --git a/vendor/github.com/go-openapi/spec/info.go b/vendor/github.com/go-openapi/spec/info.go deleted file mode 100644 index fb8b7c4ac..000000000 --- a/vendor/github.com/go-openapi/spec/info.go +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "strings" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -// Extensions vendor specific extensions -type Extensions map[string]interface{} - -// Add adds a value to these extensions -func (e Extensions) Add(key string, value interface{}) { - realKey := strings.ToLower(key) - e[realKey] = value -} - -// GetString gets a string value from the extensions -func (e Extensions) GetString(key string) (string, bool) { - if v, ok := e[strings.ToLower(key)]; ok { - str, ok := v.(string) - return str, ok - } - return "", false -} - -// GetBool gets a string value from the extensions -func (e Extensions) GetBool(key string) (bool, bool) { - if v, ok := e[strings.ToLower(key)]; ok { - str, ok := v.(bool) - return str, ok - } - return false, false -} - -// GetStringSlice gets a string value from the extensions -func (e Extensions) GetStringSlice(key string) ([]string, bool) { - if v, ok := e[strings.ToLower(key)]; ok { - arr, ok := v.([]interface{}) - if !ok { - return nil, false - } - var strs []string - for _, iface := range arr { - str, ok := iface.(string) - if !ok { - return nil, false - } - strs = append(strs, str) - } - return strs, ok - } - return nil, false -} - -// VendorExtensible composition block. -type VendorExtensible struct { - Extensions Extensions -} - -// AddExtension adds an extension to this extensible object -func (v *VendorExtensible) AddExtension(key string, value interface{}) { - if value == nil { - return - } - if v.Extensions == nil { - v.Extensions = make(map[string]interface{}) - } - v.Extensions.Add(key, value) -} - -// MarshalJSON marshals the extensions to json -func (v VendorExtensible) MarshalJSON() ([]byte, error) { - toser := make(map[string]interface{}) - for k, v := range v.Extensions { - lk := strings.ToLower(k) - if strings.HasPrefix(lk, "x-") { - toser[k] = v - } - } - return json.Marshal(toser) -} - -// UnmarshalJSON for this extensible object -func (v *VendorExtensible) UnmarshalJSON(data []byte) error { - var d map[string]interface{} - if err := json.Unmarshal(data, &d); err != nil { - return err - } - for k, vv := range d { - lk := strings.ToLower(k) - if strings.HasPrefix(lk, "x-") { - if v.Extensions == nil { - v.Extensions = map[string]interface{}{} - } - v.Extensions[k] = vv - } - } - return nil -} - -// InfoProps the properties for an info definition -type InfoProps struct { - Description string `json:"description,omitempty"` - Title string `json:"title,omitempty"` - TermsOfService string `json:"termsOfService,omitempty"` - Contact *ContactInfo `json:"contact,omitempty"` - License *License `json:"license,omitempty"` - Version string `json:"version,omitempty"` -} - -// Info object provides metadata about the API. -// The metadata can be used by the clients if needed, and can be presented in the Swagger-UI for convenience. -// -// For more information: http://goo.gl/8us55a#infoObject -type Info struct { - VendorExtensible - InfoProps -} - -// JSONLookup look up a value by the json property name -func (i Info) JSONLookup(token string) (interface{}, error) { - if ex, ok := i.Extensions[token]; ok { - return &ex, nil - } - r, _, err := jsonpointer.GetForToken(i.InfoProps, token) - return r, err -} - -// MarshalJSON marshal this to JSON -func (i Info) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(i.InfoProps) - if err != nil { - return nil, err - } - b2, err := json.Marshal(i.VendorExtensible) - if err != nil { - return nil, err - } - return swag.ConcatJSON(b1, b2), nil -} - -// UnmarshalJSON marshal this from JSON -func (i *Info) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &i.InfoProps); err != nil { - return err - } - if err := json.Unmarshal(data, &i.VendorExtensible); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/go-openapi/spec/info_test.go b/vendor/github.com/go-openapi/spec/info_test.go deleted file mode 100644 index fc40c1630..000000000 --- a/vendor/github.com/go-openapi/spec/info_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var infoJSON = `{ - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "title": "Swagger Sample API", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - }, - "version": "1.0.9-abcd", - "x-framework": "go-swagger" -}` - -var info = Info{ - InfoProps: InfoProps{ - Version: "1.0.9-abcd", - Title: "Swagger Sample API", - Description: "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - TermsOfService: "http://helloreverb.com/terms/", - Contact: &ContactInfo{Name: "wordnik api team", URL: "http://developer.wordnik.com"}, - License: &License{Name: "Creative Commons 4.0 International", URL: "http://creativecommons.org/licenses/by/4.0/"}, - }, - VendorExtensible: VendorExtensible{map[string]interface{}{"x-framework": "go-swagger"}}, -} - -func TestIntegrationInfo_Serialize(t *testing.T) { - b, err := json.MarshalIndent(info, "", "\t") - if assert.NoError(t, err) { - assert.Equal(t, infoJSON, string(b)) - } -} - -func TestIntegrationInfo_Deserialize(t *testing.T) { - actual := Info{} - err := json.Unmarshal([]byte(infoJSON), &actual) - if assert.NoError(t, err) { - assert.EqualValues(t, info, actual) - } -} diff --git a/vendor/github.com/go-openapi/spec/items.go b/vendor/github.com/go-openapi/spec/items.go deleted file mode 100644 index 492423ef7..000000000 --- a/vendor/github.com/go-openapi/spec/items.go +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "strings" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -type SimpleSchema struct { - Type string `json:"type,omitempty"` - Format string `json:"format,omitempty"` - 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 { - if s.Format != "" { - return s.Format - } - return s.Type -} - -func (s *SimpleSchema) ItemsTypeName() string { - if s.Items == nil { - return "" - } - return s.Items.TypeName() -} - -type CommonValidations struct { - Maximum *float64 `json:"maximum,omitempty"` - ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` - Minimum *float64 `json:"minimum,omitempty"` - ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` - MaxLength *int64 `json:"maxLength,omitempty"` - MinLength *int64 `json:"minLength,omitempty"` - Pattern string `json:"pattern,omitempty"` - MaxItems *int64 `json:"maxItems,omitempty"` - MinItems *int64 `json:"minItems,omitempty"` - UniqueItems bool `json:"uniqueItems,omitempty"` - MultipleOf *float64 `json:"multipleOf,omitempty"` - Enum []interface{} `json:"enum,omitempty"` -} - -// Items a limited subset of JSON-Schema's items object. -// It is used by parameter definitions that are not located in "body". -// -// For more information: http://goo.gl/8us55a#items-object -type Items struct { - Refable - CommonValidations - SimpleSchema - VendorExtensible -} - -// NewItems creates a new instance of items -func NewItems() *Items { - return &Items{} -} - -// Typed a fluent builder method for the type of item -func (i *Items) Typed(tpe, format string) *Items { - i.Type = tpe - i.Format = format - return i -} - -// CollectionOf a fluent builder method for an array item -func (i *Items) CollectionOf(items *Items, format string) *Items { - i.Type = "array" - i.Items = items - i.CollectionFormat = format - return i -} - -// WithDefault sets the default value on this item -func (i *Items) WithDefault(defaultValue interface{}) *Items { - i.Default = defaultValue - return i -} - -// WithMaxLength sets a max length value -func (i *Items) WithMaxLength(max int64) *Items { - i.MaxLength = &max - return i -} - -// WithMinLength sets a min length value -func (i *Items) WithMinLength(min int64) *Items { - i.MinLength = &min - return i -} - -// WithPattern sets a pattern value -func (i *Items) WithPattern(pattern string) *Items { - i.Pattern = pattern - return i -} - -// WithMultipleOf sets a multiple of value -func (i *Items) WithMultipleOf(number float64) *Items { - i.MultipleOf = &number - return i -} - -// WithMaximum sets a maximum number value -func (i *Items) WithMaximum(max float64, exclusive bool) *Items { - i.Maximum = &max - i.ExclusiveMaximum = exclusive - return i -} - -// WithMinimum sets a minimum number value -func (i *Items) WithMinimum(min float64, exclusive bool) *Items { - i.Minimum = &min - i.ExclusiveMinimum = exclusive - return i -} - -// WithEnum sets a the enum values (replace) -func (i *Items) WithEnum(values ...interface{}) *Items { - i.Enum = append([]interface{}{}, values...) - return i -} - -// WithMaxItems sets the max items -func (i *Items) WithMaxItems(size int64) *Items { - i.MaxItems = &size - return i -} - -// WithMinItems sets the min items -func (i *Items) WithMinItems(size int64) *Items { - i.MinItems = &size - return i -} - -// UniqueValues dictates that this array can only have unique items -func (i *Items) UniqueValues() *Items { - i.UniqueItems = true - return i -} - -// AllowDuplicates this array can have duplicates -func (i *Items) AllowDuplicates() *Items { - i.UniqueItems = false - return i -} - -// UnmarshalJSON hydrates this items instance with the data from JSON -func (i *Items) UnmarshalJSON(data []byte) error { - var validations CommonValidations - if err := json.Unmarshal(data, &validations); err != nil { - return err - } - var ref Refable - if err := json.Unmarshal(data, &ref); err != nil { - return err - } - var simpleSchema SimpleSchema - 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 -} - -// MarshalJSON converts this items object to JSON -func (i Items) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(i.CommonValidations) - if err != nil { - return nil, err - } - b2, err := json.Marshal(i.SimpleSchema) - if err != nil { - return nil, err - } - b3, err := json.Marshal(i.Refable) - if err != nil { - return nil, err - } - 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 -func (p Items) JSONLookup(token string) (interface{}, error) { - if token == "$ref" { - return &p.Ref, nil - } - - r, _, err := jsonpointer.GetForToken(p.CommonValidations, token) - if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { - return nil, err - } - if r != nil { - return r, nil - } - r, _, err = jsonpointer.GetForToken(p.SimpleSchema, token) - return r, err -} diff --git a/vendor/github.com/go-openapi/spec/items_test.go b/vendor/github.com/go-openapi/spec/items_test.go deleted file mode 100644 index 2f9ac11b4..000000000 --- a/vendor/github.com/go-openapi/spec/items_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var items = Items{ - Refable: Refable{Ref: MustCreateRef("Dog")}, - CommonValidations: CommonValidations{ - Maximum: float64Ptr(100), - ExclusiveMaximum: true, - ExclusiveMinimum: true, - Minimum: float64Ptr(5), - MaxLength: int64Ptr(100), - MinLength: int64Ptr(5), - Pattern: "\\w{1,5}\\w+", - MaxItems: int64Ptr(100), - MinItems: int64Ptr(5), - UniqueItems: true, - MultipleOf: float64Ptr(5), - Enum: []interface{}{"hello", "world"}, - }, - SimpleSchema: SimpleSchema{ - Type: "string", - Format: "date", - Items: &Items{ - Refable: Refable{Ref: MustCreateRef("Cat")}, - }, - CollectionFormat: "csv", - Default: "8", - }, -} - -var itemsJSON = `{ - "items": { - "$ref": "Cat" - }, - "$ref": "Dog", - "maximum": 100, - "minimum": 5, - "exclusiveMaximum": true, - "exclusiveMinimum": true, - "maxLength": 100, - "minLength": 5, - "pattern": "\\w{1,5}\\w+", - "maxItems": 100, - "minItems": 5, - "uniqueItems": true, - "multipleOf": 5, - "enum": ["hello", "world"], - "type": "string", - "format": "date", - "collectionFormat": "csv", - "default": "8" -}` - -func TestIntegrationItems(t *testing.T) { - var actual Items - if assert.NoError(t, json.Unmarshal([]byte(itemsJSON), &actual)) { - assert.EqualValues(t, actual, items) - } - - assertParsesJSON(t, itemsJSON, items) -} diff --git a/vendor/github.com/go-openapi/spec/license.go b/vendor/github.com/go-openapi/spec/license.go deleted file mode 100644 index f20961b4f..000000000 --- a/vendor/github.com/go-openapi/spec/license.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -// License information for the exposed API. -// -// For more information: http://goo.gl/8us55a#licenseObject -type License struct { - Name string `json:"name,omitempty"` - URL string `json:"url,omitempty"` -} diff --git a/vendor/github.com/go-openapi/spec/license_test.go b/vendor/github.com/go-openapi/spec/license_test.go deleted file mode 100644 index 8ed51a352..000000000 --- a/vendor/github.com/go-openapi/spec/license_test.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import "testing" - -func TestIntegrationLicense(t *testing.T) { - license := License{"the name", "the url"} - const licenseJSON = `{"name":"the name","url":"the url"}` - const licenseYAML = "name: the name\nurl: the url\n" - - assertSerializeJSON(t, license, licenseJSON) - assertSerializeYAML(t, license, licenseYAML) - assertParsesJSON(t, licenseJSON, license) - assertParsesYAML(t, licenseYAML, license) -} diff --git a/vendor/github.com/go-openapi/spec/operation.go b/vendor/github.com/go-openapi/spec/operation.go deleted file mode 100644 index e698f9e8a..000000000 --- a/vendor/github.com/go-openapi/spec/operation.go +++ /dev/null @@ -1,258 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -type OperationProps struct { - Description string `json:"description,omitempty"` - Consumes []string `json:"consumes,omitempty"` - Produces []string `json:"produces,omitempty"` - Schemes []string `json:"schemes,omitempty"` // the scheme, when present must be from [http, https, ws, wss] - Tags []string `json:"tags,omitempty"` - Summary string `json:"summary,omitempty"` - ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` - ID string `json:"operationId,omitempty"` - Deprecated bool `json:"deprecated,omitempty"` - Security []map[string][]string `json:"security,omitempty"` //Special case, see MarshalJSON function - Parameters []Parameter `json:"parameters,omitempty"` - Responses *Responses `json:"responses,omitempty"` -} - -// MarshalJSON takes care of serializing operation properties to JSON -// -// We use a custom marhaller here to handle a special cases related -// the Security field. We need to preserve zero length slice -// while omiting the field when the value is nil/unset. -func (op OperationProps) MarshalJSON() ([]byte, error) { - type Alias OperationProps - if op.Security == nil { - return json.Marshal(&struct { - Security []map[string][]string `json:"security,omitempty"` - *Alias - }{ - Security: op.Security, - Alias: (*Alias)(&op), - }) - } - return json.Marshal(&struct { - Security []map[string][]string `json:"security"` - *Alias - }{ - Security: op.Security, - Alias: (*Alias)(&op), - }) -} - -// Operation describes a single API operation on a path. -// -// For more information: http://goo.gl/8us55a#operationObject -type Operation struct { - VendorExtensible - OperationProps -} - -// SuccessResponse gets a success response model -func (o *Operation) SuccessResponse() (*Response, int, bool) { - if o.Responses == nil { - return nil, 0, false - } - - for k, v := range o.Responses.StatusCodeResponses { - if k/100 == 2 { - return &v, k, true - } - } - - return o.Responses.Default, 0, false -} - -// JSONLookup look up a value by the json property name -func (o Operation) JSONLookup(token string) (interface{}, error) { - if ex, ok := o.Extensions[token]; ok { - return &ex, nil - } - r, _, err := jsonpointer.GetForToken(o.OperationProps, token) - return r, err -} - -// UnmarshalJSON hydrates this items instance with the data from JSON -func (o *Operation) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &o.OperationProps); err != nil { - return err - } - if err := json.Unmarshal(data, &o.VendorExtensible); err != nil { - return err - } - return nil -} - -// MarshalJSON converts this items object to JSON -func (o Operation) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(o.OperationProps) - if err != nil { - return nil, err - } - b2, err := json.Marshal(o.VendorExtensible) - if err != nil { - return nil, err - } - concated := swag.ConcatJSON(b1, b2) - return concated, nil -} - -// NewOperation creates a new operation instance. -// It expects an ID as parameter but not passing an ID is also valid. -func NewOperation(id string) *Operation { - op := new(Operation) - op.ID = id - return op -} - -// WithID sets the ID property on this operation, allows for chaining. -func (o *Operation) WithID(id string) *Operation { - o.ID = id - return o -} - -// WithDescription sets the description on this operation, allows for chaining -func (o *Operation) WithDescription(description string) *Operation { - o.Description = description - return o -} - -// WithSummary sets the summary on this operation, allows for chaining -func (o *Operation) WithSummary(summary string) *Operation { - o.Summary = summary - return o -} - -// WithExternalDocs sets/removes the external docs for/from this operation. -// When you pass empty strings as params the external documents will be removed. -// When you pass non-empty string as one value then those values will be used on the external docs object. -// So when you pass a non-empty description, you should also pass the url and vice versa. -func (o *Operation) WithExternalDocs(description, url string) *Operation { - if description == "" && url == "" { - o.ExternalDocs = nil - return o - } - - if o.ExternalDocs == nil { - o.ExternalDocs = &ExternalDocumentation{} - } - o.ExternalDocs.Description = description - o.ExternalDocs.URL = url - return o -} - -// Deprecate marks the operation as deprecated -func (o *Operation) Deprecate() *Operation { - o.Deprecated = true - return o -} - -// Undeprecate marks the operation as not deprected -func (o *Operation) Undeprecate() *Operation { - o.Deprecated = false - return o -} - -// WithConsumes adds media types for incoming body values -func (o *Operation) WithConsumes(mediaTypes ...string) *Operation { - o.Consumes = append(o.Consumes, mediaTypes...) - return o -} - -// WithProduces adds media types for outgoing body values -func (o *Operation) WithProduces(mediaTypes ...string) *Operation { - o.Produces = append(o.Produces, mediaTypes...) - return o -} - -// WithTags adds tags for this operation -func (o *Operation) WithTags(tags ...string) *Operation { - o.Tags = append(o.Tags, tags...) - return o -} - -// AddParam adds a parameter to this operation, when a parameter for that location -// and with that name already exists it will be replaced -func (o *Operation) AddParam(param *Parameter) *Operation { - if param == nil { - return o - } - - for i, p := range o.Parameters { - if p.Name == param.Name && p.In == param.In { - params := append(o.Parameters[:i], *param) - params = append(params, o.Parameters[i+1:]...) - o.Parameters = params - return o - } - } - - o.Parameters = append(o.Parameters, *param) - return o -} - -// RemoveParam removes a parameter from the operation -func (o *Operation) RemoveParam(name, in string) *Operation { - for i, p := range o.Parameters { - if p.Name == name && p.In == name { - o.Parameters = append(o.Parameters[:i], o.Parameters[i+1:]...) - return o - } - } - return o -} - -// SecuredWith adds a security scope to this operation. -func (o *Operation) SecuredWith(name string, scopes ...string) *Operation { - o.Security = append(o.Security, map[string][]string{name: scopes}) - return o -} - -// WithDefaultResponse adds a default response to the operation. -// Passing a nil value will remove the response -func (o *Operation) WithDefaultResponse(response *Response) *Operation { - return o.RespondsWith(0, response) -} - -// RespondsWith adds a status code response to the operation. -// When the code is 0 the value of the response will be used as default response value. -// When the value of the response is nil it will be removed from the operation -func (o *Operation) RespondsWith(code int, response *Response) *Operation { - if o.Responses == nil { - o.Responses = new(Responses) - } - if code == 0 { - o.Responses.Default = response - return o - } - if response == nil { - delete(o.Responses.StatusCodeResponses, code) - return o - } - if o.Responses.StatusCodeResponses == nil { - o.Responses.StatusCodeResponses = make(map[int]Response) - } - o.Responses.StatusCodeResponses[code] = *response - return o -} diff --git a/vendor/github.com/go-openapi/spec/operation_test.go b/vendor/github.com/go-openapi/spec/operation_test.go deleted file mode 100644 index c88ceb4fa..000000000 --- a/vendor/github.com/go-openapi/spec/operation_test.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var operation = Operation{ - VendorExtensible: VendorExtensible{ - Extensions: map[string]interface{}{ - "x-framework": "go-swagger", - }, - }, - OperationProps: OperationProps{ - Description: "operation description", - Consumes: []string{"application/json", "application/x-yaml"}, - Produces: []string{"application/json", "application/x-yaml"}, - Schemes: []string{"http", "https"}, - Tags: []string{"dogs"}, - Summary: "the summary of the operation", - ID: "sendCat", - Deprecated: true, - Security: []map[string][]string{ - map[string][]string{ - "apiKey": []string{}, - }, - }, - Parameters: []Parameter{ - Parameter{Refable: Refable{Ref: MustCreateRef("Cat")}}, - }, - Responses: &Responses{ - ResponsesProps: ResponsesProps{ - Default: &Response{ - ResponseProps: ResponseProps{ - Description: "void response", - }, - }, - }, - }, - }, -} - -var operationJSON = `{ - "description": "operation description", - "x-framework": "go-swagger", - "consumes": [ "application/json", "application/x-yaml" ], - "produces": [ "application/json", "application/x-yaml" ], - "schemes": ["http", "https"], - "tags": ["dogs"], - "summary": "the summary of the operation", - "operationId": "sendCat", - "deprecated": true, - "security": [ { "apiKey": [] } ], - "parameters": [{"$ref":"Cat"}], - "responses": { - "default": { - "description": "void response" - } - } -}` - -func TestIntegrationOperation(t *testing.T) { - var actual Operation - if assert.NoError(t, json.Unmarshal([]byte(operationJSON), &actual)) { - assert.EqualValues(t, actual, operation) - } - - assertParsesJSON(t, operationJSON, operation) -} - -func TestSecurityProperty(t *testing.T) { - //Ensure we omit security key when unset - securityNotSet := OperationProps{} - jsonResult, err := json.Marshal(securityNotSet) - if assert.NoError(t, err) { - assert.NotContains(t, string(jsonResult), "security", "security key should be omitted when unset") - } - - //Ensure we preseve the security key when it contains an empty (zero length) slice - securityContainsEmptyArray := OperationProps{ - Security: []map[string][]string{}, - } - jsonResult, err = json.Marshal(securityContainsEmptyArray) - if assert.NoError(t, err) { - var props OperationProps - if assert.NoError(t, json.Unmarshal(jsonResult, &props)) { - assert.Equal(t, securityContainsEmptyArray, props) - } - } - -} diff --git a/vendor/github.com/go-openapi/spec/parameter.go b/vendor/github.com/go-openapi/spec/parameter.go deleted file mode 100644 index 71aee1e80..000000000 --- a/vendor/github.com/go-openapi/spec/parameter.go +++ /dev/null @@ -1,301 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "strings" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -// QueryParam creates a query parameter -func QueryParam(name string) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name, In: "query"}} -} - -// HeaderParam creates a header parameter, this is always required by default -func HeaderParam(name string) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name, In: "header", Required: true}} -} - -// PathParam creates a path parameter, this is always required -func PathParam(name string) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name, In: "path", Required: true}} -} - -// BodyParam creates a body parameter -func BodyParam(name string, schema *Schema) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name, In: "body", Schema: schema}, SimpleSchema: SimpleSchema{Type: "object"}} -} - -// FormDataParam creates a body parameter -func FormDataParam(name string) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"}} -} - -// FileParam creates a body parameter -func FileParam(name string) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"}, SimpleSchema: SimpleSchema{Type: "file"}} -} - -// SimpleArrayParam creates a param for a simple array (string, int, date etc) -func SimpleArrayParam(name, tpe, fmt string) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name}, SimpleSchema: SimpleSchema{Type: "array", CollectionFormat: "csv", Items: &Items{SimpleSchema: SimpleSchema{Type: "string", Format: fmt}}}} -} - -// ParamRef creates a parameter that's a json reference -func ParamRef(uri string) *Parameter { - p := new(Parameter) - p.Ref = MustCreateRef(uri) - return p -} - -type ParamProps struct { - Description string `json:"description,omitempty"` - Name string `json:"name,omitempty"` - In string `json:"in,omitempty"` - Required bool `json:"required,omitempty"` - Schema *Schema `json:"schema,omitempty"` // when in == "body" - AllowEmptyValue bool `json:"allowEmptyValue,omitempty"` // when in == "query" || "formData" -} - -// Parameter a unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). -// -// There are five possible parameter types. -// * Path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`. -// * Query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. -// * Header - Custom headers that are expected as part of the request. -// * Body - The payload that's appended to the HTTP request. Since there can only be one payload, there can only be *one* body parameter. The name of the body parameter has no effect on the parameter itself and is used for documentation purposes only. Since Form parameters are also in the payload, body and form parameters cannot exist together for the same operation. -// * Form - Used to describe the payload of an HTTP request when either `application/x-www-form-urlencoded` or `multipart/form-data` are used as the content type of the request (in Swagger's definition, the [`consumes`](#operationConsumes) property of an operation). This is the only parameter type that can be used to send files, thus supporting the `file` type. Since form parameters are sent in the payload, they cannot be declared together with a body parameter for the same operation. Form parameters have a different format based on the content-type used (for further details, consult http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4): -// * `application/x-www-form-urlencoded` - Similar to the format of Query parameters but as a payload. For example, `foo=1&bar=swagger` - both `foo` and `bar` are form parameters. This is normally used for simple parameters that are being transferred. -// * `multipart/form-data` - each parameter takes a section in the payload with an internal header. For example, for the header `Content-Disposition: form-data; name="submit-name"` the name of the parameter is `submit-name`. This type of form parameters is more commonly used for file transfers. -// -// For more information: http://goo.gl/8us55a#parameterObject -type Parameter struct { - Refable - CommonValidations - SimpleSchema - VendorExtensible - ParamProps -} - -// JSONLookup look up a value by the json property name -func (p Parameter) JSONLookup(token string) (interface{}, error) { - if ex, ok := p.Extensions[token]; ok { - return &ex, nil - } - if token == "$ref" { - return &p.Ref, nil - } - - r, _, err := jsonpointer.GetForToken(p.CommonValidations, token) - if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { - return nil, err - } - if r != nil { - return r, nil - } - r, _, err = jsonpointer.GetForToken(p.SimpleSchema, token) - if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { - return nil, err - } - if r != nil { - return r, nil - } - r, _, err = jsonpointer.GetForToken(p.ParamProps, token) - return r, err -} - -// WithDescription a fluent builder method for the description of the parameter -func (p *Parameter) WithDescription(description string) *Parameter { - p.Description = description - return p -} - -// Named a fluent builder method to override the name of the parameter -func (p *Parameter) Named(name string) *Parameter { - p.Name = name - return p -} - -// WithLocation a fluent builder method to override the location of the parameter -func (p *Parameter) WithLocation(in string) *Parameter { - p.In = in - return p -} - -// Typed a fluent builder method for the type of the parameter value -func (p *Parameter) Typed(tpe, format string) *Parameter { - p.Type = tpe - p.Format = format - return p -} - -// CollectionOf a fluent builder method for an array parameter -func (p *Parameter) CollectionOf(items *Items, format string) *Parameter { - p.Type = "array" - p.Items = items - p.CollectionFormat = format - return p -} - -// WithDefault sets the default value on this parameter -func (p *Parameter) WithDefault(defaultValue interface{}) *Parameter { - p.AsOptional() // with default implies optional - p.Default = defaultValue - return p -} - -// AllowsEmptyValues flags this parameter as being ok with empty values -func (p *Parameter) AllowsEmptyValues() *Parameter { - p.AllowEmptyValue = true - return p -} - -// NoEmptyValues flags this parameter as not liking empty values -func (p *Parameter) NoEmptyValues() *Parameter { - p.AllowEmptyValue = false - return p -} - -// AsOptional flags this parameter as optional -func (p *Parameter) AsOptional() *Parameter { - p.Required = false - return p -} - -// AsRequired flags this parameter as required -func (p *Parameter) AsRequired() *Parameter { - if p.Default != nil { // with a default required makes no sense - return p - } - p.Required = true - return p -} - -// WithMaxLength sets a max length value -func (p *Parameter) WithMaxLength(max int64) *Parameter { - p.MaxLength = &max - return p -} - -// WithMinLength sets a min length value -func (p *Parameter) WithMinLength(min int64) *Parameter { - p.MinLength = &min - return p -} - -// WithPattern sets a pattern value -func (p *Parameter) WithPattern(pattern string) *Parameter { - p.Pattern = pattern - return p -} - -// WithMultipleOf sets a multiple of value -func (p *Parameter) WithMultipleOf(number float64) *Parameter { - p.MultipleOf = &number - return p -} - -// WithMaximum sets a maximum number value -func (p *Parameter) WithMaximum(max float64, exclusive bool) *Parameter { - p.Maximum = &max - p.ExclusiveMaximum = exclusive - return p -} - -// WithMinimum sets a minimum number value -func (p *Parameter) WithMinimum(min float64, exclusive bool) *Parameter { - p.Minimum = &min - p.ExclusiveMinimum = exclusive - return p -} - -// WithEnum sets a the enum values (replace) -func (p *Parameter) WithEnum(values ...interface{}) *Parameter { - p.Enum = append([]interface{}{}, values...) - return p -} - -// WithMaxItems sets the max items -func (p *Parameter) WithMaxItems(size int64) *Parameter { - p.MaxItems = &size - return p -} - -// WithMinItems sets the min items -func (p *Parameter) WithMinItems(size int64) *Parameter { - p.MinItems = &size - return p -} - -// UniqueValues dictates that this array can only have unique items -func (p *Parameter) UniqueValues() *Parameter { - p.UniqueItems = true - return p -} - -// AllowDuplicates this array can have duplicates -func (p *Parameter) AllowDuplicates() *Parameter { - p.UniqueItems = false - return p -} - -// UnmarshalJSON hydrates this items instance with the data from JSON -func (p *Parameter) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &p.CommonValidations); err != nil { - return err - } - if err := json.Unmarshal(data, &p.Refable); err != nil { - return err - } - if err := json.Unmarshal(data, &p.SimpleSchema); err != nil { - return err - } - if err := json.Unmarshal(data, &p.VendorExtensible); err != nil { - return err - } - if err := json.Unmarshal(data, &p.ParamProps); err != nil { - return err - } - return nil -} - -// MarshalJSON converts this items object to JSON -func (p Parameter) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(p.CommonValidations) - if err != nil { - return nil, err - } - b2, err := json.Marshal(p.SimpleSchema) - if err != nil { - return nil, err - } - b3, err := json.Marshal(p.Refable) - if err != nil { - return nil, err - } - b4, err := json.Marshal(p.VendorExtensible) - if err != nil { - return nil, err - } - b5, err := json.Marshal(p.ParamProps) - if err != nil { - return nil, err - } - return swag.ConcatJSON(b3, b1, b2, b4, b5), nil -} diff --git a/vendor/github.com/go-openapi/spec/parameters_test.go b/vendor/github.com/go-openapi/spec/parameters_test.go deleted file mode 100644 index 424f66332..000000000 --- a/vendor/github.com/go-openapi/spec/parameters_test.go +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var parameter = Parameter{ - VendorExtensible: VendorExtensible{Extensions: map[string]interface{}{ - "x-framework": "swagger-go", - }}, - Refable: Refable{Ref: MustCreateRef("Dog")}, - CommonValidations: CommonValidations{ - Maximum: float64Ptr(100), - ExclusiveMaximum: true, - ExclusiveMinimum: true, - Minimum: float64Ptr(5), - MaxLength: int64Ptr(100), - MinLength: int64Ptr(5), - Pattern: "\\w{1,5}\\w+", - MaxItems: int64Ptr(100), - MinItems: int64Ptr(5), - UniqueItems: true, - MultipleOf: float64Ptr(5), - Enum: []interface{}{"hello", "world"}, - }, - SimpleSchema: SimpleSchema{ - Type: "string", - Format: "date", - CollectionFormat: "csv", - Items: &Items{ - Refable: Refable{Ref: MustCreateRef("Cat")}, - }, - Default: "8", - }, - ParamProps: ParamProps{ - Name: "param-name", - In: "header", - Required: true, - Schema: &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - Description: "the description of this parameter", - }, -} - -var parameterJSON = `{ - "items": { - "$ref": "Cat" - }, - "x-framework": "swagger-go", - "$ref": "Dog", - "description": "the description of this parameter", - "maximum": 100, - "minimum": 5, - "exclusiveMaximum": true, - "exclusiveMinimum": true, - "maxLength": 100, - "minLength": 5, - "pattern": "\\w{1,5}\\w+", - "maxItems": 100, - "minItems": 5, - "uniqueItems": true, - "multipleOf": 5, - "enum": ["hello", "world"], - "type": "string", - "format": "date", - "name": "param-name", - "in": "header", - "required": true, - "schema": { - "type": "string" - }, - "collectionFormat": "csv", - "default": "8" -}` - -func TestIntegrationParameter(t *testing.T) { - var actual Parameter - if assert.NoError(t, json.Unmarshal([]byte(parameterJSON), &actual)) { - assert.EqualValues(t, actual, parameter) - } - - assertParsesJSON(t, parameterJSON, parameter) -} - -func TestParameterSerialization(t *testing.T) { - items := &Items{ - SimpleSchema: SimpleSchema{Type: "string"}, - } - - intItems := &Items{ - SimpleSchema: SimpleSchema{Type: "int", Format: "int32"}, - } - - assertSerializeJSON(t, QueryParam("").Typed("string", ""), `{"type":"string","in":"query"}`) - - assertSerializeJSON(t, - QueryParam("").CollectionOf(items, "multi"), - `{"type":"array","items":{"type":"string"},"collectionFormat":"multi","in":"query"}`) - - assertSerializeJSON(t, PathParam("").Typed("string", ""), `{"type":"string","in":"path","required":true}`) - - assertSerializeJSON(t, - PathParam("").CollectionOf(items, "multi"), - `{"type":"array","items":{"type":"string"},"collectionFormat":"multi","in":"path","required":true}`) - - assertSerializeJSON(t, - PathParam("").CollectionOf(intItems, "multi"), - `{"type":"array","items":{"type":"int","format":"int32"},"collectionFormat":"multi","in":"path","required":true}`) - - assertSerializeJSON(t, HeaderParam("").Typed("string", ""), `{"type":"string","in":"header","required":true}`) - - assertSerializeJSON(t, - HeaderParam("").CollectionOf(items, "multi"), - `{"type":"array","items":{"type":"string"},"collectionFormat":"multi","in":"header","required":true}`) - schema := &Schema{SchemaProps: SchemaProps{ - Properties: map[string]Schema{ - "name": Schema{SchemaProps: SchemaProps{ - Type: []string{"string"}, - }}, - }, - }} - - refSchema := &Schema{ - SchemaProps: SchemaProps{Ref: MustCreateRef("Cat")}, - } - - assertSerializeJSON(t, - BodyParam("", schema), - `{"type":"object","in":"body","schema":{"properties":{"name":{"type":"string"}}}}`) - - assertSerializeJSON(t, - BodyParam("", refSchema), - `{"type":"object","in":"body","schema":{"$ref":"Cat"}}`) - - // array body param - assertSerializeJSON(t, - BodyParam("", ArrayProperty(RefProperty("Cat"))), - `{"type":"object","in":"body","schema":{"type":"array","items":{"$ref":"Cat"}}}`) - -} diff --git a/vendor/github.com/go-openapi/spec/path_item.go b/vendor/github.com/go-openapi/spec/path_item.go deleted file mode 100644 index 9ab3ec538..000000000 --- a/vendor/github.com/go-openapi/spec/path_item.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -// pathItemProps the path item specific properties -type PathItemProps struct { - Get *Operation `json:"get,omitempty"` - Put *Operation `json:"put,omitempty"` - Post *Operation `json:"post,omitempty"` - Delete *Operation `json:"delete,omitempty"` - Options *Operation `json:"options,omitempty"` - Head *Operation `json:"head,omitempty"` - Patch *Operation `json:"patch,omitempty"` - Parameters []Parameter `json:"parameters,omitempty"` -} - -// PathItem describes the operations available on a single path. -// A Path Item may be empty, due to [ACL constraints](http://goo.gl/8us55a#securityFiltering). -// The path itself is still exposed to the documentation viewer but they will -// not know which operations and parameters are available. -// -// For more information: http://goo.gl/8us55a#pathItemObject -type PathItem struct { - Refable - VendorExtensible - PathItemProps -} - -// JSONLookup look up a value by the json property name -func (p PathItem) JSONLookup(token string) (interface{}, error) { - if ex, ok := p.Extensions[token]; ok { - return &ex, nil - } - if token == "$ref" { - return &p.Ref, nil - } - r, _, err := jsonpointer.GetForToken(p.PathItemProps, token) - return r, err -} - -// UnmarshalJSON hydrates this items instance with the data from JSON -func (p *PathItem) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &p.Refable); err != nil { - return err - } - if err := json.Unmarshal(data, &p.VendorExtensible); err != nil { - return err - } - if err := json.Unmarshal(data, &p.PathItemProps); err != nil { - return err - } - return nil -} - -// MarshalJSON converts this items object to JSON -func (p PathItem) MarshalJSON() ([]byte, error) { - b3, err := json.Marshal(p.Refable) - if err != nil { - return nil, err - } - b4, err := json.Marshal(p.VendorExtensible) - if err != nil { - return nil, err - } - b5, err := json.Marshal(p.PathItemProps) - if err != nil { - return nil, err - } - concated := swag.ConcatJSON(b3, b4, b5) - return concated, nil -} diff --git a/vendor/github.com/go-openapi/spec/path_item_test.go b/vendor/github.com/go-openapi/spec/path_item_test.go deleted file mode 100644 index ea77e6a9b..000000000 --- a/vendor/github.com/go-openapi/spec/path_item_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var pathItem = PathItem{ - Refable: Refable{Ref: MustCreateRef("Dog")}, - VendorExtensible: VendorExtensible{ - Extensions: map[string]interface{}{ - "x-framework": "go-swagger", - }, - }, - PathItemProps: PathItemProps{ - Get: &Operation{ - OperationProps: OperationProps{Description: "get operation description"}, - }, - Put: &Operation{ - OperationProps: OperationProps{Description: "put operation description"}, - }, - Post: &Operation{ - OperationProps: OperationProps{Description: "post operation description"}, - }, - Delete: &Operation{ - OperationProps: OperationProps{Description: "delete operation description"}, - }, - Options: &Operation{ - OperationProps: OperationProps{Description: "options operation description"}, - }, - Head: &Operation{ - OperationProps: OperationProps{Description: "head operation description"}, - }, - Patch: &Operation{ - OperationProps: OperationProps{Description: "patch operation description"}, - }, - Parameters: []Parameter{ - Parameter{ - ParamProps: ParamProps{In: "path"}, - }, - }, - }, -} - -var pathItemJSON = `{ - "$ref": "Dog", - "x-framework": "go-swagger", - "get": { "description": "get operation description" }, - "put": { "description": "put operation description" }, - "post": { "description": "post operation description" }, - "delete": { "description": "delete operation description" }, - "options": { "description": "options operation description" }, - "head": { "description": "head operation description" }, - "patch": { "description": "patch operation description" }, - "parameters": [{"in":"path"}] -}` - -func TestIntegrationPathItem(t *testing.T) { - var actual PathItem - if assert.NoError(t, json.Unmarshal([]byte(pathItemJSON), &actual)) { - assert.EqualValues(t, actual, pathItem) - } - - assertParsesJSON(t, pathItemJSON, pathItem) -} diff --git a/vendor/github.com/go-openapi/spec/paths.go b/vendor/github.com/go-openapi/spec/paths.go deleted file mode 100644 index 9dc82a290..000000000 --- a/vendor/github.com/go-openapi/spec/paths.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "fmt" - "strings" - - "github.com/go-openapi/swag" -) - -// Paths holds the relative paths to the individual endpoints. -// The path is appended to the [`basePath`](http://goo.gl/8us55a#swaggerBasePath) in order -// to construct the full URL. -// The Paths may be empty, due to [ACL constraints](http://goo.gl/8us55a#securityFiltering). -// -// For more information: http://goo.gl/8us55a#pathsObject -type Paths struct { - VendorExtensible - Paths map[string]PathItem `json:"-"` // custom serializer to flatten this, each entry must start with "/" -} - -// JSONLookup look up a value by the json property name -func (p Paths) JSONLookup(token string) (interface{}, error) { - if pi, ok := p.Paths[token]; ok { - return &pi, nil - } - if ex, ok := p.Extensions[token]; ok { - return &ex, nil - } - return nil, fmt.Errorf("object has no field %q", token) -} - -// UnmarshalJSON hydrates this items instance with the data from JSON -func (p *Paths) UnmarshalJSON(data []byte) error { - var res map[string]json.RawMessage - if err := json.Unmarshal(data, &res); err != nil { - return err - } - for k, v := range res { - if strings.HasPrefix(strings.ToLower(k), "x-") { - if p.Extensions == nil { - p.Extensions = make(map[string]interface{}) - } - var d interface{} - if err := json.Unmarshal(v, &d); err != nil { - return err - } - p.Extensions[k] = d - } - if strings.HasPrefix(k, "/") { - if p.Paths == nil { - p.Paths = make(map[string]PathItem) - } - var pi PathItem - if err := json.Unmarshal(v, &pi); err != nil { - return err - } - p.Paths[k] = pi - } - } - return nil -} - -// MarshalJSON converts this items object to JSON -func (p Paths) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(p.VendorExtensible) - if err != nil { - return nil, err - } - - pths := make(map[string]PathItem) - for k, v := range p.Paths { - if strings.HasPrefix(k, "/") { - pths[k] = v - } - } - b2, err := json.Marshal(pths) - if err != nil { - return nil, err - } - concated := swag.ConcatJSON(b1, b2) - return concated, nil -} diff --git a/vendor/github.com/go-openapi/spec/paths_test.go b/vendor/github.com/go-openapi/spec/paths_test.go deleted file mode 100644 index 5ccfd4a0a..000000000 --- a/vendor/github.com/go-openapi/spec/paths_test.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var paths = Paths{ - VendorExtensible: VendorExtensible{Extensions: map[string]interface{}{"x-framework": "go-swagger"}}, - Paths: map[string]PathItem{ - "/": PathItem{ - Refable: Refable{Ref: MustCreateRef("cats")}, - }, - }, -} - -var pathsJSON = `{"x-framework":"go-swagger","/":{"$ref":"cats"}}` - -func TestIntegrationPaths(t *testing.T) { - var actual Paths - if assert.NoError(t, json.Unmarshal([]byte(pathsJSON), &actual)) { - assert.EqualValues(t, actual, paths) - } - - assertParsesJSON(t, pathsJSON, paths) - -} diff --git a/vendor/github.com/go-openapi/spec/properties_test.go b/vendor/github.com/go-openapi/spec/properties_test.go deleted file mode 100644 index 90bd32c9e..000000000 --- a/vendor/github.com/go-openapi/spec/properties_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "testing" -) - -func TestPropertySerialization(t *testing.T) { - strProp := StringProperty() - strProp.Enum = append(strProp.Enum, "a", "b") - - prop := &Schema{SchemaProps: SchemaProps{ - Items: &SchemaOrArray{Schemas: []Schema{ - Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - }}, - }} - - var propSerData = []struct { - Schema *Schema - JSON string - }{ - {BooleanProperty(), `{"type":"boolean"}`}, - {DateProperty(), `{"type":"string","format":"date"}`}, - {DateTimeProperty(), `{"type":"string","format":"date-time"}`}, - {Float64Property(), `{"type":"number","format":"double"}`}, - {Float32Property(), `{"type":"number","format":"float"}`}, - {Int32Property(), `{"type":"integer","format":"int32"}`}, - {Int64Property(), `{"type":"integer","format":"int64"}`}, - {MapProperty(StringProperty()), `{"type":"object","additionalProperties":{"type":"string"}}`}, - {MapProperty(Int32Property()), `{"type":"object","additionalProperties":{"type":"integer","format":"int32"}}`}, - {RefProperty("Dog"), `{"$ref":"Dog"}`}, - {StringProperty(), `{"type":"string"}`}, - {strProp, `{"type":"string","enum":["a","b"]}`}, - {ArrayProperty(StringProperty()), `{"type":"array","items":{"type":"string"}}`}, - {prop, `{"items":[{"type":"string"},{"type":"string"}]}`}, - } - - for _, v := range propSerData { - t.Log("roundtripping for", v.JSON) - assertSerializeJSON(t, v.Schema, v.JSON) - assertParsesJSON(t, v.JSON, v.Schema) - } - -} diff --git a/vendor/github.com/go-openapi/spec/ref.go b/vendor/github.com/go-openapi/spec/ref.go deleted file mode 100644 index 1405bfd8e..000000000 --- a/vendor/github.com/go-openapi/spec/ref.go +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "net/http" - "os" - "path/filepath" - - "github.com/go-openapi/jsonreference" -) - -// Refable is a struct for things that accept a $ref property -type Refable struct { - Ref Ref -} - -// MarshalJSON marshals the ref to json -func (r Refable) MarshalJSON() ([]byte, error) { - return r.Ref.MarshalJSON() -} - -// UnmarshalJSON unmarshalss the ref from json -func (r *Refable) UnmarshalJSON(d []byte) error { - return json.Unmarshal(d, &r.Ref) -} - -// Ref represents a json reference that is potentially resolved -type Ref struct { - jsonreference.Ref -} - -// RemoteURI gets the remote uri part of the ref -func (r *Ref) RemoteURI() string { - if r.String() == "" { - return r.String() - } - - u := *r.GetURL() - u.Fragment = "" - return u.String() -} - -// IsValidURI returns true when the url the ref points to can be found -func (r *Ref) IsValidURI(basepaths ...string) bool { - if r.String() == "" { - return true - } - - v := r.RemoteURI() - if v == "" { - return true - } - - if r.HasFullURL { - rr, err := http.Get(v) - if err != nil { - return false - } - - return rr.StatusCode/100 == 2 - } - - if !(r.HasFileScheme || r.HasFullFilePath || r.HasURLPathOnly) { - return false - } - - // check for local file - pth := v - if r.HasURLPathOnly { - base := "." - if len(basepaths) > 0 { - base = filepath.Dir(filepath.Join(basepaths...)) - } - p, e := filepath.Abs(filepath.ToSlash(filepath.Join(base, pth))) - if e != nil { - return false - } - pth = p - } - - fi, err := os.Stat(filepath.ToSlash(pth)) - if err != nil { - return false - } - - return !fi.IsDir() -} - -// Inherits creates a new reference from a parent and a child -// If the child cannot inherit from the parent, an error is returned -func (r *Ref) Inherits(child Ref) (*Ref, error) { - ref, err := r.Ref.Inherits(child.Ref) - if err != nil { - return nil, err - } - return &Ref{Ref: *ref}, nil -} - -// NewRef creates a new instance of a ref object -// returns an error when the reference uri is an invalid uri -func NewRef(refURI string) (Ref, error) { - ref, err := jsonreference.New(refURI) - if err != nil { - return Ref{}, err - } - return Ref{Ref: ref}, nil -} - -// MustCreateRef creates a ref object but panics when refURI is invalid. -// Use the NewRef method for a version that returns an error. -func MustCreateRef(refURI string) Ref { - return Ref{Ref: jsonreference.MustCreateRef(refURI)} -} - -// MarshalJSON marshals this ref into a JSON object -func (r Ref) MarshalJSON() ([]byte, error) { - str := r.String() - if str == "" { - if r.IsRoot() { - return []byte(`{"$ref":""}`), nil - } - return []byte("{}"), nil - } - v := map[string]interface{}{"$ref": str} - return json.Marshal(v) -} - -// UnmarshalJSON unmarshals this ref from a JSON object -func (r *Ref) UnmarshalJSON(d []byte) error { - var v map[string]interface{} - if err := json.Unmarshal(d, &v); err != nil { - return err - } - return r.fromMap(v) -} - -func (r *Ref) fromMap(v map[string]interface{}) error { - if v == nil { - return nil - } - - if vv, ok := v["$ref"]; ok { - if str, ok := vv.(string); ok { - ref, err := jsonreference.New(str) - if err != nil { - return err - } - *r = Ref{Ref: ref} - } - } - - return nil -} diff --git a/vendor/github.com/go-openapi/spec/response.go b/vendor/github.com/go-openapi/spec/response.go deleted file mode 100644 index a32b039ea..000000000 --- a/vendor/github.com/go-openapi/spec/response.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -// ResponseProps properties specific to a response -type ResponseProps struct { - Description string `json:"description,omitempty"` - Schema *Schema `json:"schema,omitempty"` - Headers map[string]Header `json:"headers,omitempty"` - Examples map[string]interface{} `json:"examples,omitempty"` -} - -// Response describes a single response from an API Operation. -// -// For more information: http://goo.gl/8us55a#responseObject -type Response struct { - Refable - ResponseProps - VendorExtensible -} - -// JSONLookup look up a value by the json property name -func (p Response) JSONLookup(token string) (interface{}, error) { - if ex, ok := p.Extensions[token]; ok { - return &ex, nil - } - if token == "$ref" { - return &p.Ref, nil - } - r, _, err := jsonpointer.GetForToken(p.ResponseProps, token) - return r, err -} - -// UnmarshalJSON hydrates this items instance with the data from JSON -func (r *Response) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &r.ResponseProps); err != nil { - return err - } - if err := json.Unmarshal(data, &r.Refable); err != nil { - return err - } - if err := json.Unmarshal(data, &r.VendorExtensible); err != nil { - return err - } - return nil -} - -// MarshalJSON converts this items object to JSON -func (r Response) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(r.ResponseProps) - if err != nil { - return nil, err - } - b2, err := json.Marshal(r.Refable) - if err != nil { - return nil, err - } - b3, err := json.Marshal(r.VendorExtensible) - if err != nil { - return nil, err - } - return swag.ConcatJSON(b1, b2, b3), nil -} - -// NewResponse creates a new response instance -func NewResponse() *Response { - return new(Response) -} - -// ResponseRef creates a response as a json reference -func ResponseRef(url string) *Response { - resp := NewResponse() - resp.Ref = MustCreateRef(url) - return resp -} - -// WithDescription sets the description on this response, allows for chaining -func (r *Response) WithDescription(description string) *Response { - r.Description = description - return r -} - -// WithSchema sets the schema on this response, allows for chaining. -// Passing a nil argument removes the schema from this response -func (r *Response) WithSchema(schema *Schema) *Response { - r.Schema = schema - return r -} - -// AddHeader adds a header to this response -func (r *Response) AddHeader(name string, header *Header) *Response { - if header == nil { - return r.RemoveHeader(name) - } - if r.Headers == nil { - r.Headers = make(map[string]Header) - } - r.Headers[name] = *header - return r -} - -// RemoveHeader removes a header from this response -func (r *Response) RemoveHeader(name string) *Response { - delete(r.Headers, name) - return r -} - -// AddExample adds an example to this response -func (r *Response) AddExample(mediaType string, example interface{}) *Response { - if r.Examples == nil { - r.Examples = make(map[string]interface{}) - } - r.Examples[mediaType] = example - return r -} diff --git a/vendor/github.com/go-openapi/spec/response_test.go b/vendor/github.com/go-openapi/spec/response_test.go deleted file mode 100644 index 2a3ca4093..000000000 --- a/vendor/github.com/go-openapi/spec/response_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// 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 ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var response = Response{ - Refable: Refable{Ref: MustCreateRef("Dog")}, - VendorExtensible: VendorExtensible{ - Extensions: map[string]interface{}{ - "x-go-name": "PutDogExists", - }, - }, - ResponseProps: ResponseProps{ - Description: "Dog exists", - Schema: &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - }, -} - -var responseJSON = `{ - "$ref": "Dog", - "x-go-name": "PutDogExists", - "description": "Dog exists", - "schema": { - "type": "string" - } -}` - -func TestIntegrationResponse(t *testing.T) { - var actual Response - if assert.NoError(t, json.Unmarshal([]byte(responseJSON), &actual)) { - assert.EqualValues(t, actual, response) - } - - assertParsesJSON(t, responseJSON, response) -} diff --git a/vendor/github.com/go-openapi/spec/responses.go b/vendor/github.com/go-openapi/spec/responses.go deleted file mode 100644 index 3ab06697f..000000000 --- a/vendor/github.com/go-openapi/spec/responses.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "fmt" - "reflect" - "strconv" - - "github.com/go-openapi/swag" -) - -// Responses is a container for the expected responses of an operation. -// The container maps a HTTP response code to the expected response. -// It is not expected from the documentation to necessarily cover all possible HTTP response codes, -// since they may not be known in advance. However, it is expected from the documentation to cover -// a successful operation response and any known errors. -// -// The `default` can be used a default response object for all HTTP codes that are not covered -// individually by the specification. -// -// The `Responses Object` MUST contain at least one response code, and it SHOULD be the response -// for a successful operation call. -// -// For more information: http://goo.gl/8us55a#responsesObject -type Responses struct { - VendorExtensible - ResponsesProps -} - -// JSONLookup implements an interface to customize json pointer lookup -func (r Responses) JSONLookup(token string) (interface{}, error) { - if token == "default" { - return r.Default, nil - } - if ex, ok := r.Extensions[token]; ok { - return &ex, nil - } - if i, err := strconv.Atoi(token); err == nil { - if scr, ok := r.StatusCodeResponses[i]; ok { - return scr, nil - } - } - return nil, fmt.Errorf("object has no field %q", token) -} - -// UnmarshalJSON hydrates this items instance with the data from JSON -func (r *Responses) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &r.ResponsesProps); err != nil { - return err - } - if err := json.Unmarshal(data, &r.VendorExtensible); err != nil { - return err - } - if reflect.DeepEqual(ResponsesProps{}, r.ResponsesProps) { - r.ResponsesProps = ResponsesProps{} - } - return nil -} - -// MarshalJSON converts this items object to JSON -func (r Responses) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(r.ResponsesProps) - if err != nil { - return nil, err - } - b2, err := json.Marshal(r.VendorExtensible) - if err != nil { - return nil, err - } - concated := swag.ConcatJSON(b1, b2) - return concated, nil -} - -type ResponsesProps struct { - Default *Response - StatusCodeResponses map[int]Response -} - -func (r ResponsesProps) MarshalJSON() ([]byte, error) { - toser := map[string]Response{} - if r.Default != nil { - toser["default"] = *r.Default - } - for k, v := range r.StatusCodeResponses { - toser[strconv.Itoa(k)] = v - } - return json.Marshal(toser) -} - -func (r *ResponsesProps) UnmarshalJSON(data []byte) error { - var res map[string]Response - if err := json.Unmarshal(data, &res); err != nil { - return nil - } - if v, ok := res["default"]; ok { - r.Default = &v - delete(res, "default") - } - for k, v := range res { - if nk, err := strconv.Atoi(k); err == nil { - if r.StatusCodeResponses == nil { - r.StatusCodeResponses = map[int]Response{} - } - r.StatusCodeResponses[nk] = v - } - } - return nil -} diff --git a/vendor/github.com/go-openapi/spec/schema.go b/vendor/github.com/go-openapi/spec/schema.go deleted file mode 100644 index 05c1a4aa0..000000000 --- a/vendor/github.com/go-openapi/spec/schema.go +++ /dev/null @@ -1,634 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "fmt" - "net/url" - "strings" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -// BooleanProperty creates a boolean property -func BooleanProperty() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"boolean"}}} -} - -// BoolProperty creates a boolean property -func BoolProperty() *Schema { return BooleanProperty() } - -// StringProperty creates a string property -func StringProperty() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} -} - -// CharProperty creates a string property -func CharProperty() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} -} - -// Float64Property creates a float64/double property -func Float64Property() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "double"}} -} - -// Float32Property creates a float32/float property -func Float32Property() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "float"}} -} - -// Int8Property creates an int8 property -func Int8Property() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int8"}} -} - -// Int16Property creates an int16 property -func Int16Property() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int16"}} -} - -// Int32Property creates an int32 property -func Int32Property() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int32"}} -} - -// Int64Property creates an int64 property -func Int64Property() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int64"}} -} - -// StrFmtProperty creates a property for the named string format -func StrFmtProperty(format string) *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: format}} -} - -// DateProperty creates a date property -func DateProperty() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date"}} -} - -// DateTimeProperty creates a date time property -func DateTimeProperty() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date-time"}} -} - -// MapProperty creates a map property -func MapProperty(property *Schema) *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"object"}, AdditionalProperties: &SchemaOrBool{Allows: true, Schema: property}}} -} - -// RefProperty creates a ref property -func RefProperty(name string) *Schema { - return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} -} - -// RefSchema creates a ref property -func RefSchema(name string) *Schema { - return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} -} - -// ArrayProperty creates an array property -func ArrayProperty(items *Schema) *Schema { - if items == nil { - return &Schema{SchemaProps: SchemaProps{Type: []string{"array"}}} - } - return &Schema{SchemaProps: SchemaProps{Items: &SchemaOrArray{Schema: items}, Type: []string{"array"}}} -} - -// ComposedSchema creates a schema with allOf -func ComposedSchema(schemas ...Schema) *Schema { - s := new(Schema) - s.AllOf = schemas - return s -} - -// SchemaURL represents a schema url -type SchemaURL string - -// MarshalJSON marshal this to JSON -func (r SchemaURL) MarshalJSON() ([]byte, error) { - if r == "" { - return []byte("{}"), nil - } - v := map[string]interface{}{"$schema": string(r)} - return json.Marshal(v) -} - -// UnmarshalJSON unmarshal this from JSON -func (r *SchemaURL) UnmarshalJSON(data []byte) error { - var v map[string]interface{} - if err := json.Unmarshal(data, &v); err != nil { - return err - } - return r.fromMap(v) -} - -func (r *SchemaURL) fromMap(v map[string]interface{}) error { - if v == nil { - return nil - } - if vv, ok := v["$schema"]; ok { - if str, ok := vv.(string); ok { - u, err := url.Parse(str) - if err != nil { - return err - } - - *r = SchemaURL(u.String()) - } - } - return nil -} - -// type ExtraSchemaProps map[string]interface{} - -// // JSONSchema represents a structure that is a json schema draft 04 -// type JSONSchema struct { -// SchemaProps -// ExtraSchemaProps -// } - -// // MarshalJSON marshal this to JSON -// func (s JSONSchema) MarshalJSON() ([]byte, error) { -// b1, err := json.Marshal(s.SchemaProps) -// if err != nil { -// return nil, err -// } -// b2, err := s.Ref.MarshalJSON() -// if err != nil { -// return nil, err -// } -// b3, err := s.Schema.MarshalJSON() -// if err != nil { -// return nil, err -// } -// b4, err := json.Marshal(s.ExtraSchemaProps) -// if err != nil { -// return nil, err -// } -// return swag.ConcatJSON(b1, b2, b3, b4), nil -// } - -// // UnmarshalJSON marshal this from JSON -// func (s *JSONSchema) UnmarshalJSON(data []byte) error { -// var sch JSONSchema -// if err := json.Unmarshal(data, &sch.SchemaProps); err != nil { -// return err -// } -// if err := json.Unmarshal(data, &sch.Ref); err != nil { -// return err -// } -// if err := json.Unmarshal(data, &sch.Schema); err != nil { -// return err -// } -// if err := json.Unmarshal(data, &sch.ExtraSchemaProps); err != nil { -// return err -// } -// *s = sch -// return nil -// } - -type SchemaProps struct { - ID string `json:"id,omitempty"` - Ref Ref `json:"-"` - Schema SchemaURL `json:"-"` - Description string `json:"description,omitempty"` - Type StringOrArray `json:"type,omitempty"` - Format string `json:"format,omitempty"` - Title string `json:"title,omitempty"` - Default interface{} `json:"default,omitempty"` - Maximum *float64 `json:"maximum,omitempty"` - ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` - Minimum *float64 `json:"minimum,omitempty"` - ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` - MaxLength *int64 `json:"maxLength,omitempty"` - MinLength *int64 `json:"minLength,omitempty"` - Pattern string `json:"pattern,omitempty"` - MaxItems *int64 `json:"maxItems,omitempty"` - MinItems *int64 `json:"minItems,omitempty"` - UniqueItems bool `json:"uniqueItems,omitempty"` - MultipleOf *float64 `json:"multipleOf,omitempty"` - Enum []interface{} `json:"enum,omitempty"` - MaxProperties *int64 `json:"maxProperties,omitempty"` - MinProperties *int64 `json:"minProperties,omitempty"` - Required []string `json:"required,omitempty"` - Items *SchemaOrArray `json:"items,omitempty"` - AllOf []Schema `json:"allOf,omitempty"` - OneOf []Schema `json:"oneOf,omitempty"` - AnyOf []Schema `json:"anyOf,omitempty"` - Not *Schema `json:"not,omitempty"` - Properties map[string]Schema `json:"properties,omitempty"` - AdditionalProperties *SchemaOrBool `json:"additionalProperties,omitempty"` - PatternProperties map[string]Schema `json:"patternProperties,omitempty"` - Dependencies Dependencies `json:"dependencies,omitempty"` - AdditionalItems *SchemaOrBool `json:"additionalItems,omitempty"` - Definitions Definitions `json:"definitions,omitempty"` -} - -type SwaggerSchemaProps struct { - Discriminator string `json:"discriminator,omitempty"` - ReadOnly bool `json:"readOnly,omitempty"` - XML *XMLObject `json:"xml,omitempty"` - ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` - Example interface{} `json:"example,omitempty"` -} - -// Schema the schema object allows the definition of input and output data types. -// These types can be objects, but also primitives and arrays. -// This object is based on the [JSON Schema Specification Draft 4](http://json-schema.org/) -// and uses a predefined subset of it. -// On top of this subset, there are extensions provided by this specification to allow for more complete documentation. -// -// For more information: http://goo.gl/8us55a#schemaObject -type Schema struct { - VendorExtensible - SchemaProps - SwaggerSchemaProps - ExtraProps map[string]interface{} `json:"-"` -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s Schema) JSONLookup(token string) (interface{}, error) { - if ex, ok := s.Extensions[token]; ok { - return &ex, nil - } - - if ex, ok := s.ExtraProps[token]; ok { - return &ex, nil - } - - r, _, err := jsonpointer.GetForToken(s.SchemaProps, token) - if r != nil || (err != nil && !strings.HasPrefix(err.Error(), "object has no field")) { - return r, err - } - r, _, err = jsonpointer.GetForToken(s.SwaggerSchemaProps, token) - return r, err -} - -// WithID sets the id for this schema, allows for chaining -func (s *Schema) WithID(id string) *Schema { - s.ID = id - return s -} - -// WithTitle sets the title for this schema, allows for chaining -func (s *Schema) WithTitle(title string) *Schema { - s.Title = title - return s -} - -// WithDescription sets the description for this schema, allows for chaining -func (s *Schema) WithDescription(description string) *Schema { - s.Description = description - return s -} - -// WithProperties sets the properties for this schema -func (s *Schema) WithProperties(schemas map[string]Schema) *Schema { - s.Properties = schemas - return s -} - -// SetProperty sets a property on this schema -func (s *Schema) SetProperty(name string, schema Schema) *Schema { - if s.Properties == nil { - s.Properties = make(map[string]Schema) - } - s.Properties[name] = schema - return s -} - -// WithAllOf sets the all of property -func (s *Schema) WithAllOf(schemas ...Schema) *Schema { - s.AllOf = schemas - return s -} - -// WithMaxProperties sets the max number of properties an object can have -func (s *Schema) WithMaxProperties(max int64) *Schema { - s.MaxProperties = &max - return s -} - -// WithMinProperties sets the min number of properties an object must have -func (s *Schema) WithMinProperties(min int64) *Schema { - s.MinProperties = &min - return s -} - -// Typed sets the type of this schema for a single value item -func (s *Schema) Typed(tpe, format string) *Schema { - s.Type = []string{tpe} - s.Format = format - return s -} - -// AddType adds a type with potential format to the types for this schema -func (s *Schema) AddType(tpe, format string) *Schema { - s.Type = append(s.Type, tpe) - if format != "" { - s.Format = format - } - return s -} - -// CollectionOf a fluent builder method for an array parameter -func (s *Schema) CollectionOf(items Schema) *Schema { - s.Type = []string{"array"} - s.Items = &SchemaOrArray{Schema: &items} - return s -} - -// WithDefault sets the default value on this parameter -func (s *Schema) WithDefault(defaultValue interface{}) *Schema { - s.Default = defaultValue - return s -} - -// WithRequired flags this parameter as required -func (s *Schema) WithRequired(items ...string) *Schema { - s.Required = items - return s -} - -// AddRequired adds field names to the required properties array -func (s *Schema) AddRequired(items ...string) *Schema { - s.Required = append(s.Required, items...) - return s -} - -// WithMaxLength sets a max length value -func (s *Schema) WithMaxLength(max int64) *Schema { - s.MaxLength = &max - return s -} - -// WithMinLength sets a min length value -func (s *Schema) WithMinLength(min int64) *Schema { - s.MinLength = &min - return s -} - -// WithPattern sets a pattern value -func (s *Schema) WithPattern(pattern string) *Schema { - s.Pattern = pattern - return s -} - -// WithMultipleOf sets a multiple of value -func (s *Schema) WithMultipleOf(number float64) *Schema { - s.MultipleOf = &number - return s -} - -// WithMaximum sets a maximum number value -func (s *Schema) WithMaximum(max float64, exclusive bool) *Schema { - s.Maximum = &max - s.ExclusiveMaximum = exclusive - return s -} - -// WithMinimum sets a minimum number value -func (s *Schema) WithMinimum(min float64, exclusive bool) *Schema { - s.Minimum = &min - s.ExclusiveMinimum = exclusive - return s -} - -// WithEnum sets a the enum values (replace) -func (s *Schema) WithEnum(values ...interface{}) *Schema { - s.Enum = append([]interface{}{}, values...) - return s -} - -// WithMaxItems sets the max items -func (s *Schema) WithMaxItems(size int64) *Schema { - s.MaxItems = &size - return s -} - -// WithMinItems sets the min items -func (s *Schema) WithMinItems(size int64) *Schema { - s.MinItems = &size - return s -} - -// UniqueValues dictates that this array can only have unique items -func (s *Schema) UniqueValues() *Schema { - s.UniqueItems = true - return s -} - -// AllowDuplicates this array can have duplicates -func (s *Schema) AllowDuplicates() *Schema { - s.UniqueItems = false - return s -} - -// AddToAllOf adds a schema to the allOf property -func (s *Schema) AddToAllOf(schemas ...Schema) *Schema { - s.AllOf = append(s.AllOf, schemas...) - return s -} - -// WithDiscriminator sets the name of the discriminator field -func (s *Schema) WithDiscriminator(discriminator string) *Schema { - s.Discriminator = discriminator - return s -} - -// AsReadOnly flags this schema as readonly -func (s *Schema) AsReadOnly() *Schema { - s.ReadOnly = true - return s -} - -// AsWritable flags this schema as writeable (not read-only) -func (s *Schema) AsWritable() *Schema { - s.ReadOnly = false - return s -} - -// WithExample sets the example for this schema -func (s *Schema) WithExample(example interface{}) *Schema { - s.Example = example - return s -} - -// WithExternalDocs sets/removes the external docs for/from this schema. -// When you pass empty strings as params the external documents will be removed. -// When you pass non-empty string as one value then those values will be used on the external docs object. -// So when you pass a non-empty description, you should also pass the url and vice versa. -func (s *Schema) WithExternalDocs(description, url string) *Schema { - if description == "" && url == "" { - s.ExternalDocs = nil - return s - } - - if s.ExternalDocs == nil { - s.ExternalDocs = &ExternalDocumentation{} - } - s.ExternalDocs.Description = description - s.ExternalDocs.URL = url - return s -} - -// WithXMLName sets the xml name for the object -func (s *Schema) WithXMLName(name string) *Schema { - if s.XML == nil { - s.XML = new(XMLObject) - } - s.XML.Name = name - return s -} - -// WithXMLNamespace sets the xml namespace for the object -func (s *Schema) WithXMLNamespace(namespace string) *Schema { - if s.XML == nil { - s.XML = new(XMLObject) - } - s.XML.Namespace = namespace - return s -} - -// WithXMLPrefix sets the xml prefix for the object -func (s *Schema) WithXMLPrefix(prefix string) *Schema { - if s.XML == nil { - s.XML = new(XMLObject) - } - s.XML.Prefix = prefix - return s -} - -// AsXMLAttribute flags this object as xml attribute -func (s *Schema) AsXMLAttribute() *Schema { - if s.XML == nil { - s.XML = new(XMLObject) - } - s.XML.Attribute = true - return s -} - -// AsXMLElement flags this object as an xml node -func (s *Schema) AsXMLElement() *Schema { - if s.XML == nil { - s.XML = new(XMLObject) - } - s.XML.Attribute = false - return s -} - -// AsWrappedXML flags this object as wrapped, this is mostly useful for array types -func (s *Schema) AsWrappedXML() *Schema { - if s.XML == nil { - s.XML = new(XMLObject) - } - s.XML.Wrapped = true - return s -} - -// AsUnwrappedXML flags this object as an xml node -func (s *Schema) AsUnwrappedXML() *Schema { - if s.XML == nil { - s.XML = new(XMLObject) - } - s.XML.Wrapped = false - return s -} - -// MarshalJSON marshal this to JSON -func (s Schema) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(s.SchemaProps) - if err != nil { - return nil, fmt.Errorf("schema props %v", err) - } - b2, err := json.Marshal(s.VendorExtensible) - if err != nil { - return nil, fmt.Errorf("vendor props %v", err) - } - b3, err := s.Ref.MarshalJSON() - if err != nil { - return nil, fmt.Errorf("ref prop %v", err) - } - b4, err := s.Schema.MarshalJSON() - if err != nil { - return nil, fmt.Errorf("schema prop %v", err) - } - b5, err := json.Marshal(s.SwaggerSchemaProps) - if err != nil { - return nil, fmt.Errorf("common validations %v", err) - } - var b6 []byte - if s.ExtraProps != nil { - jj, err := json.Marshal(s.ExtraProps) - if err != nil { - return nil, fmt.Errorf("extra props %v", err) - } - b6 = jj - } - return swag.ConcatJSON(b1, b2, b3, b4, b5, b6), nil -} - -// UnmarshalJSON marshal this from JSON -func (s *Schema) UnmarshalJSON(data []byte) error { - props := struct { - SchemaProps - SwaggerSchemaProps - }{} - if err := json.Unmarshal(data, &props); err != nil { - return err - } - - sch := Schema{ - SchemaProps: props.SchemaProps, - SwaggerSchemaProps: props.SwaggerSchemaProps, - } - - var d map[string]interface{} - if err := json.Unmarshal(data, &d); err != nil { - return err - } - - sch.Ref.fromMap(d) - sch.Schema.fromMap(d) - - delete(d, "$ref") - delete(d, "$schema") - for _, pn := range swag.DefaultJSONNameProvider.GetJSONNames(s) { - delete(d, pn) - } - - for k, vv := range d { - lk := strings.ToLower(k) - if strings.HasPrefix(lk, "x-") { - if sch.Extensions == nil { - sch.Extensions = map[string]interface{}{} - } - sch.Extensions[k] = vv - continue - } - if sch.ExtraProps == nil { - sch.ExtraProps = map[string]interface{}{} - } - sch.ExtraProps[k] = vv - } - - *s = sch - - return nil -} diff --git a/vendor/github.com/go-openapi/spec/schema_test.go b/vendor/github.com/go-openapi/spec/schema_test.go deleted file mode 100644 index 6995fbb48..000000000 --- a/vendor/github.com/go-openapi/spec/schema_test.go +++ /dev/null @@ -1,212 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -var schema = Schema{ - VendorExtensible: VendorExtensible{Extensions: map[string]interface{}{"x-framework": "go-swagger"}}, - SchemaProps: SchemaProps{ - Ref: MustCreateRef("Cat"), - Type: []string{"string"}, - Format: "date", - Description: "the description of this schema", - Title: "the title", - Default: "blah", - Maximum: float64Ptr(100), - ExclusiveMaximum: true, - ExclusiveMinimum: true, - Minimum: float64Ptr(5), - MaxLength: int64Ptr(100), - MinLength: int64Ptr(5), - Pattern: "\\w{1,5}\\w+", - MaxItems: int64Ptr(100), - MinItems: int64Ptr(5), - UniqueItems: true, - MultipleOf: float64Ptr(5), - Enum: []interface{}{"hello", "world"}, - MaxProperties: int64Ptr(5), - MinProperties: int64Ptr(1), - Required: []string{"id", "name"}, - Items: &SchemaOrArray{Schema: &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}}, - AllOf: []Schema{Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}}, - Properties: map[string]Schema{ - "id": Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int64"}}, - "name": Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - }, - AdditionalProperties: &SchemaOrBool{Allows: true, Schema: &Schema{SchemaProps: SchemaProps{ - Type: []string{"integer"}, - Format: "int32", - }}}, - }, - SwaggerSchemaProps: SwaggerSchemaProps{ - Discriminator: "not this", - ReadOnly: true, - XML: &XMLObject{"sch", "io", "sw", true, true}, - ExternalDocs: &ExternalDocumentation{ - Description: "the documentation etc", - URL: "http://readthedocs.org/swagger", - }, - Example: []interface{}{ - map[string]interface{}{ - "id": 1, - "name": "a book", - }, - map[string]interface{}{ - "id": 2, - "name": "the thing", - }, - }, - }, -} - -var schemaJSON = `{ - "x-framework": "go-swagger", - "$ref": "Cat", - "description": "the description of this schema", - "maximum": 100, - "minimum": 5, - "exclusiveMaximum": true, - "exclusiveMinimum": true, - "maxLength": 100, - "minLength": 5, - "pattern": "\\w{1,5}\\w+", - "maxItems": 100, - "minItems": 5, - "uniqueItems": true, - "multipleOf": 5, - "enum": ["hello", "world"], - "type": "string", - "format": "date", - "title": "the title", - "default": "blah", - "maxProperties": 5, - "minProperties": 1, - "required": ["id", "name"], - "items": { - "type": "string" - }, - "allOf": [ - { - "type": "string" - } - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - }, - "discriminator": "not this", - "readOnly": true, - "xml": { - "name": "sch", - "namespace": "io", - "prefix": "sw", - "wrapped": true, - "attribute": true - }, - "externalDocs": { - "description": "the documentation etc", - "url": "http://readthedocs.org/swagger" - }, - "example": [ - { - "id": 1, - "name": "a book" - }, - { - "id": 2, - "name": "the thing" - } - ], - "additionalProperties": { - "type": "integer", - "format": "int32" - } -} -` - -func TestSchema(t *testing.T) { - - expected := map[string]interface{}{} - json.Unmarshal([]byte(schemaJSON), &expected) - b, err := json.Marshal(schema) - if assert.NoError(t, err) { - var actual map[string]interface{} - json.Unmarshal(b, &actual) - assert.Equal(t, expected, actual) - } - - actual2 := Schema{} - if assert.NoError(t, json.Unmarshal([]byte(schemaJSON), &actual2)) { - assert.Equal(t, schema.Ref, actual2.Ref) - assert.Equal(t, schema.Description, actual2.Description) - assert.Equal(t, schema.Maximum, actual2.Maximum) - assert.Equal(t, schema.Minimum, actual2.Minimum) - assert.Equal(t, schema.ExclusiveMinimum, actual2.ExclusiveMinimum) - assert.Equal(t, schema.ExclusiveMaximum, actual2.ExclusiveMaximum) - assert.Equal(t, schema.MaxLength, actual2.MaxLength) - assert.Equal(t, schema.MinLength, actual2.MinLength) - assert.Equal(t, schema.Pattern, actual2.Pattern) - assert.Equal(t, schema.MaxItems, actual2.MaxItems) - assert.Equal(t, schema.MinItems, actual2.MinItems) - assert.True(t, actual2.UniqueItems) - assert.Equal(t, schema.MultipleOf, actual2.MultipleOf) - assert.Equal(t, schema.Enum, actual2.Enum) - assert.Equal(t, schema.Type, actual2.Type) - assert.Equal(t, schema.Format, actual2.Format) - assert.Equal(t, schema.Title, actual2.Title) - assert.Equal(t, schema.MaxProperties, actual2.MaxProperties) - assert.Equal(t, schema.MinProperties, actual2.MinProperties) - assert.Equal(t, schema.Required, actual2.Required) - assert.Equal(t, schema.Items, actual2.Items) - assert.Equal(t, schema.AllOf, actual2.AllOf) - assert.Equal(t, schema.Properties, actual2.Properties) - assert.Equal(t, schema.Discriminator, actual2.Discriminator) - assert.Equal(t, schema.ReadOnly, actual2.ReadOnly) - assert.Equal(t, schema.XML, actual2.XML) - assert.Equal(t, schema.ExternalDocs, actual2.ExternalDocs) - assert.Equal(t, schema.AdditionalProperties, actual2.AdditionalProperties) - assert.Equal(t, schema.Extensions, actual2.Extensions) - examples := actual2.Example.([]interface{}) - expEx := schema.Example.([]interface{}) - ex1 := examples[0].(map[string]interface{}) - ex2 := examples[1].(map[string]interface{}) - exp1 := expEx[0].(map[string]interface{}) - exp2 := expEx[1].(map[string]interface{}) - - assert.EqualValues(t, exp1["id"], ex1["id"]) - assert.Equal(t, exp1["name"], ex1["name"]) - assert.EqualValues(t, exp2["id"], ex2["id"]) - assert.Equal(t, exp2["name"], ex2["name"]) - } - -} - -func BenchmarkSchemaUnmarshal(b *testing.B) { - for i := 0; i < b.N; i++ { - sch := &Schema{} - sch.UnmarshalJSON([]byte(schemaJSON)) - } -} diff --git a/vendor/github.com/go-openapi/spec/schemas/jsonschema-draft-04.json b/vendor/github.com/go-openapi/spec/schemas/jsonschema-draft-04.json deleted file mode 100644 index 85eb502a6..000000000 --- a/vendor/github.com/go-openapi/spec/schemas/jsonschema-draft-04.json +++ /dev/null @@ -1,150 +0,0 @@ -{ - "id": "http://json-schema.org/draft-04/schema#", - "$schema": "http://json-schema.org/draft-04/schema#", - "description": "Core schema meta-schema", - "definitions": { - "schemaArray": { - "type": "array", - "minItems": 1, - "items": { "$ref": "#" } - }, - "positiveInteger": { - "type": "integer", - "minimum": 0 - }, - "positiveIntegerDefault0": { - "allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ] - }, - "simpleTypes": { - "enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ] - }, - "stringArray": { - "type": "array", - "items": { "type": "string" }, - "minItems": 1, - "uniqueItems": true - } - }, - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uri" - }, - "$schema": { - "type": "string", - "format": "uri" - }, - "title": { - "type": "string" - }, - "description": { - "type": "string" - }, - "default": {}, - "multipleOf": { - "type": "number", - "minimum": 0, - "exclusiveMinimum": true - }, - "maximum": { - "type": "number" - }, - "exclusiveMaximum": { - "type": "boolean", - "default": false - }, - "minimum": { - "type": "number" - }, - "exclusiveMinimum": { - "type": "boolean", - "default": false - }, - "maxLength": { "$ref": "#/definitions/positiveInteger" }, - "minLength": { "$ref": "#/definitions/positiveIntegerDefault0" }, - "pattern": { - "type": "string", - "format": "regex" - }, - "additionalItems": { - "anyOf": [ - { "type": "boolean" }, - { "$ref": "#" } - ], - "default": {} - }, - "items": { - "anyOf": [ - { "$ref": "#" }, - { "$ref": "#/definitions/schemaArray" } - ], - "default": {} - }, - "maxItems": { "$ref": "#/definitions/positiveInteger" }, - "minItems": { "$ref": "#/definitions/positiveIntegerDefault0" }, - "uniqueItems": { - "type": "boolean", - "default": false - }, - "maxProperties": { "$ref": "#/definitions/positiveInteger" }, - "minProperties": { "$ref": "#/definitions/positiveIntegerDefault0" }, - "required": { "$ref": "#/definitions/stringArray" }, - "additionalProperties": { - "anyOf": [ - { "type": "boolean" }, - { "$ref": "#" } - ], - "default": {} - }, - "definitions": { - "type": "object", - "additionalProperties": { "$ref": "#" }, - "default": {} - }, - "properties": { - "type": "object", - "additionalProperties": { "$ref": "#" }, - "default": {} - }, - "patternProperties": { - "type": "object", - "additionalProperties": { "$ref": "#" }, - "default": {} - }, - "dependencies": { - "type": "object", - "additionalProperties": { - "anyOf": [ - { "$ref": "#" }, - { "$ref": "#/definitions/stringArray" } - ] - } - }, - "enum": { - "type": "array", - "minItems": 1, - "uniqueItems": true - }, - "type": { - "anyOf": [ - { "$ref": "#/definitions/simpleTypes" }, - { - "type": "array", - "items": { "$ref": "#/definitions/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - } - ] - }, - "allOf": { "$ref": "#/definitions/schemaArray" }, - "anyOf": { "$ref": "#/definitions/schemaArray" }, - "oneOf": { "$ref": "#/definitions/schemaArray" }, - "not": { "$ref": "#" } - }, - "dependencies": { - "exclusiveMaximum": [ "maximum" ], - "exclusiveMinimum": [ "minimum" ] - }, - "default": {} -} diff --git a/vendor/github.com/go-openapi/spec/schemas/v2/README.md b/vendor/github.com/go-openapi/spec/schemas/v2/README.md deleted file mode 100644 index 32c1b929b..000000000 --- a/vendor/github.com/go-openapi/spec/schemas/v2/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Swagger 2.0 specification schema - -This folder contains the Swagger 2.0 specification schema files maintained here: - -https://github.com/reverb/swagger-spec/blob/master/schemas/v2.0 \ No newline at end of file diff --git a/vendor/github.com/go-openapi/spec/schemas/v2/schema.json b/vendor/github.com/go-openapi/spec/schemas/v2/schema.json deleted file mode 100644 index 4dfccd07b..000000000 --- a/vendor/github.com/go-openapi/spec/schemas/v2/schema.json +++ /dev/null @@ -1,1607 +0,0 @@ -{ - "title": "A JSON Schema for Swagger 2.0 API.", - "id": "http://swagger.io/v2/schema.json#", - "$schema": "http://json-schema.org/draft-04/schema#", - "type": "object", - "required": [ - "swagger", - "info", - "paths" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - }, - "properties": { - "swagger": { - "type": "string", - "enum": [ - "2.0" - ], - "description": "The Swagger version of this document." - }, - "info": { - "$ref": "#/definitions/info" - }, - "host": { - "type": "string", - "pattern": "^[^{}/ :\\\\]+(?::\\d+)?$", - "description": "The host (name or ip) of the API. Example: 'swagger.io'" - }, - "basePath": { - "type": "string", - "pattern": "^/", - "description": "The base path to the API. Example: '/api'." - }, - "schemes": { - "$ref": "#/definitions/schemesList" - }, - "consumes": { - "description": "A list of MIME types accepted by the API.", - "allOf": [ - { - "$ref": "#/definitions/mediaTypeList" - } - ] - }, - "produces": { - "description": "A list of MIME types the API can produce.", - "allOf": [ - { - "$ref": "#/definitions/mediaTypeList" - } - ] - }, - "paths": { - "$ref": "#/definitions/paths" - }, - "definitions": { - "$ref": "#/definitions/definitions" - }, - "parameters": { - "$ref": "#/definitions/parameterDefinitions" - }, - "responses": { - "$ref": "#/definitions/responseDefinitions" - }, - "security": { - "$ref": "#/definitions/security" - }, - "securityDefinitions": { - "$ref": "#/definitions/securityDefinitions" - }, - "tags": { - "type": "array", - "items": { - "$ref": "#/definitions/tag" - }, - "uniqueItems": true - }, - "externalDocs": { - "$ref": "#/definitions/externalDocs" - } - }, - "definitions": { - "info": { - "type": "object", - "description": "General information about the API.", - "required": [ - "version", - "title" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - }, - "properties": { - "title": { - "type": "string", - "description": "A unique and precise title of the API." - }, - "version": { - "type": "string", - "description": "A semantic version number of the API." - }, - "description": { - "type": "string", - "description": "A longer description of the API. Should be different from the title. GitHub Flavored Markdown is allowed." - }, - "termsOfService": { - "type": "string", - "description": "The terms of service for the API." - }, - "contact": { - "$ref": "#/definitions/contact" - }, - "license": { - "$ref": "#/definitions/license" - } - } - }, - "contact": { - "type": "object", - "description": "Contact information for the owners of the API.", - "additionalProperties": false, - "properties": { - "name": { - "type": "string", - "description": "The identifying name of the contact person/organization." - }, - "url": { - "type": "string", - "description": "The URL pointing to the contact information.", - "format": "uri" - }, - "email": { - "type": "string", - "description": "The email address of the contact person/organization.", - "format": "email" - } - }, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "license": { - "type": "object", - "required": [ - "name" - ], - "additionalProperties": false, - "properties": { - "name": { - "type": "string", - "description": "The name of the license type. It's encouraged to use an OSI compatible license." - }, - "url": { - "type": "string", - "description": "The URL pointing to the license.", - "format": "uri" - } - }, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "paths": { - "type": "object", - "description": "Relative paths to the individual endpoints. They must be relative to the 'basePath'.", - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - }, - "^/": { - "$ref": "#/definitions/pathItem" - } - }, - "additionalProperties": false - }, - "definitions": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/schema" - }, - "description": "One or more JSON objects describing the schemas being consumed and produced by the API." - }, - "parameterDefinitions": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/parameter" - }, - "description": "One or more JSON representations for parameters" - }, - "responseDefinitions": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/response" - }, - "description": "One or more JSON representations for parameters" - }, - "externalDocs": { - "type": "object", - "additionalProperties": false, - "description": "information about external documentation", - "required": [ - "url" - ], - "properties": { - "description": { - "type": "string" - }, - "url": { - "type": "string", - "format": "uri" - } - }, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "examples": { - "type": "object", - "additionalProperties": true - }, - "mimeType": { - "type": "string", - "description": "The MIME type of the HTTP message." - }, - "operation": { - "type": "object", - "required": [ - "responses" - ], - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - }, - "properties": { - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "uniqueItems": true - }, - "summary": { - "type": "string", - "description": "A brief summary of the operation." - }, - "description": { - "type": "string", - "description": "A longer description of the operation, GitHub Flavored Markdown is allowed." - }, - "externalDocs": { - "$ref": "#/definitions/externalDocs" - }, - "operationId": { - "type": "string", - "description": "A unique identifier of the operation." - }, - "produces": { - "description": "A list of MIME types the API can produce.", - "allOf": [ - { - "$ref": "#/definitions/mediaTypeList" - } - ] - }, - "consumes": { - "description": "A list of MIME types the API can consume.", - "allOf": [ - { - "$ref": "#/definitions/mediaTypeList" - } - ] - }, - "parameters": { - "$ref": "#/definitions/parametersList" - }, - "responses": { - "$ref": "#/definitions/responses" - }, - "schemes": { - "$ref": "#/definitions/schemesList" - }, - "deprecated": { - "type": "boolean", - "default": false - }, - "security": { - "$ref": "#/definitions/security" - } - } - }, - "pathItem": { - "type": "object", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - }, - "properties": { - "$ref": { - "type": "string" - }, - "get": { - "$ref": "#/definitions/operation" - }, - "put": { - "$ref": "#/definitions/operation" - }, - "post": { - "$ref": "#/definitions/operation" - }, - "delete": { - "$ref": "#/definitions/operation" - }, - "options": { - "$ref": "#/definitions/operation" - }, - "head": { - "$ref": "#/definitions/operation" - }, - "patch": { - "$ref": "#/definitions/operation" - }, - "parameters": { - "$ref": "#/definitions/parametersList" - } - } - }, - "responses": { - "type": "object", - "description": "Response objects names can either be any valid HTTP status code or 'default'.", - "minProperties": 1, - "additionalProperties": false, - "patternProperties": { - "^([0-9]{3})$|^(default)$": { - "$ref": "#/definitions/responseValue" - }, - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - }, - "not": { - "type": "object", - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - } - } - }, - "responseValue": { - "oneOf": [ - { - "$ref": "#/definitions/response" - }, - { - "$ref": "#/definitions/jsonReference" - } - ] - }, - "response": { - "type": "object", - "required": [ - "description" - ], - "properties": { - "description": { - "type": "string" - }, - "schema": { - "oneOf": [ - { - "$ref": "#/definitions/schema" - }, - { - "$ref": "#/definitions/fileSchema" - } - ] - }, - "headers": { - "$ref": "#/definitions/headers" - }, - "examples": { - "$ref": "#/definitions/examples" - } - }, - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "headers": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/header" - } - }, - "header": { - "type": "object", - "additionalProperties": false, - "required": [ - "type" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "string", - "number", - "integer", - "boolean", - "array" - ] - }, - "format": { - "type": "string" - }, - "items": { - "$ref": "#/definitions/primitivesItems" - }, - "collectionFormat": { - "$ref": "#/definitions/collectionFormat" - }, - "default": { - "$ref": "#/definitions/default" - }, - "maximum": { - "$ref": "#/definitions/maximum" - }, - "exclusiveMaximum": { - "$ref": "#/definitions/exclusiveMaximum" - }, - "minimum": { - "$ref": "#/definitions/minimum" - }, - "exclusiveMinimum": { - "$ref": "#/definitions/exclusiveMinimum" - }, - "maxLength": { - "$ref": "#/definitions/maxLength" - }, - "minLength": { - "$ref": "#/definitions/minLength" - }, - "pattern": { - "$ref": "#/definitions/pattern" - }, - "maxItems": { - "$ref": "#/definitions/maxItems" - }, - "minItems": { - "$ref": "#/definitions/minItems" - }, - "uniqueItems": { - "$ref": "#/definitions/uniqueItems" - }, - "enum": { - "$ref": "#/definitions/enum" - }, - "multipleOf": { - "$ref": "#/definitions/multipleOf" - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "vendorExtension": { - "description": "Any property starting with x- is valid.", - "additionalProperties": true, - "additionalItems": true - }, - "bodyParameter": { - "type": "object", - "required": [ - "name", - "in", - "schema" - ], - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - }, - "properties": { - "description": { - "type": "string", - "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." - }, - "name": { - "type": "string", - "description": "The name of the parameter." - }, - "in": { - "type": "string", - "description": "Determines the location of the parameter.", - "enum": [ - "body" - ] - }, - "required": { - "type": "boolean", - "description": "Determines whether or not this parameter is required or optional.", - "default": false - }, - "schema": { - "$ref": "#/definitions/schema" - } - }, - "additionalProperties": false - }, - "headerParameterSubSchema": { - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - }, - "properties": { - "required": { - "type": "boolean", - "description": "Determines whether or not this parameter is required or optional.", - "default": false - }, - "in": { - "type": "string", - "description": "Determines the location of the parameter.", - "enum": [ - "header" - ] - }, - "description": { - "type": "string", - "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." - }, - "name": { - "type": "string", - "description": "The name of the parameter." - }, - "type": { - "type": "string", - "enum": [ - "string", - "number", - "boolean", - "integer", - "array" - ] - }, - "format": { - "type": "string" - }, - "items": { - "$ref": "#/definitions/primitivesItems" - }, - "collectionFormat": { - "$ref": "#/definitions/collectionFormat" - }, - "default": { - "$ref": "#/definitions/default" - }, - "maximum": { - "$ref": "#/definitions/maximum" - }, - "exclusiveMaximum": { - "$ref": "#/definitions/exclusiveMaximum" - }, - "minimum": { - "$ref": "#/definitions/minimum" - }, - "exclusiveMinimum": { - "$ref": "#/definitions/exclusiveMinimum" - }, - "maxLength": { - "$ref": "#/definitions/maxLength" - }, - "minLength": { - "$ref": "#/definitions/minLength" - }, - "pattern": { - "$ref": "#/definitions/pattern" - }, - "maxItems": { - "$ref": "#/definitions/maxItems" - }, - "minItems": { - "$ref": "#/definitions/minItems" - }, - "uniqueItems": { - "$ref": "#/definitions/uniqueItems" - }, - "enum": { - "$ref": "#/definitions/enum" - }, - "multipleOf": { - "$ref": "#/definitions/multipleOf" - } - } - }, - "queryParameterSubSchema": { - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - }, - "properties": { - "required": { - "type": "boolean", - "description": "Determines whether or not this parameter is required or optional.", - "default": false - }, - "in": { - "type": "string", - "description": "Determines the location of the parameter.", - "enum": [ - "query" - ] - }, - "description": { - "type": "string", - "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." - }, - "name": { - "type": "string", - "description": "The name of the parameter." - }, - "allowEmptyValue": { - "type": "boolean", - "default": false, - "description": "allows sending a parameter by name only or with an empty value." - }, - "type": { - "type": "string", - "enum": [ - "string", - "number", - "boolean", - "integer", - "array" - ] - }, - "format": { - "type": "string" - }, - "items": { - "$ref": "#/definitions/primitivesItems" - }, - "collectionFormat": { - "$ref": "#/definitions/collectionFormatWithMulti" - }, - "default": { - "$ref": "#/definitions/default" - }, - "maximum": { - "$ref": "#/definitions/maximum" - }, - "exclusiveMaximum": { - "$ref": "#/definitions/exclusiveMaximum" - }, - "minimum": { - "$ref": "#/definitions/minimum" - }, - "exclusiveMinimum": { - "$ref": "#/definitions/exclusiveMinimum" - }, - "maxLength": { - "$ref": "#/definitions/maxLength" - }, - "minLength": { - "$ref": "#/definitions/minLength" - }, - "pattern": { - "$ref": "#/definitions/pattern" - }, - "maxItems": { - "$ref": "#/definitions/maxItems" - }, - "minItems": { - "$ref": "#/definitions/minItems" - }, - "uniqueItems": { - "$ref": "#/definitions/uniqueItems" - }, - "enum": { - "$ref": "#/definitions/enum" - }, - "multipleOf": { - "$ref": "#/definitions/multipleOf" - } - } - }, - "formDataParameterSubSchema": { - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - }, - "properties": { - "required": { - "type": "boolean", - "description": "Determines whether or not this parameter is required or optional.", - "default": false - }, - "in": { - "type": "string", - "description": "Determines the location of the parameter.", - "enum": [ - "formData" - ] - }, - "description": { - "type": "string", - "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." - }, - "name": { - "type": "string", - "description": "The name of the parameter." - }, - "allowEmptyValue": { - "type": "boolean", - "default": false, - "description": "allows sending a parameter by name only or with an empty value." - }, - "type": { - "type": "string", - "enum": [ - "string", - "number", - "boolean", - "integer", - "array", - "file" - ] - }, - "format": { - "type": "string" - }, - "items": { - "$ref": "#/definitions/primitivesItems" - }, - "collectionFormat": { - "$ref": "#/definitions/collectionFormatWithMulti" - }, - "default": { - "$ref": "#/definitions/default" - }, - "maximum": { - "$ref": "#/definitions/maximum" - }, - "exclusiveMaximum": { - "$ref": "#/definitions/exclusiveMaximum" - }, - "minimum": { - "$ref": "#/definitions/minimum" - }, - "exclusiveMinimum": { - "$ref": "#/definitions/exclusiveMinimum" - }, - "maxLength": { - "$ref": "#/definitions/maxLength" - }, - "minLength": { - "$ref": "#/definitions/minLength" - }, - "pattern": { - "$ref": "#/definitions/pattern" - }, - "maxItems": { - "$ref": "#/definitions/maxItems" - }, - "minItems": { - "$ref": "#/definitions/minItems" - }, - "uniqueItems": { - "$ref": "#/definitions/uniqueItems" - }, - "enum": { - "$ref": "#/definitions/enum" - }, - "multipleOf": { - "$ref": "#/definitions/multipleOf" - } - } - }, - "pathParameterSubSchema": { - "additionalProperties": false, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - }, - "required": [ - "required" - ], - "properties": { - "required": { - "type": "boolean", - "enum": [ - true - ], - "description": "Determines whether or not this parameter is required or optional." - }, - "in": { - "type": "string", - "description": "Determines the location of the parameter.", - "enum": [ - "path" - ] - }, - "description": { - "type": "string", - "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." - }, - "name": { - "type": "string", - "description": "The name of the parameter." - }, - "type": { - "type": "string", - "enum": [ - "string", - "number", - "boolean", - "integer", - "array" - ] - }, - "format": { - "type": "string" - }, - "items": { - "$ref": "#/definitions/primitivesItems" - }, - "collectionFormat": { - "$ref": "#/definitions/collectionFormat" - }, - "default": { - "$ref": "#/definitions/default" - }, - "maximum": { - "$ref": "#/definitions/maximum" - }, - "exclusiveMaximum": { - "$ref": "#/definitions/exclusiveMaximum" - }, - "minimum": { - "$ref": "#/definitions/minimum" - }, - "exclusiveMinimum": { - "$ref": "#/definitions/exclusiveMinimum" - }, - "maxLength": { - "$ref": "#/definitions/maxLength" - }, - "minLength": { - "$ref": "#/definitions/minLength" - }, - "pattern": { - "$ref": "#/definitions/pattern" - }, - "maxItems": { - "$ref": "#/definitions/maxItems" - }, - "minItems": { - "$ref": "#/definitions/minItems" - }, - "uniqueItems": { - "$ref": "#/definitions/uniqueItems" - }, - "enum": { - "$ref": "#/definitions/enum" - }, - "multipleOf": { - "$ref": "#/definitions/multipleOf" - } - } - }, - "nonBodyParameter": { - "type": "object", - "required": [ - "name", - "in", - "type" - ], - "oneOf": [ - { - "$ref": "#/definitions/headerParameterSubSchema" - }, - { - "$ref": "#/definitions/formDataParameterSubSchema" - }, - { - "$ref": "#/definitions/queryParameterSubSchema" - }, - { - "$ref": "#/definitions/pathParameterSubSchema" - } - ] - }, - "parameter": { - "oneOf": [ - { - "$ref": "#/definitions/bodyParameter" - }, - { - "$ref": "#/definitions/nonBodyParameter" - } - ] - }, - "schema": { - "type": "object", - "description": "A deterministic version of a JSON Schema object.", - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - }, - "properties": { - "$ref": { - "type": "string" - }, - "format": { - "type": "string" - }, - "title": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/title" - }, - "description": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/description" - }, - "default": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/default" - }, - "multipleOf": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf" - }, - "maximum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum" - }, - "exclusiveMaximum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum" - }, - "minimum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum" - }, - "exclusiveMinimum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum" - }, - "maxLength": { - "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" - }, - "minLength": { - "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" - }, - "pattern": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern" - }, - "maxItems": { - "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" - }, - "minItems": { - "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" - }, - "uniqueItems": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems" - }, - "maxProperties": { - "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" - }, - "minProperties": { - "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" - }, - "required": { - "$ref": "http://json-schema.org/draft-04/schema#/definitions/stringArray" - }, - "enum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/enum" - }, - "additionalProperties": { - "anyOf": [ - { - "$ref": "#/definitions/schema" - }, - { - "type": "boolean" - } - ], - "default": {} - }, - "type": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/type" - }, - "items": { - "anyOf": [ - { - "$ref": "#/definitions/schema" - }, - { - "type": "array", - "minItems": 1, - "items": { - "$ref": "#/definitions/schema" - } - } - ], - "default": {} - }, - "allOf": { - "type": "array", - "minItems": 1, - "items": { - "$ref": "#/definitions/schema" - } - }, - "properties": { - "type": "object", - "additionalProperties": { - "$ref": "#/definitions/schema" - }, - "default": {} - }, - "discriminator": { - "type": "string" - }, - "readOnly": { - "type": "boolean", - "default": false - }, - "xml": { - "$ref": "#/definitions/xml" - }, - "externalDocs": { - "$ref": "#/definitions/externalDocs" - }, - "example": {} - }, - "additionalProperties": false - }, - "fileSchema": { - "type": "object", - "description": "A deterministic version of a JSON Schema object.", - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - }, - "required": [ - "type" - ], - "properties": { - "format": { - "type": "string" - }, - "title": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/title" - }, - "description": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/description" - }, - "default": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/default" - }, - "required": { - "$ref": "http://json-schema.org/draft-04/schema#/definitions/stringArray" - }, - "type": { - "type": "string", - "enum": [ - "file" - ] - }, - "readOnly": { - "type": "boolean", - "default": false - }, - "externalDocs": { - "$ref": "#/definitions/externalDocs" - }, - "example": {} - }, - "additionalProperties": false - }, - "primitivesItems": { - "type": "object", - "additionalProperties": false, - "properties": { - "type": { - "type": "string", - "enum": [ - "string", - "number", - "integer", - "boolean", - "array" - ] - }, - "format": { - "type": "string" - }, - "items": { - "$ref": "#/definitions/primitivesItems" - }, - "collectionFormat": { - "$ref": "#/definitions/collectionFormat" - }, - "default": { - "$ref": "#/definitions/default" - }, - "maximum": { - "$ref": "#/definitions/maximum" - }, - "exclusiveMaximum": { - "$ref": "#/definitions/exclusiveMaximum" - }, - "minimum": { - "$ref": "#/definitions/minimum" - }, - "exclusiveMinimum": { - "$ref": "#/definitions/exclusiveMinimum" - }, - "maxLength": { - "$ref": "#/definitions/maxLength" - }, - "minLength": { - "$ref": "#/definitions/minLength" - }, - "pattern": { - "$ref": "#/definitions/pattern" - }, - "maxItems": { - "$ref": "#/definitions/maxItems" - }, - "minItems": { - "$ref": "#/definitions/minItems" - }, - "uniqueItems": { - "$ref": "#/definitions/uniqueItems" - }, - "enum": { - "$ref": "#/definitions/enum" - }, - "multipleOf": { - "$ref": "#/definitions/multipleOf" - } - }, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "security": { - "type": "array", - "items": { - "$ref": "#/definitions/securityRequirement" - }, - "uniqueItems": true - }, - "securityRequirement": { - "type": "object", - "additionalProperties": { - "type": "array", - "items": { - "type": "string" - }, - "uniqueItems": true - } - }, - "xml": { - "type": "object", - "additionalProperties": false, - "properties": { - "name": { - "type": "string" - }, - "namespace": { - "type": "string" - }, - "prefix": { - "type": "string" - }, - "attribute": { - "type": "boolean", - "default": false - }, - "wrapped": { - "type": "boolean", - "default": false - } - }, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "tag": { - "type": "object", - "additionalProperties": false, - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "description": { - "type": "string" - }, - "externalDocs": { - "$ref": "#/definitions/externalDocs" - } - }, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "securityDefinitions": { - "type": "object", - "additionalProperties": { - "oneOf": [ - { - "$ref": "#/definitions/basicAuthenticationSecurity" - }, - { - "$ref": "#/definitions/apiKeySecurity" - }, - { - "$ref": "#/definitions/oauth2ImplicitSecurity" - }, - { - "$ref": "#/definitions/oauth2PasswordSecurity" - }, - { - "$ref": "#/definitions/oauth2ApplicationSecurity" - }, - { - "$ref": "#/definitions/oauth2AccessCodeSecurity" - } - ] - } - }, - "basicAuthenticationSecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "basic" - ] - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "apiKeySecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type", - "name", - "in" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "apiKey" - ] - }, - "name": { - "type": "string" - }, - "in": { - "type": "string", - "enum": [ - "header", - "query" - ] - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "oauth2ImplicitSecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type", - "flow", - "authorizationUrl" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "oauth2" - ] - }, - "flow": { - "type": "string", - "enum": [ - "implicit" - ] - }, - "scopes": { - "$ref": "#/definitions/oauth2Scopes" - }, - "authorizationUrl": { - "type": "string", - "format": "uri" - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "oauth2PasswordSecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type", - "flow", - "tokenUrl" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "oauth2" - ] - }, - "flow": { - "type": "string", - "enum": [ - "password" - ] - }, - "scopes": { - "$ref": "#/definitions/oauth2Scopes" - }, - "tokenUrl": { - "type": "string", - "format": "uri" - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "oauth2ApplicationSecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type", - "flow", - "tokenUrl" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "oauth2" - ] - }, - "flow": { - "type": "string", - "enum": [ - "application" - ] - }, - "scopes": { - "$ref": "#/definitions/oauth2Scopes" - }, - "tokenUrl": { - "type": "string", - "format": "uri" - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "oauth2AccessCodeSecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type", - "flow", - "authorizationUrl", - "tokenUrl" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "oauth2" - ] - }, - "flow": { - "type": "string", - "enum": [ - "accessCode" - ] - }, - "scopes": { - "$ref": "#/definitions/oauth2Scopes" - }, - "authorizationUrl": { - "type": "string", - "format": "uri" - }, - "tokenUrl": { - "type": "string", - "format": "uri" - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "oauth2Scopes": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, - "mediaTypeList": { - "type": "array", - "items": { - "$ref": "#/definitions/mimeType" - }, - "uniqueItems": true - }, - "parametersList": { - "type": "array", - "description": "The parameters needed to send a valid API call.", - "additionalItems": false, - "items": { - "oneOf": [ - { - "$ref": "#/definitions/parameter" - }, - { - "$ref": "#/definitions/jsonReference" - } - ] - }, - "uniqueItems": true - }, - "schemesList": { - "type": "array", - "description": "The transfer protocol of the API.", - "items": { - "type": "string", - "enum": [ - "http", - "https", - "ws", - "wss" - ] - }, - "uniqueItems": true - }, - "collectionFormat": { - "type": "string", - "enum": [ - "csv", - "ssv", - "tsv", - "pipes" - ], - "default": "csv" - }, - "collectionFormatWithMulti": { - "type": "string", - "enum": [ - "csv", - "ssv", - "tsv", - "pipes", - "multi" - ], - "default": "csv" - }, - "title": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/title" - }, - "description": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/description" - }, - "default": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/default" - }, - "multipleOf": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf" - }, - "maximum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum" - }, - "exclusiveMaximum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum" - }, - "minimum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum" - }, - "exclusiveMinimum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum" - }, - "maxLength": { - "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" - }, - "minLength": { - "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" - }, - "pattern": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern" - }, - "maxItems": { - "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" - }, - "minItems": { - "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" - }, - "uniqueItems": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems" - }, - "enum": { - "$ref": "http://json-schema.org/draft-04/schema#/properties/enum" - }, - "jsonReference": { - "type": "object", - "required": [ - "$ref" - ], - "additionalProperties": false, - "properties": { - "$ref": { - "type": "string" - } - } - } - } -} diff --git a/vendor/github.com/go-openapi/spec/security_scheme.go b/vendor/github.com/go-openapi/spec/security_scheme.go deleted file mode 100644 index 22d4f10af..000000000 --- a/vendor/github.com/go-openapi/spec/security_scheme.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -const ( - basic = "basic" - apiKey = "apiKey" - oauth2 = "oauth2" - implicit = "implicit" - password = "password" - application = "application" - accessCode = "accessCode" -) - -// BasicAuth creates a basic auth security scheme -func BasicAuth() *SecurityScheme { - return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{Type: basic}} -} - -// APIKeyAuth creates an api key auth security scheme -func APIKeyAuth(fieldName, valueSource string) *SecurityScheme { - return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{Type: apiKey, Name: fieldName, In: valueSource}} -} - -// OAuth2Implicit creates an implicit flow oauth2 security scheme -func OAuth2Implicit(authorizationURL string) *SecurityScheme { - return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ - Type: oauth2, - Flow: implicit, - AuthorizationURL: authorizationURL, - }} -} - -// OAuth2Password creates a password flow oauth2 security scheme -func OAuth2Password(tokenURL string) *SecurityScheme { - return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ - Type: oauth2, - Flow: password, - TokenURL: tokenURL, - }} -} - -// OAuth2Application creates an application flow oauth2 security scheme -func OAuth2Application(tokenURL string) *SecurityScheme { - return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ - Type: oauth2, - Flow: application, - TokenURL: tokenURL, - }} -} - -// OAuth2AccessToken creates an access token flow oauth2 security scheme -func OAuth2AccessToken(authorizationURL, tokenURL string) *SecurityScheme { - return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ - Type: oauth2, - Flow: accessCode, - AuthorizationURL: authorizationURL, - TokenURL: tokenURL, - }} -} - -type SecuritySchemeProps struct { - Description string `json:"description,omitempty"` - Type string `json:"type"` - Name string `json:"name,omitempty"` // api key - In string `json:"in,omitempty"` // api key - Flow string `json:"flow,omitempty"` // oauth2 - AuthorizationURL string `json:"authorizationUrl,omitempty"` // oauth2 - TokenURL string `json:"tokenUrl,omitempty"` // oauth2 - Scopes map[string]string `json:"scopes,omitempty"` // oauth2 -} - -// AddScope adds a scope to this security scheme -func (s *SecuritySchemeProps) AddScope(scope, description string) { - if s.Scopes == nil { - s.Scopes = make(map[string]string) - } - s.Scopes[scope] = description -} - -// SecurityScheme allows the definition of a security scheme that can be used by the operations. -// Supported schemes are basic authentication, an API key (either as a header or as a query parameter) -// and OAuth2's common flows (implicit, password, application and access code). -// -// For more information: http://goo.gl/8us55a#securitySchemeObject -type SecurityScheme struct { - VendorExtensible - SecuritySchemeProps -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s SecurityScheme) JSONLookup(token string) (interface{}, error) { - if ex, ok := s.Extensions[token]; ok { - return &ex, nil - } - - r, _, err := jsonpointer.GetForToken(s.SecuritySchemeProps, token) - return r, err -} - -// MarshalJSON marshal this to JSON -func (s SecurityScheme) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(s.SecuritySchemeProps) - if err != nil { - return nil, err - } - b2, err := json.Marshal(s.VendorExtensible) - if err != nil { - return nil, err - } - return swag.ConcatJSON(b1, b2), nil -} - -// UnmarshalJSON marshal this from JSON -func (s *SecurityScheme) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &s.SecuritySchemeProps); err != nil { - return err - } - if err := json.Unmarshal(data, &s.VendorExtensible); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/go-openapi/spec/spec.go b/vendor/github.com/go-openapi/spec/spec.go deleted file mode 100644 index 0bb045bc0..000000000 --- a/vendor/github.com/go-openapi/spec/spec.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import "encoding/json" - -//go:generate curl -L --progress -o ./schemas/v2/schema.json http://swagger.io/v2/schema.json -//go:generate curl -L --progress -o ./schemas/jsonschema-draft-04.json http://json-schema.org/draft-04/schema -//go:generate go-bindata -pkg=spec -prefix=./schemas -ignore=.*\.md ./schemas/... -//go:generate perl -pi -e s,Json,JSON,g bindata.go - -const ( - // SwaggerSchemaURL the url for the swagger 2.0 schema to validate specs - SwaggerSchemaURL = "http://swagger.io/v2/schema.json#" - // JSONSchemaURL the url for the json schema schema - JSONSchemaURL = "http://json-schema.org/draft-04/schema#" -) - -var ( - jsonSchema *Schema - swaggerSchema *Schema -) - -func init() { - jsonSchema = MustLoadJSONSchemaDraft04() - swaggerSchema = MustLoadSwagger20Schema() -} - -// MustLoadJSONSchemaDraft04 panics when Swagger20Schema returns an error -func MustLoadJSONSchemaDraft04() *Schema { - d, e := JSONSchemaDraft04() - if e != nil { - panic(e) - } - return d -} - -// JSONSchemaDraft04 loads the json schema document for json shema draft04 -func JSONSchemaDraft04() (*Schema, error) { - b, err := Asset("jsonschema-draft-04.json") - if err != nil { - return nil, err - } - - schema := new(Schema) - if err := json.Unmarshal(b, schema); err != nil { - return nil, err - } - return schema, nil -} - -// MustLoadSwagger20Schema panics when Swagger20Schema returns an error -func MustLoadSwagger20Schema() *Schema { - d, e := Swagger20Schema() - if e != nil { - panic(e) - } - return d -} - -// Swagger20Schema loads the swagger 2.0 schema from the embedded assets -func Swagger20Schema() (*Schema, error) { - - b, err := Asset("v2/schema.json") - if err != nil { - return nil, err - } - - schema := new(Schema) - if err := json.Unmarshal(b, schema); err != nil { - return nil, err - } - return schema, nil -} diff --git a/vendor/github.com/go-openapi/spec/structs_test.go b/vendor/github.com/go-openapi/spec/structs_test.go deleted file mode 100644 index bfa59ee03..000000000 --- a/vendor/github.com/go-openapi/spec/structs_test.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "reflect" - "testing" - - "github.com/stretchr/testify/assert" - "gopkg.in/yaml.v2" -) - -func assertSerializeJSON(t testing.TB, actual interface{}, expected string) bool { - ser, err := json.Marshal(actual) - if err != nil { - return assert.Fail(t, "unable to marshal to json (%s): %#v", err, actual) - } - return assert.Equal(t, string(ser), expected) -} - -func assertParsesJSON(t testing.TB, actual string, expected interface{}) bool { - tpe := reflect.TypeOf(expected) - var pointed bool - if tpe.Kind() == reflect.Ptr { - tpe = tpe.Elem() - pointed = true - } - - parsed := reflect.New(tpe) - err := json.Unmarshal([]byte(actual), parsed.Interface()) - if err != nil { - return assert.Fail(t, "unable to unmarshal from json (%s): %s", err, actual) - } - act := parsed.Interface() - if !pointed { - act = reflect.Indirect(parsed).Interface() - } - return assert.Equal(t, act, expected) -} - -func assertSerializeYAML(t testing.TB, actual interface{}, expected string) bool { - ser, err := yaml.Marshal(actual) - if err != nil { - return assert.Fail(t, "unable to marshal to yaml (%s): %#v", err, actual) - } - return assert.Equal(t, string(ser), expected) -} - -func assertParsesYAML(t testing.TB, actual string, expected interface{}) bool { - tpe := reflect.TypeOf(expected) - var pointed bool - if tpe.Kind() == reflect.Ptr { - tpe = tpe.Elem() - pointed = true - } - parsed := reflect.New(tpe) - err := yaml.Unmarshal([]byte(actual), parsed.Interface()) - if err != nil { - return assert.Fail(t, "unable to unmarshal from yaml (%s): %s", err, actual) - } - act := parsed.Interface() - if !pointed { - act = reflect.Indirect(parsed).Interface() - } - return assert.EqualValues(t, act, expected) -} - -func TestSerialization_SerializeJSON(t *testing.T) { - assertSerializeJSON(t, []string{"hello"}, "[\"hello\"]") - assertSerializeJSON(t, []string{"hello", "world", "and", "stuff"}, "[\"hello\",\"world\",\"and\",\"stuff\"]") - assertSerializeJSON(t, StringOrArray(nil), "null") - assertSerializeJSON(t, SchemaOrArray{Schemas: []Schema{Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}}}, "[{\"type\":\"string\"}]") - assertSerializeJSON(t, SchemaOrArray{ - Schemas: []Schema{ - Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - }}, "[{\"type\":\"string\"},{\"type\":\"string\"}]") - assertSerializeJSON(t, SchemaOrArray{}, "null") -} - -func TestSerialization_DeserializeJSON(t *testing.T) { - // String - assertParsesJSON(t, "\"hello\"", StringOrArray([]string{"hello"})) - assertParsesJSON(t, "[\"hello\",\"world\",\"and\",\"stuff\"]", StringOrArray([]string{"hello", "world", "and", "stuff"})) - assertParsesJSON(t, "[\"hello\",\"world\",null,\"stuff\"]", StringOrArray([]string{"hello", "world", "", "stuff"})) - assertParsesJSON(t, "null", StringOrArray(nil)) - - // Schema - assertParsesJSON(t, "{\"type\":\"string\"}", SchemaOrArray{Schema: &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}}) - assertParsesJSON(t, "[{\"type\":\"string\"},{\"type\":\"string\"}]", &SchemaOrArray{ - Schemas: []Schema{ - Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - Schema{SchemaProps: SchemaProps{Type: []string{"string"}}}, - }, - }) - assertParsesJSON(t, "null", SchemaOrArray{}) -} diff --git a/vendor/github.com/go-openapi/spec/swagger.go b/vendor/github.com/go-openapi/spec/swagger.go deleted file mode 100644 index 23780c78a..000000000 --- a/vendor/github.com/go-openapi/spec/swagger.go +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "fmt" - "strconv" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -// Swagger this is the root document object for the API specification. -// It combines what previously was the Resource Listing and API Declaration (version 1.2 and earlier) together into one document. -// -// For more information: http://goo.gl/8us55a#swagger-object- -type Swagger struct { - VendorExtensible - SwaggerProps -} - -// JSONLookup look up a value by the json property name -func (s Swagger) JSONLookup(token string) (interface{}, error) { - if ex, ok := s.Extensions[token]; ok { - return &ex, nil - } - r, _, err := jsonpointer.GetForToken(s.SwaggerProps, token) - return r, err -} - -// MarshalJSON marshals this swagger structure to json -func (s Swagger) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(s.SwaggerProps) - if err != nil { - return nil, err - } - b2, err := json.Marshal(s.VendorExtensible) - if err != nil { - return nil, err - } - return swag.ConcatJSON(b1, b2), nil -} - -// UnmarshalJSON unmarshals a swagger spec from json -func (s *Swagger) UnmarshalJSON(data []byte) error { - var sw Swagger - if err := json.Unmarshal(data, &sw.SwaggerProps); err != nil { - return err - } - if err := json.Unmarshal(data, &sw.VendorExtensible); err != nil { - return err - } - *s = sw - return nil -} - -type SwaggerProps struct { - ID string `json:"id,omitempty"` - Consumes []string `json:"consumes,omitempty"` - Produces []string `json:"produces,omitempty"` - Schemes []string `json:"schemes,omitempty"` // the scheme, when present must be from [http, https, ws, wss] - Swagger string `json:"swagger,omitempty"` - Info *Info `json:"info,omitempty"` - Host string `json:"host,omitempty"` - BasePath string `json:"basePath,omitempty"` // must start with a leading "/" - Paths *Paths `json:"paths"` // required - Definitions Definitions `json:"definitions,omitempty"` - Parameters map[string]Parameter `json:"parameters,omitempty"` - Responses map[string]Response `json:"responses,omitempty"` - SecurityDefinitions SecurityDefinitions `json:"securityDefinitions,omitempty"` - Security []map[string][]string `json:"security,omitempty"` - Tags []Tag `json:"tags,omitempty"` - ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` -} - -// Dependencies represent a dependencies property -type Dependencies map[string]SchemaOrStringArray - -// SchemaOrBool represents a schema or boolean value, is biased towards true for the boolean property -type SchemaOrBool struct { - Allows bool - Schema *Schema -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s SchemaOrBool) JSONLookup(token string) (interface{}, error) { - if token == "allows" { - return s.Allows, nil - } - r, _, err := jsonpointer.GetForToken(s.Schema, token) - return r, err -} - -var jsTrue = []byte("true") -var jsFalse = []byte("false") - -// MarshalJSON convert this object to JSON -func (s SchemaOrBool) MarshalJSON() ([]byte, error) { - if s.Schema != nil { - return json.Marshal(s.Schema) - } - - if s.Schema == nil && !s.Allows { - return jsFalse, nil - } - return jsTrue, nil -} - -// UnmarshalJSON converts this bool or schema object from a JSON structure -func (s *SchemaOrBool) UnmarshalJSON(data []byte) error { - var nw SchemaOrBool - if len(data) >= 4 { - if data[0] == '{' { - var sch Schema - if err := json.Unmarshal(data, &sch); err != nil { - return err - } - nw.Schema = &sch - } - nw.Allows = !(data[0] == 'f' && data[1] == 'a' && data[2] == 'l' && data[3] == 's' && data[4] == 'e') - } - *s = nw - return nil -} - -// SchemaOrStringArray represents a schema or a string array -type SchemaOrStringArray struct { - Schema *Schema - Property []string -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s SchemaOrStringArray) JSONLookup(token string) (interface{}, error) { - r, _, err := jsonpointer.GetForToken(s.Schema, token) - return r, err -} - -// MarshalJSON converts this schema object or array into JSON structure -func (s SchemaOrStringArray) MarshalJSON() ([]byte, error) { - if len(s.Property) > 0 { - return json.Marshal(s.Property) - } - if s.Schema != nil { - return json.Marshal(s.Schema) - } - return []byte("null"), nil -} - -// UnmarshalJSON converts this schema object or array from a JSON structure -func (s *SchemaOrStringArray) UnmarshalJSON(data []byte) error { - var first byte - if len(data) > 1 { - first = data[0] - } - var nw SchemaOrStringArray - if first == '{' { - var sch Schema - if err := json.Unmarshal(data, &sch); err != nil { - return err - } - nw.Schema = &sch - } - if first == '[' { - if err := json.Unmarshal(data, &nw.Property); err != nil { - return err - } - } - *s = nw - return nil -} - -// Definitions contains the models explicitly defined in this spec -// An object to hold data types that can be consumed and produced by operations. -// These data types can be primitives, arrays or models. -// -// For more information: http://goo.gl/8us55a#definitionsObject -type Definitions map[string]Schema - -// SecurityDefinitions a declaration of the security schemes available to be used in the specification. -// This does not enforce the security schemes on the operations and only serves to provide -// the relevant details for each scheme. -// -// For more information: http://goo.gl/8us55a#securityDefinitionsObject -type SecurityDefinitions map[string]*SecurityScheme - -// StringOrArray represents a value that can either be a string -// or an array of strings. Mainly here for serialization purposes -type StringOrArray []string - -// Contains returns true when the value is contained in the slice -func (s StringOrArray) Contains(value string) bool { - for _, str := range s { - if str == value { - return true - } - } - return false -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s SchemaOrArray) JSONLookup(token string) (interface{}, error) { - if _, err := strconv.Atoi(token); err == nil { - r, _, err := jsonpointer.GetForToken(s.Schemas, token) - return r, err - } - r, _, err := jsonpointer.GetForToken(s.Schema, token) - return r, err -} - -// UnmarshalJSON unmarshals this string or array object from a JSON array or JSON string -func (s *StringOrArray) UnmarshalJSON(data []byte) error { - var first byte - if len(data) > 1 { - first = data[0] - } - - if first == '[' { - var parsed []string - if err := json.Unmarshal(data, &parsed); err != nil { - return err - } - *s = StringOrArray(parsed) - return nil - } - - var single interface{} - if err := json.Unmarshal(data, &single); err != nil { - return err - } - if single == nil { - return nil - } - switch single.(type) { - case string: - *s = StringOrArray([]string{single.(string)}) - return nil - default: - return fmt.Errorf("only string or array is allowed, not %T", single) - } -} - -// MarshalJSON converts this string or array to a JSON array or JSON string -func (s StringOrArray) MarshalJSON() ([]byte, error) { - if len(s) == 1 { - return json.Marshal([]string(s)[0]) - } - return json.Marshal([]string(s)) -} - -// SchemaOrArray represents a value that can either be a Schema -// or an array of Schema. Mainly here for serialization purposes -type SchemaOrArray struct { - Schema *Schema - Schemas []Schema -} - -// Len returns the number of schemas in this property -func (s SchemaOrArray) Len() int { - if s.Schema != nil { - return 1 - } - return len(s.Schemas) -} - -// ContainsType returns true when one of the schemas is of the specified type -func (s *SchemaOrArray) ContainsType(name string) bool { - if s.Schema != nil { - return s.Schema.Type != nil && s.Schema.Type.Contains(name) - } - return false -} - -// MarshalJSON converts this schema object or array into JSON structure -func (s SchemaOrArray) MarshalJSON() ([]byte, error) { - if len(s.Schemas) > 0 { - return json.Marshal(s.Schemas) - } - return json.Marshal(s.Schema) -} - -// UnmarshalJSON converts this schema object or array from a JSON structure -func (s *SchemaOrArray) UnmarshalJSON(data []byte) error { - var nw SchemaOrArray - var first byte - if len(data) > 1 { - first = data[0] - } - if first == '{' { - var sch Schema - if err := json.Unmarshal(data, &sch); err != nil { - return err - } - nw.Schema = &sch - } - if first == '[' { - if err := json.Unmarshal(data, &nw.Schemas); err != nil { - return err - } - } - *s = nw - return nil -} - -// vim:set ft=go noet sts=2 sw=2 ts=2: diff --git a/vendor/github.com/go-openapi/spec/swagger_test.go b/vendor/github.com/go-openapi/spec/swagger_test.go deleted file mode 100644 index f7b3d9022..000000000 --- a/vendor/github.com/go-openapi/spec/swagger_test.go +++ /dev/null @@ -1,365 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "fmt" - "reflect" - "testing" - - "github.com/go-openapi/swag" - "github.com/stretchr/testify/assert" -) - -var spec = Swagger{ - SwaggerProps: SwaggerProps{ - ID: "http://localhost:3849/api-docs", - Swagger: "2.0", - Consumes: []string{"application/json", "application/x-yaml"}, - Produces: []string{"application/json"}, - Schemes: []string{"http", "https"}, - Info: &info, - Host: "some.api.out.there", - BasePath: "/", - Paths: &paths, - Definitions: map[string]Schema{"Category": {SchemaProps: SchemaProps{Type: []string{"string"}}}}, - Parameters: map[string]Parameter{ - "categoryParam": {ParamProps: ParamProps{Name: "category", In: "query"}, SimpleSchema: SimpleSchema{Type: "string"}}, - }, - Responses: map[string]Response{ - "EmptyAnswer": { - ResponseProps: ResponseProps{ - Description: "no data to return for this operation", - }, - }, - }, - SecurityDefinitions: map[string]*SecurityScheme{ - "internalApiKey": APIKeyAuth("api_key", "header"), - }, - Security: []map[string][]string{ - {"internalApiKey": {}}, - }, - Tags: []Tag{NewTag("pets", "", nil)}, - ExternalDocs: &ExternalDocumentation{"the name", "the url"}, - }, - VendorExtensible: VendorExtensible{map[string]interface{}{ - "x-some-extension": "vendor", - "x-schemes": []interface{}{"unix", "amqp"}, - }}, -} - -var specJSON = `{ - "id": "http://localhost:3849/api-docs", - "consumes": ["application/json", "application/x-yaml"], - "produces": ["application/json"], - "schemes": ["http", "https"], - "swagger": "2.0", - "info": { - "contact": { - "name": "wordnik api team", - "url": "http://developer.wordnik.com" - }, - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "license": { - "name": "Creative Commons 4.0 International", - "url": "http://creativecommons.org/licenses/by/4.0/" - }, - "termsOfService": "http://helloreverb.com/terms/", - "title": "Swagger Sample API", - "version": "1.0.9-abcd", - "x-framework": "go-swagger" - }, - "host": "some.api.out.there", - "basePath": "/", - "paths": {"x-framework":"go-swagger","/":{"$ref":"cats"}}, - "definitions": { "Category": { "type": "string"} }, - "parameters": { - "categoryParam": { - "name": "category", - "in": "query", - "type": "string" - } - }, - "responses": { "EmptyAnswer": { "description": "no data to return for this operation" } }, - "securityDefinitions": { - "internalApiKey": { - "type": "apiKey", - "in": "header", - "name": "api_key" - } - }, - "security": [{"internalApiKey":[]}], - "tags": [{"name":"pets"}], - "externalDocs": {"description":"the name","url":"the url"}, - "x-some-extension": "vendor", - "x-schemes": ["unix","amqp"] -}` - -// -// func verifySpecSerialize(specJSON []byte, spec Swagger) { -// expected := map[string]interface{}{} -// json.Unmarshal(specJSON, &expected) -// b, err := json.MarshalIndent(spec, "", " ") -// So(err, ShouldBeNil) -// var actual map[string]interface{} -// err = json.Unmarshal(b, &actual) -// So(err, ShouldBeNil) -// compareSpecMaps(actual, expected) -// } - -func assertEquivalent(t testing.TB, actual, expected interface{}) bool { - if actual == nil || expected == nil || reflect.DeepEqual(actual, expected) { - return true - } - - actualType := reflect.TypeOf(actual) - expectedType := reflect.TypeOf(expected) - if reflect.TypeOf(actual).ConvertibleTo(expectedType) { - expectedValue := reflect.ValueOf(expected) - if swag.IsZero(expectedValue) && swag.IsZero(reflect.ValueOf(actual)) { - return true - } - - // Attempt comparison after type conversion - if reflect.DeepEqual(actual, expectedValue.Convert(actualType).Interface()) { - return true - } - } - - // Last ditch effort - if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) { - return true - } - errFmt := "Expected: '%T(%#v)'\nActual: '%T(%#v)'\n(Should be equivalent)!" - return assert.Fail(t, errFmt, expected, expected, actual, actual) -} - -func ShouldBeEquivalentTo(actual interface{}, expecteds ...interface{}) string { - expected := expecteds[0] - if actual == nil || expected == nil { - return "" - } - - if reflect.DeepEqual(expected, actual) { - return "" - } - - actualType := reflect.TypeOf(actual) - expectedType := reflect.TypeOf(expected) - if reflect.TypeOf(actual).ConvertibleTo(expectedType) { - expectedValue := reflect.ValueOf(expected) - if swag.IsZero(expectedValue) && swag.IsZero(reflect.ValueOf(actual)) { - return "" - } - - // Attempt comparison after type conversion - if reflect.DeepEqual(actual, expectedValue.Convert(actualType).Interface()) { - return "" - } - } - - // Last ditch effort - if fmt.Sprintf("%#v", expected) == fmt.Sprintf("%#v", actual) { - return "" - } - errFmt := "Expected: '%T(%#v)'\nActual: '%T(%#v)'\n(Should be equivalent)!" - return fmt.Sprintf(errFmt, expected, expected, actual, actual) - -} - -func assertSpecMaps(t testing.TB, actual, expected map[string]interface{}) bool { - res := true - if id, ok := expected["id"]; ok { - res = assert.Equal(t, id, actual["id"]) - } - res = res && assert.Equal(t, expected["consumes"], actual["consumes"]) - res = res && assert.Equal(t, expected["produces"], actual["produces"]) - res = res && assert.Equal(t, expected["schemes"], actual["schemes"]) - res = res && assert.Equal(t, expected["swagger"], actual["swagger"]) - res = res && assert.Equal(t, expected["info"], actual["info"]) - res = res && assert.Equal(t, expected["host"], actual["host"]) - res = res && assert.Equal(t, expected["basePath"], actual["basePath"]) - res = res && assert.Equal(t, expected["paths"], actual["paths"]) - res = res && assert.Equal(t, expected["definitions"], actual["definitions"]) - res = res && assert.Equal(t, expected["responses"], actual["responses"]) - res = res && assert.Equal(t, expected["securityDefinitions"], actual["securityDefinitions"]) - res = res && assert.Equal(t, expected["tags"], actual["tags"]) - res = res && assert.Equal(t, expected["externalDocs"], actual["externalDocs"]) - res = res && assert.Equal(t, expected["x-some-extension"], actual["x-some-extension"]) - res = res && assert.Equal(t, expected["x-schemes"], actual["x-schemes"]) - - return res -} - -// -// func compareSpecMaps(actual, expected map[string]interface{}) { -// if id, ok := expected["id"]; ok { -// So(actual["id"], ShouldEqual, id) -// } -// //So(actual["$schema"], ShouldEqual, SwaggerSchemaURL) -// So(actual["consumes"], ShouldResemble, expected["consumes"]) -// So(actual["produces"], ShouldResemble, expected["produces"]) -// So(actual["schemes"], ShouldResemble, expected["schemes"]) -// So(actual["swagger"], ShouldEqual, expected["swagger"]) -// So(actual["info"], ShouldResemble, expected["info"]) -// So(actual["host"], ShouldEqual, expected["host"]) -// So(actual["basePath"], ShouldEqual, expected["basePath"]) -// So(actual["paths"], ShouldBeEquivalentTo, expected["paths"]) -// So(actual["definitions"], ShouldBeEquivalentTo, expected["definitions"]) -// So(actual["responses"], ShouldBeEquivalentTo, expected["responses"]) -// So(actual["securityDefinitions"], ShouldResemble, expected["securityDefinitions"]) -// So(actual["tags"], ShouldResemble, expected["tags"]) -// So(actual["externalDocs"], ShouldResemble, expected["externalDocs"]) -// So(actual["x-some-extension"], ShouldResemble, expected["x-some-extension"]) -// So(actual["x-schemes"], ShouldResemble, expected["x-schemes"]) -// } - -func assertSpecs(t testing.TB, actual, expected Swagger) bool { - expected.Swagger = "2.0" - return assert.Equal(t, actual, expected) -} - -// -// func compareSpecs(actual Swagger, spec Swagger) { -// spec.Swagger = "2.0" -// So(actual, ShouldBeEquivalentTo, spec) -// } - -func assertSpecJSON(t testing.TB, specJSON []byte) bool { - var expected map[string]interface{} - if !assert.NoError(t, json.Unmarshal(specJSON, &expected)) { - return false - } - - obj := Swagger{} - if !assert.NoError(t, json.Unmarshal(specJSON, &obj)) { - return false - } - - cb, err := json.MarshalIndent(obj, "", " ") - if assert.NoError(t, err) { - return false - } - var actual map[string]interface{} - if !assert.NoError(t, json.Unmarshal(cb, &actual)) { - return false - } - return assertSpecMaps(t, actual, expected) -} - -// func verifySpecJSON(specJSON []byte) { -// //Println() -// //Println("json to verify", string(specJson)) -// var expected map[string]interface{} -// err := json.Unmarshal(specJSON, &expected) -// So(err, ShouldBeNil) -// -// obj := Swagger{} -// err = json.Unmarshal(specJSON, &obj) -// So(err, ShouldBeNil) -// -// //spew.Dump(obj) -// -// cb, err := json.MarshalIndent(obj, "", " ") -// So(err, ShouldBeNil) -// //Println() -// //Println("Marshalling to json returned", string(cb)) -// -// var actual map[string]interface{} -// err = json.Unmarshal(cb, &actual) -// So(err, ShouldBeNil) -// //Println() -// //spew.Dump(expected) -// //spew.Dump(actual) -// //fmt.Printf("comparing %s\n\t%#v\nto\n\t%#+v\n", fileName, expected, actual) -// compareSpecMaps(actual, expected) -// } - -func TestSwaggerSpec_Serialize(t *testing.T) { - expected := make(map[string]interface{}) - json.Unmarshal([]byte(specJSON), &expected) - b, err := json.MarshalIndent(spec, "", " ") - if assert.NoError(t, err) { - var actual map[string]interface{} - err := json.Unmarshal(b, &actual) - if assert.NoError(t, err) { - assert.EqualValues(t, actual, expected) - } - } -} - -func TestSwaggerSpec_Deserialize(t *testing.T) { - var actual Swagger - err := json.Unmarshal([]byte(specJSON), &actual) - if assert.NoError(t, err) { - assert.EqualValues(t, actual, spec) - } -} - -func TestVendorExtensionStringSlice(t *testing.T) { - var actual Swagger - err := json.Unmarshal([]byte(specJSON), &actual) - if assert.NoError(t, err) { - schemes, ok := actual.Extensions.GetStringSlice("x-schemes") - if assert.True(t, ok) { - assert.EqualValues(t, []string{"unix", "amqp"}, schemes) - } - } -} - -func TestOptionalSwaggerProps_Serialize(t *testing.T) { - minimalJsonSpec := []byte(`{ - "swagger": "2.0", - "info": { - "version": "0.0.0", - "title": "Simple API" - }, - "paths": { - "/": { - "get": { - "responses": { - "200": { - "description": "OK" - } - } - } - } - } -}`) - - var minimalSpec Swagger - err := json.Unmarshal(minimalJsonSpec, &minimalSpec) - if assert.NoError(t, err) { - bytes, err := json.Marshal(&minimalSpec) - if assert.NoError(t, err) { - var ms map[string]interface{} - if err := json.Unmarshal(bytes, &ms); assert.NoError(t, err) { - assert.NotContains(t, ms, "consumes") - assert.NotContains(t, ms, "produces") - assert.NotContains(t, ms, "schemes") - assert.NotContains(t, ms, "host") - assert.NotContains(t, ms, "basePath") - assert.NotContains(t, ms, "definitions") - assert.NotContains(t, ms, "parameters") - assert.NotContains(t, ms, "responses") - assert.NotContains(t, ms, "securityDefinitions") - assert.NotContains(t, ms, "security") - assert.NotContains(t, ms, "tags") - assert.NotContains(t, ms, "externalDocs") - } - } - } -} diff --git a/vendor/github.com/go-openapi/spec/tag.go b/vendor/github.com/go-openapi/spec/tag.go deleted file mode 100644 index 97f555840..000000000 --- a/vendor/github.com/go-openapi/spec/tag.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -type TagProps struct { - Description string `json:"description,omitempty"` - Name string `json:"name,omitempty"` - ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` -} - -// NewTag creates a new tag -func NewTag(name, description string, externalDocs *ExternalDocumentation) Tag { - return Tag{TagProps: TagProps{description, name, externalDocs}} -} - -// Tag allows adding meta data to a single tag that is used by the [Operation Object](http://goo.gl/8us55a#operationObject). -// It is not mandatory to have a Tag Object per tag used there. -// -// For more information: http://goo.gl/8us55a#tagObject -type Tag struct { - VendorExtensible - TagProps -} - -// JSONLookup implements an interface to customize json pointer lookup -func (t Tag) JSONLookup(token string) (interface{}, error) { - if ex, ok := t.Extensions[token]; ok { - return &ex, nil - } - - r, _, err := jsonpointer.GetForToken(t.TagProps, token) - return r, err -} - -// MarshalJSON marshal this to JSON -func (t Tag) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(t.TagProps) - if err != nil { - return nil, err - } - b2, err := json.Marshal(t.VendorExtensible) - if err != nil { - return nil, err - } - return swag.ConcatJSON(b1, b2), nil -} - -// UnmarshalJSON marshal this from JSON -func (t *Tag) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &t.TagProps); err != nil { - return err - } - return json.Unmarshal(data, &t.VendorExtensible) -} diff --git a/vendor/github.com/go-openapi/spec/xml_object.go b/vendor/github.com/go-openapi/spec/xml_object.go deleted file mode 100644 index 945a46703..000000000 --- a/vendor/github.com/go-openapi/spec/xml_object.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -// XMLObject a metadata object that allows for more fine-tuned XML model definitions. -// -// For more information: http://goo.gl/8us55a#xmlObject -type XMLObject struct { - Name string `json:"name,omitempty"` - Namespace string `json:"namespace,omitempty"` - Prefix string `json:"prefix,omitempty"` - Attribute bool `json:"attribute,omitempty"` - Wrapped bool `json:"wrapped,omitempty"` -} - -// WithName sets the xml name for the object -func (x *XMLObject) WithName(name string) *XMLObject { - x.Name = name - return x -} - -// WithNamespace sets the xml namespace for the object -func (x *XMLObject) WithNamespace(namespace string) *XMLObject { - x.Namespace = namespace - return x -} - -// WithPrefix sets the xml prefix for the object -func (x *XMLObject) WithPrefix(prefix string) *XMLObject { - x.Prefix = prefix - return x -} - -// AsAttribute flags this object as xml attribute -func (x *XMLObject) AsAttribute() *XMLObject { - x.Attribute = true - return x -} - -// AsElement flags this object as an xml node -func (x *XMLObject) AsElement() *XMLObject { - x.Attribute = false - return x -} - -// AsWrapped flags this object as wrapped, this is mostly useful for array types -func (x *XMLObject) AsWrapped() *XMLObject { - x.Wrapped = true - return x -} - -// AsUnwrapped flags this object as an xml node -func (x *XMLObject) AsUnwrapped() *XMLObject { - x.Wrapped = false - return x -} diff --git a/vendor/github.com/go-openapi/spec/xml_object_test.go b/vendor/github.com/go-openapi/spec/xml_object_test.go deleted file mode 100644 index fda3b1084..000000000 --- a/vendor/github.com/go-openapi/spec/xml_object_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package spec - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestXmlObject_Serialize(t *testing.T) { - obj1 := XMLObject{} - actual, err := json.Marshal(obj1) - if assert.NoError(t, err) { - assert.Equal(t, "{}", string(actual)) - } - - obj2 := XMLObject{ - Name: "the name", - Namespace: "the namespace", - Prefix: "the prefix", - Attribute: true, - Wrapped: true, - } - - actual, err = json.Marshal(obj2) - if assert.NoError(t, err) { - var ad map[string]interface{} - if assert.NoError(t, json.Unmarshal(actual, &ad)) { - assert.Equal(t, obj2.Name, ad["name"]) - assert.Equal(t, obj2.Namespace, ad["namespace"]) - assert.Equal(t, obj2.Prefix, ad["prefix"]) - assert.True(t, ad["attribute"].(bool)) - assert.True(t, ad["wrapped"].(bool)) - } - } -} - -func TestXmlObject_Deserialize(t *testing.T) { - expected := XMLObject{} - actual := XMLObject{} - if assert.NoError(t, json.Unmarshal([]byte("{}"), &actual)) { - assert.Equal(t, expected, actual) - } - - completed := `{"name":"the name","namespace":"the namespace","prefix":"the prefix","attribute":true,"wrapped":true}` - expected = XMLObject{"the name", "the namespace", "the prefix", true, true} - actual = XMLObject{} - if assert.NoError(t, json.Unmarshal([]byte(completed), &actual)) { - assert.Equal(t, expected, actual) - } -} diff --git a/vendor/github.com/go-openapi/strfmt/.editorconfig b/vendor/github.com/go-openapi/strfmt/.editorconfig deleted file mode 100644 index 3152da69a..000000000 --- a/vendor/github.com/go-openapi/strfmt/.editorconfig +++ /dev/null @@ -1,26 +0,0 @@ -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -end_of_line = lf -insert_final_newline = true -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true - -# Set default charset -[*.{js,py,go,scala,rb,java,html,css,less,sass,md}] -charset = utf-8 - -# Tab indentation (no size specified) -[*.go] -indent_style = tab - -[*.md] -trim_trailing_whitespace = false - -# Matches the exact files either package.json or .travis.yml -[{package.json,.travis.yml}] -indent_style = space -indent_size = 2 diff --git a/vendor/github.com/go-openapi/strfmt/.github/CONTRIBUTING.md b/vendor/github.com/go-openapi/strfmt/.github/CONTRIBUTING.md deleted file mode 100644 index 7dea4240d..000000000 --- a/vendor/github.com/go-openapi/strfmt/.github/CONTRIBUTING.md +++ /dev/null @@ -1,117 +0,0 @@ -## Contribution Guidelines - -### Pull requests are always welcome - -We are always thrilled to receive pull requests, and do our best to -process them as fast as possible. Not sure if that typo is worth a pull -request? Do it! We will appreciate it. - -If your pull request is not accepted on the first try, don't be -discouraged! If there's a problem with the implementation, hopefully you -received feedback on what to improve. - -We're trying very hard to keep go-swagger lean and focused. We don't want it -to do everything for everybody. This means that we might decide against -incorporating a new feature. However, there might be a way to implement -that feature *on top of* go-swagger. - - -### Conventions - -Fork the repo and make changes on your fork in a feature branch: - -- If it's a bugfix branch, name it XXX-something where XXX is the number of the - issue -- If it's a feature branch, create an enhancement issue to announce your - intentions, and name it XXX-something where XXX is the number of the issue. - -Submit unit tests for your changes. Go has a great test framework built in; use -it! Take a look at existing tests for inspiration. Run the full test suite on -your branch before submitting a pull request. - -Update the documentation when creating or modifying features. Test -your documentation changes for clarity, concision, and correctness, as -well as a clean documentation build. See ``docs/README.md`` for more -information on building the docs and how docs get released. - -Write clean code. Universally formatted code promotes ease of writing, reading, -and maintenance. Always run `gofmt -s -w file.go` on each changed file before -committing your changes. Most editors have plugins that do this automatically. - -Pull requests descriptions should be as clear as possible and include a -reference to all the issues that they address. - -Pull requests must not contain commits from other users or branches. - -Commit messages must start with a capitalized and short summary (max. 50 -chars) written in the imperative, followed by an optional, more detailed -explanatory text which is separated from the summary by an empty line. - -Code review comments may be added to your pull request. Discuss, then make the -suggested modifications and push additional commits to your feature branch. Be -sure to post a comment after pushing. The new commits will show up in the pull -request automatically, but the reviewers will not be notified unless you -comment. - -Before the pull request is merged, make sure that you squash your commits into -logical units of work using `git rebase -i` and `git push -f`. After every -commit the test suite should be passing. Include documentation changes in the -same commit so that a revert would remove all traces of the feature or fix. - -Commits that fix or close an issue should include a reference like `Closes #XXX` -or `Fixes #XXX`, which will automatically close the issue when merged. - -### Sign your work - -The sign-off is a simple line at the end of the explanation for the -patch, which certifies that you wrote it or otherwise have the right to -pass it on as an open-source patch. The rules are pretty simple: if you -can certify the below (from -[developercertificate.org](http://developercertificate.org/)): - -``` -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` - -then you just add a line to every git commit message: - - Signed-off-by: Joe Smith - -using your real name (sorry, no pseudonyms or anonymous contributions.) - -You can add the sign off when creating the git commit via `git commit -s`. diff --git a/vendor/github.com/go-openapi/strfmt/.gitignore b/vendor/github.com/go-openapi/strfmt/.gitignore deleted file mode 100644 index dd91ed6a0..000000000 --- a/vendor/github.com/go-openapi/strfmt/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -secrets.yml -coverage.out diff --git a/vendor/github.com/go-openapi/strfmt/.travis.yml b/vendor/github.com/go-openapi/strfmt/.travis.yml deleted file mode 100644 index 88a3a6eae..000000000 --- a/vendor/github.com/go-openapi/strfmt/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -language: go -go: -- 1.7.1 -install: -- go get -u github.com/stretchr/testify/assert -- go get -u github.com/pborman/uuid -- go get -u github.com/asaskevich/govalidator -- go get -u github.com/mailru/easyjson -- go get -u github.com/go-openapi/errors -- go get -u github.com/mitchellh/mapstructure -- go get -u gopkg.in/mgo.v2/bson -script: -- ./hack/coverage -after_success: -- bash <(curl -s https://codecov.io/bash) -notifications: - slack: - secure: zE5AtIYTpYfQPnTzP+EaQPN7JKtfFAGv6PrJqoIZLOXa8B6zGb6+J1JRNNxWi7faWbyJOxa4FSSsuPsKZMycUK6wlLFIdhDxwqeo7Ew8r6rdZKdfUHQggfNS9wO79ARoNYUDHtmnaBUS+eWSM1YqSc4i99QxyyfuURLOeAaA/q14YbdlTlaw3lrZ0qT92ot1FnVGNOx064zuHtFeUf+jAVRMZ6Q3rvqllwIlPszE6rmHGXBt2VoJxRaBetdwd7FgkcYw9FPXKHhadwC7/75ZAdmxIukhxNMw4Tr5NuPcqNcnbYLenDP7B3lssGVIrP4BRSqekS1d/tqvdvnnFWHMwrNCkSnSc065G5+qWTlXKAemIclgiXXqE2furBNLm05MDdG8fn5epS0UNarkjD+zX336RiqwBlOX4KbF+vPyqcO98CsN0lnd+H6loc9reiTHs37orFFpQ+309av9be2GGsHUsRB9ssIyrewmhAccOmkRtr2dVTZJNFQwa5Kph5TNJuTjnZEwG/xUkEX2YSfwShOsb062JWiflV6PJdnl80pc9Tn7D5sO5Bf9DbijGRJwwP+YiiJtwtr+vsvS+n4sM0b5eqm4UoRo+JJO8ffoJtHS7ItuyRbVQCwEPJ4221WLcf5PquEEDdAPwR+K4Gj8qTXqTDdxOiES1xFUKVgmzhI= diff --git a/vendor/github.com/go-openapi/strfmt/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/strfmt/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e..000000000 --- a/vendor/github.com/go-openapi/strfmt/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/strfmt/LICENSE b/vendor/github.com/go-openapi/strfmt/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/go-openapi/strfmt/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/go-openapi/strfmt/README.md b/vendor/github.com/go-openapi/strfmt/README.md deleted file mode 100644 index ec041ba12..000000000 --- a/vendor/github.com/go-openapi/strfmt/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# Strfmt [![Build Status](https://travis-ci.org/go-openapi/strfmt.svg?branch=master)](https://travis-ci.org/go-openapi/strfmt) [![codecov](https://codecov.io/gh/go-openapi/strfmt/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/strfmt) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/strfmt/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/strfmt?status.svg)](http://godoc.org/github.com/go-openapi/strfmt) - -This package exposes a registry of data types to support string formats in the go-openapi toolkit. - -strfmt represents a well known string format such as credit card or email. The go toolkit for open api specifications knows how to deal with those. - -## Supported data formats -go-openapi/strfmt follows the swagger 2.0 specification with the following formats -defined [here](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types). - -It also provides convenient extensions to go-openapi users. - -- [x] JSON-schema draft 4 formats - - date-time - - email - - hostname - - ipv4 - - ipv6 - - uri -- [x] swagger 2.0 format extensions - - binary - - byte (e.g. base64 encoded string) - - date (e.g. "1970-01-01") - - password -- [x] go-openapi custom format extensions - - bsonobjectid (BSON objectID) - - creditcard - - duration (e.g. "3 weeks", "1ms") - - hexcolor (e.g. "#FFFFFF") - - isbn, isbn10, isbn13 - - mac (e.g "01:02:03:04:05:06") - - rgbcolor (e.g. "rgb(100,100,100)") - - ssn - - uuid, uuid3, uuid4, uuid5 - -> NOTE: as the name stands for, this package is intended to support string formatting only. -> It does not provide validation for numerical values with swagger format extension for JSON types "number" or -> "integer" (e.g. float, double, int32...). - -## Format types -Types defined in strfmt expose marshaling and validation capabilities. - -List of defined types: -- Base64 -- CreditCard -- Date -- DateTime -- Duration -- Email -- HexColor -- Hostname -- IPv4 -- IPv6 -- ISBN -- ISBN10 -- ISBN13 -- MAC -- ObjectId -- Password -- RGBColor -- SSN -- URI -- UUID -- UUID3 -- UUID4 -- UUID5 diff --git a/vendor/github.com/go-openapi/strfmt/bson.go b/vendor/github.com/go-openapi/strfmt/bson.go deleted file mode 100644 index d5a4f9861..000000000 --- a/vendor/github.com/go-openapi/strfmt/bson.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package strfmt - -import ( - "database/sql/driver" - "errors" - "fmt" - - "github.com/mailru/easyjson/jlexer" - "github.com/mailru/easyjson/jwriter" - - "gopkg.in/mgo.v2/bson" -) - -func init() { - var id ObjectId - // register this format in the default registry - Default.Add("bsonobjectid", &id, IsBSONObjectID) -} - -// IsBSONObjectID returns true when the string is a valid BSON.ObjectId -func IsBSONObjectID(str string) bool { - return bson.IsObjectIdHex(str) -} - -// ObjectId represents a BSON object ID (alias to gopkg.in/mgo.v2/bson.ObjectId) -// -// swagger:strfmt bsonobjectid -type ObjectId bson.ObjectId - -// NewObjectId creates a ObjectId from a Hex String -func NewObjectId(hex string) ObjectId { - return ObjectId(bson.ObjectIdHex(hex)) -} - -// MarshalText turns this instance into text -func (id *ObjectId) MarshalText() ([]byte, error) { - return []byte(bson.ObjectId(*id).Hex()), nil -} - -// UnmarshalText hydrates this instance from text -func (id *ObjectId) UnmarshalText(data []byte) error { // validation is performed later on - *id = ObjectId(bson.ObjectIdHex(string(data))) - return nil -} - -// Scan read a value from a database driver -func (id *ObjectId) Scan(raw interface{}) error { - var data []byte - switch v := raw.(type) { - case []byte: - data = v - case string: - data = []byte(v) - default: - return fmt.Errorf("cannot sql.Scan() strfmt.URI from: %#v", v) - } - - return id.UnmarshalText(data) -} - -// Value converts a value to a database driver value -func (id *ObjectId) Value() (driver.Value, error) { - return driver.Value(string(*id)), nil -} - -func (id *ObjectId) String() string { - return string(*id) -} - -// MarshalJSON returns the ObjectId as JSON -func (id *ObjectId) MarshalJSON() ([]byte, error) { - var w jwriter.Writer - id.MarshalEasyJSON(&w) - return w.BuildBytes() -} - -// MarshalEasyJSON writes the ObjectId to a easyjson.Writer -func (id *ObjectId) MarshalEasyJSON(w *jwriter.Writer) { - w.String(bson.ObjectId(*id).Hex()) -} - -// UnmarshalJSON sets the ObjectId from JSON -func (id *ObjectId) UnmarshalJSON(data []byte) error { - l := jlexer.Lexer{Data: data} - id.UnmarshalEasyJSON(&l) - return l.Error() -} - -// UnmarshalEasyJSON sets the ObjectId from a easyjson.Lexer -func (id *ObjectId) UnmarshalEasyJSON(in *jlexer.Lexer) { - if data := in.String(); in.Ok() { - *id = NewObjectId(data) - } -} - -// GetBSON returns the hex representation of the ObjectId as a bson.M{} map. -func (id *ObjectId) GetBSON() (interface{}, error) { - return bson.M{"data": bson.ObjectId(*id).Hex()}, nil -} - -// SetBSON sets the ObjectId from raw bson data -func (id *ObjectId) SetBSON(raw bson.Raw) error { - var m bson.M - if err := raw.Unmarshal(&m); err != nil { - return err - } - - if data, ok := m["data"].(string); ok { - *id = NewObjectId(data) - return nil - } - - return errors.New("couldn't unmarshal bson raw value as ObjectId") -} diff --git a/vendor/github.com/go-openapi/strfmt/bson_test.go b/vendor/github.com/go-openapi/strfmt/bson_test.go deleted file mode 100644 index 32ba962b1..000000000 --- a/vendor/github.com/go-openapi/strfmt/bson_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package strfmt - -import ( - "testing" - - "gopkg.in/mgo.v2/bson" - - "github.com/stretchr/testify/assert" -) - -func TestBSONObjectId_fullCycle(t *testing.T) { - id := NewObjectId("507f1f77bcf86cd799439011") - bytes, err := id.MarshalText() - assert.NoError(t, err) - - var idCopy ObjectId - - err = idCopy.Scan(bytes) - assert.NoError(t, err) - assert.Equal(t, id, idCopy) - - err = idCopy.UnmarshalText(bytes) - assert.NoError(t, err) - assert.Equal(t, id, idCopy) - - jsonBytes, err := id.MarshalJSON() - assert.NoError(t, err) - - err = idCopy.UnmarshalJSON(jsonBytes) - assert.NoError(t, err) - assert.Equal(t, id, idCopy) - - bsonBytes, err := bson.Marshal(&id) - assert.NoError(t, err) - - err = bson.Unmarshal(bsonBytes, &idCopy) - assert.NoError(t, err) - assert.Equal(t, id, idCopy) -} diff --git a/vendor/github.com/go-openapi/strfmt/conv/date.go b/vendor/github.com/go-openapi/strfmt/conv/date.go deleted file mode 100644 index b5c382060..000000000 --- a/vendor/github.com/go-openapi/strfmt/conv/date.go +++ /dev/null @@ -1,18 +0,0 @@ -package conv - -import "github.com/go-openapi/strfmt" - -// Date returns a pointer to of the Date value passed in. -func Date(v strfmt.Date) *strfmt.Date { - return &v -} - -// DateValue returns the value of the Date pointer passed in or -// the default value if the pointer is nil. -func DateValue(v *strfmt.Date) strfmt.Date { - if v == nil { - return strfmt.Date{} - } - - return *v -} diff --git a/vendor/github.com/go-openapi/strfmt/conv/date_test.go b/vendor/github.com/go-openapi/strfmt/conv/date_test.go deleted file mode 100644 index da9788892..000000000 --- a/vendor/github.com/go-openapi/strfmt/conv/date_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package conv - -import ( - "testing" - "time" - - "github.com/go-openapi/strfmt" - "github.com/stretchr/testify/assert" -) - -func TestDateValue(t *testing.T) { - assert.Equal(t, strfmt.Date{}, DateValue(nil)) - date := strfmt.Date(time.Now()) - assert.Equal(t, date, DateValue(&date)) -} diff --git a/vendor/github.com/go-openapi/strfmt/conv/default.go b/vendor/github.com/go-openapi/strfmt/conv/default.go deleted file mode 100644 index d00fa175e..000000000 --- a/vendor/github.com/go-openapi/strfmt/conv/default.go +++ /dev/null @@ -1,290 +0,0 @@ -package conv - -import ( - "github.com/go-openapi/strfmt" -) - -// Base64 returns a pointer to of the Base64 value passed in. -func Base64(v strfmt.Base64) *strfmt.Base64 { - return &v -} - -// Base64Value returns the value of the Base64 pointer passed in or -// the default value if the pointer is nil. -func Base64Value(v *strfmt.Base64) strfmt.Base64 { - if v == nil { - return nil - } - - return *v -} - -// URI returns a pointer to of the URI value passed in. -func URI(v strfmt.URI) *strfmt.URI { - return &v -} - -// URIValue returns the value of the URI pointer passed in or -// the default value if the pointer is nil. -func URIValue(v *strfmt.URI) strfmt.URI { - if v == nil { - return strfmt.URI("") - } - - return *v -} - -// Email returns a pointer to of the Email value passed in. -func Email(v strfmt.Email) *strfmt.Email { - return &v -} - -// EmailValue returns the value of the Email pointer passed in or -// the default value if the pointer is nil. -func EmailValue(v *strfmt.Email) strfmt.Email { - if v == nil { - return strfmt.Email("") - } - - return *v -} - -// Hostname returns a pointer to of the Hostname value passed in. -func Hostname(v strfmt.Hostname) *strfmt.Hostname { - return &v -} - -// HostnameValue returns the value of the Hostname pointer passed in or -// the default value if the pointer is nil. -func HostnameValue(v *strfmt.Hostname) strfmt.Hostname { - if v == nil { - return strfmt.Hostname("") - } - - return *v -} - -// IPv4 returns a pointer to of the IPv4 value passed in. -func IPv4(v strfmt.IPv4) *strfmt.IPv4 { - return &v -} - -// IPv4Value returns the value of the IPv4 pointer passed in or -// the default value if the pointer is nil. -func IPv4Value(v *strfmt.IPv4) strfmt.IPv4 { - if v == nil { - return strfmt.IPv4("") - } - - return *v -} - -// IPv6 returns a pointer to of the IPv6 value passed in. -func IPv6(v strfmt.IPv6) *strfmt.IPv6 { - return &v -} - -// IPv6Value returns the value of the IPv6 pointer passed in or -// the default value if the pointer is nil. -func IPv6Value(v *strfmt.IPv6) strfmt.IPv6 { - if v == nil { - return strfmt.IPv6("") - } - - return *v -} - -// MAC returns a pointer to of the MAC value passed in. -func MAC(v strfmt.MAC) *strfmt.MAC { - return &v -} - -// MACValue returns the value of the MAC pointer passed in or -// the default value if the pointer is nil. -func MACValue(v *strfmt.MAC) strfmt.MAC { - if v == nil { - return strfmt.MAC("") - } - - return *v -} - -// UUID returns a pointer to of the UUID value passed in. -func UUID(v strfmt.UUID) *strfmt.UUID { - return &v -} - -// UUIDValue returns the value of the UUID pointer passed in or -// the default value if the pointer is nil. -func UUIDValue(v *strfmt.UUID) strfmt.UUID { - if v == nil { - return strfmt.UUID("") - } - - return *v -} - -// UUID3 returns a pointer to of the UUID3 value passed in. -func UUID3(v strfmt.UUID3) *strfmt.UUID3 { - return &v -} - -// UUID3Value returns the value of the UUID3 pointer passed in or -// the default value if the pointer is nil. -func UUID3Value(v *strfmt.UUID3) strfmt.UUID3 { - if v == nil { - return strfmt.UUID3("") - } - - return *v -} - -// UUID4 returns a pointer to of the UUID4 value passed in. -func UUID4(v strfmt.UUID4) *strfmt.UUID4 { - return &v -} - -// UUID4Value returns the value of the UUID4 pointer passed in or -// the default value if the pointer is nil. -func UUID4Value(v *strfmt.UUID4) strfmt.UUID4 { - if v == nil { - return strfmt.UUID4("") - } - - return *v -} - -// UUID5 returns a pointer to of the UUID5 value passed in. -func UUID5(v strfmt.UUID5) *strfmt.UUID5 { - return &v -} - -// UUID5Value returns the value of the UUID5 pointer passed in or -// the default value if the pointer is nil. -func UUID5Value(v *strfmt.UUID5) strfmt.UUID5 { - if v == nil { - return strfmt.UUID5("") - } - - return *v -} - -// ISBN returns a pointer to of the ISBN value passed in. -func ISBN(v strfmt.ISBN) *strfmt.ISBN { - return &v -} - -// ISBNValue returns the value of the ISBN pointer passed in or -// the default value if the pointer is nil. -func ISBNValue(v *strfmt.ISBN) strfmt.ISBN { - if v == nil { - return strfmt.ISBN("") - } - - return *v -} - -// ISBN10 returns a pointer to of the ISBN10 value passed in. -func ISBN10(v strfmt.ISBN10) *strfmt.ISBN10 { - return &v -} - -// ISBN10Value returns the value of the ISBN10 pointer passed in or -// the default value if the pointer is nil. -func ISBN10Value(v *strfmt.ISBN10) strfmt.ISBN10 { - if v == nil { - return strfmt.ISBN10("") - } - - return *v -} - -// ISBN13 returns a pointer to of the ISBN13 value passed in. -func ISBN13(v strfmt.ISBN13) *strfmt.ISBN13 { - return &v -} - -// ISBN13Value returns the value of the ISBN13 pointer passed in or -// the default value if the pointer is nil. -func ISBN13Value(v *strfmt.ISBN13) strfmt.ISBN13 { - if v == nil { - return strfmt.ISBN13("") - } - - return *v -} - -// CreditCard returns a pointer to of the CreditCard value passed in. -func CreditCard(v strfmt.CreditCard) *strfmt.CreditCard { - return &v -} - -// CreditCardValue returns the value of the CreditCard pointer passed in or -// the default value if the pointer is nil. -func CreditCardValue(v *strfmt.CreditCard) strfmt.CreditCard { - if v == nil { - return strfmt.CreditCard("") - } - - return *v -} - -// SSN returns a pointer to of the SSN value passed in. -func SSN(v strfmt.SSN) *strfmt.SSN { - return &v -} - -// SSNValue returns the value of the SSN pointer passed in or -// the default value if the pointer is nil. -func SSNValue(v *strfmt.SSN) strfmt.SSN { - if v == nil { - return strfmt.SSN("") - } - - return *v -} - -// HexColor returns a pointer to of the HexColor value passed in. -func HexColor(v strfmt.HexColor) *strfmt.HexColor { - return &v -} - -// HexColorValue returns the value of the HexColor pointer passed in or -// the default value if the pointer is nil. -func HexColorValue(v *strfmt.HexColor) strfmt.HexColor { - if v == nil { - return strfmt.HexColor("") - } - - return *v -} - -// RGBColor returns a pointer to of the RGBColor value passed in. -func RGBColor(v strfmt.RGBColor) *strfmt.RGBColor { - return &v -} - -// RGBColorValue returns the value of the RGBColor pointer passed in or -// the default value if the pointer is nil. -func RGBColorValue(v *strfmt.RGBColor) strfmt.RGBColor { - if v == nil { - return strfmt.RGBColor("") - } - - return *v -} - -// Password returns a pointer to of the Password value passed in. -func Password(v strfmt.Password) *strfmt.Password { - return &v -} - -// PasswordValue returns the value of the Password pointer passed in or -// the default value if the pointer is nil. -func PasswordValue(v *strfmt.Password) strfmt.Password { - if v == nil { - return strfmt.Password("") - } - - return *v -} diff --git a/vendor/github.com/go-openapi/strfmt/conv/default_test.go b/vendor/github.com/go-openapi/strfmt/conv/default_test.go deleted file mode 100644 index b182ef741..000000000 --- a/vendor/github.com/go-openapi/strfmt/conv/default_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package conv - -import ( - "testing" - - "github.com/go-openapi/strfmt" - "github.com/stretchr/testify/assert" -) - -func TestBase64Value(t *testing.T) { - assert.Equal(t, strfmt.Base64(nil), Base64Value(nil)) - base64 := strfmt.Base64([]byte{4, 2}) - assert.Equal(t, base64, Base64Value(&base64)) -} - -func TestURIValue(t *testing.T) { - assert.Equal(t, strfmt.URI(""), URIValue(nil)) - value := strfmt.URI("foo") - assert.Equal(t, value, URIValue(&value)) -} - -func TestEmailValue(t *testing.T) { - assert.Equal(t, strfmt.Email(""), EmailValue(nil)) - value := strfmt.Email("foo") - assert.Equal(t, value, EmailValue(&value)) -} - -func TestHostnameValue(t *testing.T) { - assert.Equal(t, strfmt.Hostname(""), HostnameValue(nil)) - value := strfmt.Hostname("foo") - assert.Equal(t, value, HostnameValue(&value)) -} - -func TestIPv4Value(t *testing.T) { - assert.Equal(t, strfmt.IPv4(""), IPv4Value(nil)) - value := strfmt.IPv4("foo") - assert.Equal(t, value, IPv4Value(&value)) -} - -func TestIPv6Value(t *testing.T) { - assert.Equal(t, strfmt.IPv6(""), IPv6Value(nil)) - value := strfmt.IPv6("foo") - assert.Equal(t, value, IPv6Value(&value)) -} - -func TestMACValue(t *testing.T) { - assert.Equal(t, strfmt.MAC(""), MACValue(nil)) - value := strfmt.MAC("foo") - assert.Equal(t, value, MACValue(&value)) -} - -func TestUUIDValue(t *testing.T) { - assert.Equal(t, strfmt.UUID(""), UUIDValue(nil)) - value := strfmt.UUID("foo") - assert.Equal(t, value, UUIDValue(&value)) -} - -func TestUUID3Value(t *testing.T) { - assert.Equal(t, strfmt.UUID3(""), UUID3Value(nil)) - value := strfmt.UUID3("foo") - assert.Equal(t, value, UUID3Value(&value)) -} - -func TestUUID4Value(t *testing.T) { - assert.Equal(t, strfmt.UUID4(""), UUID4Value(nil)) - value := strfmt.UUID4("foo") - assert.Equal(t, value, UUID4Value(&value)) -} - -func TestUUID5Value(t *testing.T) { - assert.Equal(t, strfmt.UUID5(""), UUID5Value(nil)) - value := strfmt.UUID5("foo") - assert.Equal(t, value, UUID5Value(&value)) -} - -func TestISBNValue(t *testing.T) { - assert.Equal(t, strfmt.ISBN(""), ISBNValue(nil)) - value := strfmt.ISBN("foo") - assert.Equal(t, value, ISBNValue(&value)) -} - -func TestISBN10Value(t *testing.T) { - assert.Equal(t, strfmt.ISBN10(""), ISBN10Value(nil)) - value := strfmt.ISBN10("foo") - assert.Equal(t, value, ISBN10Value(&value)) -} - -func TestISBN13Value(t *testing.T) { - assert.Equal(t, strfmt.ISBN13(""), ISBN13Value(nil)) - value := strfmt.ISBN13("foo") - assert.Equal(t, value, ISBN13Value(&value)) -} - -func TestCreditCardValue(t *testing.T) { - assert.Equal(t, strfmt.CreditCard(""), CreditCardValue(nil)) - value := strfmt.CreditCard("foo") - assert.Equal(t, value, CreditCardValue(&value)) -} - -func TestSSNValue(t *testing.T) { - assert.Equal(t, strfmt.SSN(""), SSNValue(nil)) - value := strfmt.SSN("foo") - assert.Equal(t, value, SSNValue(&value)) -} - -func TestHexColorValue(t *testing.T) { - assert.Equal(t, strfmt.HexColor(""), HexColorValue(nil)) - value := strfmt.HexColor("foo") - assert.Equal(t, value, HexColorValue(&value)) -} - -func TestRGBColorValue(t *testing.T) { - assert.Equal(t, strfmt.RGBColor(""), RGBColorValue(nil)) - value := strfmt.RGBColor("foo") - assert.Equal(t, value, RGBColorValue(&value)) -} - -func TestPasswordValue(t *testing.T) { - assert.Equal(t, strfmt.Password(""), PasswordValue(nil)) - value := strfmt.Password("foo") - assert.Equal(t, value, PasswordValue(&value)) -} diff --git a/vendor/github.com/go-openapi/strfmt/conv/duration.go b/vendor/github.com/go-openapi/strfmt/conv/duration.go deleted file mode 100644 index ea30132b5..000000000 --- a/vendor/github.com/go-openapi/strfmt/conv/duration.go +++ /dev/null @@ -1,18 +0,0 @@ -package conv - -import "github.com/go-openapi/strfmt" - -// Duration returns a pointer to of the Duration value passed in. -func Duration(v strfmt.Duration) *strfmt.Duration { - return &v -} - -// DurationValue returns the value of the Duration pointer passed in or -// the default value if the pointer is nil. -func DurationValue(v *strfmt.Duration) strfmt.Duration { - if v == nil { - return strfmt.Duration(0) - } - - return *v -} diff --git a/vendor/github.com/go-openapi/strfmt/conv/duration_test.go b/vendor/github.com/go-openapi/strfmt/conv/duration_test.go deleted file mode 100644 index f19173f4e..000000000 --- a/vendor/github.com/go-openapi/strfmt/conv/duration_test.go +++ /dev/null @@ -1,14 +0,0 @@ -package conv - -import ( - "testing" - - "github.com/go-openapi/strfmt" - "github.com/stretchr/testify/assert" -) - -func TestDurationValue(t *testing.T) { - assert.Equal(t, strfmt.Duration(0), DurationValue(nil)) - duration := strfmt.Duration(42) - assert.Equal(t, duration, DurationValue(&duration)) -} diff --git a/vendor/github.com/go-openapi/strfmt/conv/time.go b/vendor/github.com/go-openapi/strfmt/conv/time.go deleted file mode 100644 index 627cd12d7..000000000 --- a/vendor/github.com/go-openapi/strfmt/conv/time.go +++ /dev/null @@ -1,18 +0,0 @@ -package conv - -import "github.com/go-openapi/strfmt" - -// DateTime returns a pointer to of the DateTime value passed in. -func DateTime(v strfmt.DateTime) *strfmt.DateTime { - return &v -} - -// DateTimeValue returns the value of the DateTime pointer passed in or -// the default value if the pointer is nil. -func DateTimeValue(v *strfmt.DateTime) strfmt.DateTime { - if v == nil { - return strfmt.DateTime{} - } - - return *v -} diff --git a/vendor/github.com/go-openapi/strfmt/conv/time_test.go b/vendor/github.com/go-openapi/strfmt/conv/time_test.go deleted file mode 100644 index 89a427df2..000000000 --- a/vendor/github.com/go-openapi/strfmt/conv/time_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package conv - -import ( - "testing" - "time" - - "github.com/go-openapi/strfmt" - "github.com/stretchr/testify/assert" -) - -func TestDateTimeValue(t *testing.T) { - assert.Equal(t, strfmt.DateTime{}, DateTimeValue(nil)) - time := strfmt.DateTime(time.Now()) - assert.Equal(t, time, DateTimeValue(&time)) -} diff --git a/vendor/github.com/go-openapi/strfmt/date.go b/vendor/github.com/go-openapi/strfmt/date.go deleted file mode 100644 index 206b7cb90..000000000 --- a/vendor/github.com/go-openapi/strfmt/date.go +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package strfmt - -import ( - "database/sql/driver" - "errors" - "fmt" - "time" - - "gopkg.in/mgo.v2/bson" - - "github.com/mailru/easyjson/jlexer" - "github.com/mailru/easyjson/jwriter" -) - -func init() { - d := Date{} - // register this format in the default registry - Default.Add("date", &d, IsDate) -} - -// IsDate returns true when the string is a valid date -func IsDate(str string) bool { - _, err := time.Parse(RFC3339FullDate, str) - return err == nil -} - -const ( - // RFC3339FullDate represents a full-date as specified by RFC3339 - // See: http://goo.gl/xXOvVd - RFC3339FullDate = "2006-01-02" -) - -// Date represents a date from the API -// -// swagger:strfmt date -type Date time.Time - -// String converts this date into a string -func (d Date) String() string { - return time.Time(d).Format(RFC3339FullDate) -} - -// UnmarshalText parses a text representation into a date type -func (d *Date) UnmarshalText(text []byte) error { - if len(text) == 0 { - return nil - } - dd, err := time.Parse(RFC3339FullDate, string(text)) - if err != nil { - return err - } - *d = Date(dd) - return nil -} - -// MarshalText serializes this date type to string -func (d Date) MarshalText() ([]byte, error) { - return []byte(d.String()), nil -} - -// Scan scans a Date value from database driver type. -func (d *Date) Scan(raw interface{}) error { - switch v := raw.(type) { - case []byte: - return d.UnmarshalText(v) - case string: - return d.UnmarshalText([]byte(v)) - case time.Time: - *d = Date(v) - return nil - case nil: - *d = Date{} - return nil - default: - return fmt.Errorf("cannot sql.Scan() strfmt.Date from: %#v", v) - } -} - -// Value converts Date to a primitive value ready to written to a database. -func (d Date) Value() (driver.Value, error) { - return driver.Value(d.String()), nil -} - -// MarshalJSON returns the Date as JSON -func (d Date) MarshalJSON() ([]byte, error) { - var w jwriter.Writer - d.MarshalEasyJSON(&w) - return w.BuildBytes() -} - -// MarshalEasyJSON writes the Date to a easyjson.Writer -func (d Date) MarshalEasyJSON(w *jwriter.Writer) { - w.String(time.Time(d).Format(RFC3339FullDate)) -} - -// UnmarshalJSON sets the Date from JSON -func (d *Date) UnmarshalJSON(data []byte) error { - l := jlexer.Lexer{Data: data} - d.UnmarshalEasyJSON(&l) - return l.Error() -} - -// UnmarshalEasyJSON sets the Date from a easyjson.Lexer -func (d *Date) UnmarshalEasyJSON(in *jlexer.Lexer) { - if data := in.String(); in.Ok() { - tt, err := time.Parse(RFC3339FullDate, data) - if err != nil { - in.AddError(err) - return - } - *d = Date(tt) - } -} - -// GetBSON returns the Date as a bson.M{} map. -func (d *Date) GetBSON() (interface{}, error) { - return bson.M{"data": d.String()}, nil -} - -// SetBSON sets the Date from raw bson data -func (d *Date) SetBSON(raw bson.Raw) error { - var m bson.M - if err := raw.Unmarshal(&m); err != nil { - return err - } - - if data, ok := m["data"].(string); ok { - rd, err := time.Parse(RFC3339FullDate, data) - *d = Date(rd) - return err - } - - return errors.New("couldn't unmarshal bson raw value as Date") -} diff --git a/vendor/github.com/go-openapi/strfmt/date_test.go b/vendor/github.com/go-openapi/strfmt/date_test.go deleted file mode 100644 index 4498dc267..000000000 --- a/vendor/github.com/go-openapi/strfmt/date_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package strfmt - -import ( - "database/sql" - "database/sql/driver" - "testing" - "time" - - "gopkg.in/mgo.v2/bson" - - "github.com/stretchr/testify/assert" -) - -var _ sql.Scanner = &Date{} -var _ driver.Valuer = Date{} - -func TestDate(t *testing.T) { - pp := Date{} - err := pp.UnmarshalText([]byte{}) - assert.NoError(t, err) - err = pp.UnmarshalText([]byte("yada")) - assert.Error(t, err) - - orig := "2014-12-15" - b := []byte(orig) - bj := []byte("\"" + orig + "\"") - err = pp.UnmarshalText([]byte(orig)) - assert.NoError(t, err) - - txt, err := pp.MarshalText() - assert.NoError(t, err) - assert.Equal(t, orig, string(txt)) - - err = pp.UnmarshalJSON(bj) - assert.NoError(t, err) - assert.EqualValues(t, orig, pp.String()) - - err = pp.UnmarshalJSON([]byte(`"1972/01/01"`)) - assert.Error(t, err) - - b, err = pp.MarshalJSON() - assert.NoError(t, err) - assert.Equal(t, bj, b) - - dateOriginal := Date(time.Date(2014, 10, 10, 0, 0, 0, 0, time.UTC)) - - bsonData, err := bson.Marshal(&dateOriginal) - assert.NoError(t, err) - - var dateCopy Date - err = bson.Unmarshal(bsonData, &dateCopy) - assert.NoError(t, err) - assert.Equal(t, dateOriginal, dateCopy) -} - -func TestDate_Scan(t *testing.T) { - ref := time.Now().Truncate(24 * time.Hour).UTC() - date, str := Date(ref), ref.Format(RFC3339FullDate) - - values := []interface{}{str, []byte(str), ref} - for _, value := range values { - result := Date{} - (&result).Scan(value) - assert.Equal(t, date, result, "value: %#v", value) - } - - dd := Date{} - err := dd.Scan(nil) - assert.NoError(t, err) - assert.Equal(t, Date{}, dd) - - err = dd.Scan(19700101) - assert.Error(t, err) -} - -func TestDate_Value(t *testing.T) { - ref := time.Now().Truncate(24 * time.Hour).UTC() - date := Date(ref) - dbv, err := date.Value() - assert.NoError(t, err) - assert.EqualValues(t, dbv, ref.Format("2006-01-02")) -} - -func TestDate_IsDate(t *testing.T) { - tests := []struct { - value string - valid bool - }{ - {"2017-12-22", true}, - {"2017-1-1", false}, - {"17-13-22", false}, - {"2017-02-29", false}, // not a valid date : 2017 is not a leap year - {"1900-02-29", false}, // not a valid date : 1900 is not a leap year - {"2100-02-29", false}, // not a valid date : 2100 is not a leap year - {"2000-02-29", true}, // a valid date : 2000 is a leap year - {"2400-02-29", true}, // a valid date : 2000 is a leap year - {"2017-13-22", false}, - {"2017-12-32", false}, - {"20171-12-32", false}, - {"YYYY-MM-DD", false}, - {"20-17-2017", false}, - {"2017-12-22T01:02:03Z", false}, - } - for _, test := range tests { - assert.Equal(t, test.valid, IsDate(test.value), "value [%s] should be valid: [%t]", test.value, test.valid) - } -} diff --git a/vendor/github.com/go-openapi/strfmt/default.go b/vendor/github.com/go-openapi/strfmt/default.go deleted file mode 100644 index 469f7222f..000000000 --- a/vendor/github.com/go-openapi/strfmt/default.go +++ /dev/null @@ -1,1831 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package strfmt - -import ( - "database/sql/driver" - "encoding/base64" - "errors" - "fmt" - "regexp" - "strings" - - "github.com/asaskevich/govalidator" - "github.com/mailru/easyjson/jlexer" - "github.com/mailru/easyjson/jwriter" - - "gopkg.in/mgo.v2/bson" -) - -const ( - // HostnamePattern http://json-schema.org/latest/json-schema-validation.html#anchor114 - // A string instance is valid against this attribute if it is a valid - // representation for an Internet host name, as defined by RFC 1034, section 3.1 [RFC1034]. - // http://tools.ietf.org/html/rfc1034#section-3.5 - // ::= any one of the ten digits 0 through 9 - // var digit = /[0-9]/; - // ::= any one of the 52 alphabetic characters A through Z in upper case and a through z in lower case - // var letter = /[a-zA-Z]/; - // ::= | - // var letDig = /[0-9a-zA-Z]/; - // ::= | "-" - // var letDigHyp = /[-0-9a-zA-Z]/; - // ::= | - // var ldhStr = /[-0-9a-zA-Z]+/; - //