aboutsummaryrefslogtreecommitdiff
path: root/src/dict2rest/vendor/github.com
diff options
context:
space:
mode:
authorFelix Hanley <felix@userspace.com.au>2016-05-12 13:28:05 +0000
committerFelix Hanley <felix@userspace.com.au>2016-05-12 13:28:05 +0000
commite1c3d6f7db06d592538f1162b2b6b9f1b6efa330 (patch)
treec26ee9ad763a2bc48cde0e2c46f831a40f55ed28 /src/dict2rest/vendor/github.com
parentbb8476ffe78210d1a4c0b4bbee6da99da1bc15c5 (diff)
downloadgo-dict2rest-e1c3d6f7db06d592538f1162b2b6b9f1b6efa330.tar.gz
go-dict2rest-e1c3d6f7db06d592538f1162b2b6b9f1b6efa330.tar.bz2
Shuffle vendor directory up a level o_0
Diffstat (limited to 'src/dict2rest/vendor/github.com')
-rw-r--r--src/dict2rest/vendor/github.com/julienschmidt/httprouter/.travis.yml9
-rw-r--r--src/dict2rest/vendor/github.com/julienschmidt/httprouter/LICENSE24
-rw-r--r--src/dict2rest/vendor/github.com/julienschmidt/httprouter/README.md286
-rw-r--r--src/dict2rest/vendor/github.com/julienschmidt/httprouter/path.go123
-rw-r--r--src/dict2rest/vendor/github.com/julienschmidt/httprouter/path_test.go92
-rw-r--r--src/dict2rest/vendor/github.com/julienschmidt/httprouter/router.go363
-rw-r--r--src/dict2rest/vendor/github.com/julienschmidt/httprouter/router_test.go420
-rw-r--r--src/dict2rest/vendor/github.com/julienschmidt/httprouter/tree.go562
-rw-r--r--src/dict2rest/vendor/github.com/julienschmidt/httprouter/tree_test.go635
-rw-r--r--src/dict2rest/vendor/github.com/justinas/alice/.travis.yml11
-rw-r--r--src/dict2rest/vendor/github.com/justinas/alice/LICENSE20
-rw-r--r--src/dict2rest/vendor/github.com/justinas/alice/README.md92
-rw-r--r--src/dict2rest/vendor/github.com/justinas/alice/chain.go119
-rw-r--r--src/dict2rest/vendor/github.com/justinas/alice/chain_test.go144
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/.travis.yml4
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/LICENSE19
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/README.md99
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/bench_test.go88
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/cors.go406
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/cors_test.go371
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/examples/alice/server.go24
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/examples/default/server.go19
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/examples/goji/server.go22
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/examples/martini/server.go23
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/examples/negroni/server.go26
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/examples/nethttp/server.go20
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/examples/openbar/server.go22
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/examples/xhandler/server.go24
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/utils.go70
-rw-r--r--src/dict2rest/vendor/github.com/rs/cors/utils_test.go70
-rw-r--r--src/dict2rest/vendor/github.com/rs/xhandler/.travis.yml7
-rw-r--r--src/dict2rest/vendor/github.com/rs/xhandler/LICENSE19
-rw-r--r--src/dict2rest/vendor/github.com/rs/xhandler/README.md134
-rw-r--r--src/dict2rest/vendor/github.com/rs/xhandler/chain.go93
-rw-r--r--src/dict2rest/vendor/github.com/rs/xhandler/chain_example_test.go52
-rw-r--r--src/dict2rest/vendor/github.com/rs/xhandler/chain_test.go112
-rw-r--r--src/dict2rest/vendor/github.com/rs/xhandler/middleware.go59
-rw-r--r--src/dict2rest/vendor/github.com/rs/xhandler/middleware_test.go88
-rw-r--r--src/dict2rest/vendor/github.com/rs/xhandler/xhandler.go42
-rw-r--r--src/dict2rest/vendor/github.com/rs/xhandler/xhandler_example_test.go67
-rw-r--r--src/dict2rest/vendor/github.com/rs/xhandler/xhandler_test.go61
-rw-r--r--src/dict2rest/vendor/github.com/rs/xhandler/xmux/README.md1
-rw-r--r--src/dict2rest/vendor/github.com/stretchr/graceful/.gitignore23
-rw-r--r--src/dict2rest/vendor/github.com/stretchr/graceful/LICENSE21
-rw-r--r--src/dict2rest/vendor/github.com/stretchr/graceful/README.md137
-rw-r--r--src/dict2rest/vendor/github.com/stretchr/graceful/graceful.go359
-rw-r--r--src/dict2rest/vendor/github.com/stretchr/graceful/graceful_test.go439
-rw-r--r--src/dict2rest/vendor/github.com/stretchr/graceful/tests/main.go40
48 files changed, 0 insertions, 5961 deletions
diff --git a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/.travis.yml b/src/dict2rest/vendor/github.com/julienschmidt/httprouter/.travis.yml
deleted file mode 100644
index 9a3c1a8..0000000
--- a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/.travis.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-sudo: false
-language: go
-go:
- - 1.1
- - 1.2
- - 1.3
- - 1.4
- - 1.5
- - tip
diff --git a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/LICENSE b/src/dict2rest/vendor/github.com/julienschmidt/httprouter/LICENSE
deleted file mode 100644
index b829abc..0000000
--- a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/LICENSE
+++ /dev/null
@@ -1,24 +0,0 @@
-Copyright (c) 2013 Julien Schmidt. 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.
- * The names of the contributors may not 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 JULIEN SCHMIDT 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. \ No newline at end of file
diff --git a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/README.md b/src/dict2rest/vendor/github.com/julienschmidt/httprouter/README.md
deleted file mode 100644
index 7b467f5..0000000
--- a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/README.md
+++ /dev/null
@@ -1,286 +0,0 @@
-# HttpRouter [![Build Status](https://travis-ci.org/julienschmidt/httprouter.svg?branch=master)](https://travis-ci.org/julienschmidt/httprouter) [![Coverage](http://gocover.io/_badge/github.com/julienschmidt/httprouter?0)](http://gocover.io/github.com/julienschmidt/httprouter) [![GoDoc](https://godoc.org/github.com/julienschmidt/httprouter?status.svg)](http://godoc.org/github.com/julienschmidt/httprouter)
-
-HttpRouter is a lightweight high performance HTTP request router (also called *multiplexer* or just *mux* for short) for [Go](https://golang.org/).
-
-In contrast to the [default mux][http.ServeMux] of Go's `net/http` package, this router supports variables in the routing pattern and matches against the request method. It also scales better.
-
-The router is optimized for high performance and a small memory footprint. It scales well even with very long paths and a large number of routes. A compressing dynamic trie (radix tree) structure is used for efficient matching.
-
-## Features
-
-**Only explicit matches:** With other routers, like [`http.ServeMux`][http.ServeMux], a requested URL path could match multiple patterns. Therefore they have some awkward pattern priority rules, like *longest match* or *first registered, first matched*. By design of this router, a request can only match exactly one or no route. As a result, there are also no unintended matches, which makes it great for SEO and improves the user experience.
-
-**Stop caring about trailing slashes:** Choose the URL style you like, the router automatically redirects the client if a trailing slash is missing or if there is one extra. Of course it only does so, if the new path has a handler. If you don't like it, you can [turn off this behavior](https://godoc.org/github.com/julienschmidt/httprouter#Router.RedirectTrailingSlash).
-
-**Path auto-correction:** Besides detecting the missing or additional trailing slash at no extra cost, the router can also fix wrong cases and remove superfluous path elements (like `../` or `//`). Is [CAPTAIN CAPS LOCK](http://www.urbandictionary.com/define.php?term=Captain+Caps+Lock) one of your users? HttpRouter can help him by making a case-insensitive look-up and redirecting him to the correct URL.
-
-**Parameters in your routing pattern:** Stop parsing the requested URL path, just give the path segment a name and the router delivers the dynamic value to you. Because of the design of the router, path parameters are very cheap.
-
-**Zero Garbage:** The matching and dispatching process generates zero bytes of garbage. In fact, the only heap allocations that are made, is by building the slice of the key-value pairs for path parameters. If the request path contains no parameters, not a single heap allocation is necessary.
-
-**Best Performance:** [Benchmarks speak for themselves][benchmark]. See below for technical details of the implementation.
-
-**No more server crashes:** You can set a [Panic handler][Router.PanicHandler] to deal with panics occurring during handling a HTTP request. The router then recovers and lets the `PanicHandler` log what happened and deliver a nice error page.
-
-Of course you can also set **custom [`NotFound`][Router.NotFound] and [`MethodNotAllowed`](https://godoc.org/github.com/julienschmidt/httprouter#Router.MethodNotAllowed) handlers** and [**serve static files**][Router.ServeFiles].
-
-## Usage
-
-This is just a quick introduction, view the [GoDoc](http://godoc.org/github.com/julienschmidt/httprouter) for details.
-
-Let's start with a trivial example:
-
-```go
-package main
-
-import (
- "fmt"
- "github.com/julienschmidt/httprouter"
- "net/http"
- "log"
-)
-
-func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
- fmt.Fprint(w, "Welcome!\n")
-}
-
-func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
- fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
-}
-
-func main() {
- router := httprouter.New()
- router.GET("/", Index)
- router.GET("/hello/:name", Hello)
-
- log.Fatal(http.ListenAndServe(":8080", router))
-}
-```
-
-### Named parameters
-
-As you can see, `:name` is a *named parameter*. The values are accessible via `httprouter.Params`, which is just a slice of `httprouter.Param`s. You can get the value of a parameter either by its index in the slice, or by using the `ByName(name)` method: `:name` can be retrived by `ByName("name")`.
-
-Named parameters only match a single path segment:
-
-```
-Pattern: /user/:user
-
- /user/gordon match
- /user/you match
- /user/gordon/profile no match
- /user/ no match
-```
-
-**Note:** Since this router has only explicit matches, you can not register static routes and parameters for the same path segment. For example you can not register the patterns `/user/new` and `/user/:user` for the same request method at the same time. The routing of different request methods is independent from each other.
-
-### Catch-All parameters
-
-The second type are *catch-all* parameters and have the form `*name`. Like the name suggests, they match everything. Therefore they must always be at the **end** of the pattern:
-
-```
-Pattern: /src/*filepath
-
- /src/ match
- /src/somefile.go match
- /src/subdir/somefile.go match
-```
-
-## How does it work?
-
-The router relies on a tree structure which makes heavy use of *common prefixes*, it is basically a *compact* [*prefix tree*](https://en.wikipedia.org/wiki/Trie) (or just [*Radix tree*](https://en.wikipedia.org/wiki/Radix_tree)). Nodes with a common prefix also share a common parent. Here is a short example what the routing tree for the `GET` request method could look like:
-
-```
-Priority Path Handle
-9 \ *<1>
-3 ├s nil
-2 |├earch\ *<2>
-1 |└upport\ *<3>
-2 ├blog\ *<4>
-1 | └:post nil
-1 | └\ *<5>
-2 ├about-us\ *<6>
-1 | └team\ *<7>
-1 └contact\ *<8>
-```
-
-Every `*<num>` represents the memory address of a handler function (a pointer). If you follow a path trough the tree from the root to the leaf, you get the complete route path, e.g `\blog\:post\`, where `:post` is just a placeholder ([*parameter*](#named-parameters)) for an actual post name. Unlike hash-maps, a tree structure also allows us to use dynamic parts like the `:post` parameter, since we actually match against the routing patterns instead of just comparing hashes. [As benchmarks show][benchmark], this works very well and efficient.
-
-Since URL paths have a hierarchical structure and make use only of a limited set of characters (byte values), it is very likely that there are a lot of common prefixes. This allows us to easily reduce the routing into ever smaller problems. Moreover the router manages a separate tree for every request method. For one thing it is more space efficient than holding a method->handle map in every single node, for another thing is also allows us to greatly reduce the routing problem before even starting the look-up in the prefix-tree.
-
-For even better scalability, the child nodes on each tree level are ordered by priority, where the priority is just the number of handles registered in sub nodes (children, grandchildren, and so on..). This helps in two ways:
-
-1. Nodes which are part of the most routing paths are evaluated first. This helps to make as much routes as possible to be reachable as fast as possible.
-2. It is some sort of cost compensation. The longest reachable path (highest cost) can always be evaluated first. The following scheme visualizes the tree structure. Nodes are evaluated from top to bottom and from left to right.
-
-```
-├------------
-├---------
-├-----
-├----
-├--
-├--
-└-
-```
-
-## Why doesn't this work with `http.Handler`?
-
-**It does!** The router itself implements the `http.Handler` interface. Moreover the router provides convenient [adapters for `http.Handler`][Router.Handler]s and [`http.HandlerFunc`][Router.HandlerFunc]s which allows them to be used as a [`httprouter.Handle`][Router.Handle] when registering a route. The only disadvantage is, that no parameter values can be retrieved when a `http.Handler` or `http.HandlerFunc` is used, since there is no efficient way to pass the values with the existing function parameters. Therefore [`httprouter.Handle`][Router.Handle] has a third function parameter.
-
-Just try it out for yourself, the usage of HttpRouter is very straightforward. The package is compact and minimalistic, but also probably one of the easiest routers to set up.
-
-## Where can I find Middleware *X*?
-
-This package just provides a very efficient request router with a few extra features. The router is just a [`http.Handler`][http.Handler], you can chain any http.Handler compatible middleware before the router, for example the [Gorilla handlers](http://www.gorillatoolkit.org/pkg/handlers). Or you could [just write your own](https://justinas.org/writing-http-middleware-in-go/), it's very easy!
-
-Alternatively, you could try [a web framework based on HttpRouter](#web-frameworks-based-on-httprouter).
-
-### Multi-domain / Sub-domains
-
-Here is a quick example: Does your server serve multiple domains / hosts?
-You want to use sub-domains?
-Define a router per host!
-
-```go
-// We need an object that implements the http.Handler interface.
-// Therefore we need a type for which we implement the ServeHTTP method.
-// We just use a map here, in which we map host names (with port) to http.Handlers
-type HostSwitch map[string]http.Handler
-
-// Implement the ServerHTTP method on our new type
-func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- // Check if a http.Handler is registered for the given host.
- // If yes, use it to handle the request.
- if handler := hs[r.Host]; handler != nil {
- handler.ServeHTTP(w, r)
- } else {
- // Handle host names for wich no handler is registered
- http.Error(w, "Forbidden", 403) // Or Redirect?
- }
-}
-
-func main() {
- // Initialize a router as usual
- router := httprouter.New()
- router.GET("/", Index)
- router.GET("/hello/:name", Hello)
-
- // Make a new HostSwitch and insert the router (our http handler)
- // for example.com and port 12345
- hs := make(HostSwitch)
- hs["example.com:12345"] = router
-
- // Use the HostSwitch to listen and serve on port 12345
- log.Fatal(http.ListenAndServe(":12345", hs))
-}
-```
-
-### Basic Authentication
-
-Another quick example: Basic Authentication (RFC 2617) for handles:
-
-```go
-package main
-
-import (
- "bytes"
- "encoding/base64"
- "fmt"
- "github.com/julienschmidt/httprouter"
- "net/http"
- "log"
- "strings"
-)
-
-func BasicAuth(h httprouter.Handle, user, pass []byte) httprouter.Handle {
- return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
- const basicAuthPrefix string = "Basic "
-
- // Get the Basic Authentication credentials
- auth := r.Header.Get("Authorization")
- if strings.HasPrefix(auth, basicAuthPrefix) {
- // Check credentials
- payload, err := base64.StdEncoding.DecodeString(auth[len(basicAuthPrefix):])
- if err == nil {
- pair := bytes.SplitN(payload, []byte(":"), 2)
- if len(pair) == 2 &&
- bytes.Equal(pair[0], user) &&
- bytes.Equal(pair[1], pass) {
-
- // Delegate request to the given handle
- h(w, r, ps)
- return
- }
- }
- }
-
- // Request Basic Authentication otherwise
- w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
- http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
- }
-}
-
-func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
- fmt.Fprint(w, "Not protected!\n")
-}
-
-func Protected(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
- fmt.Fprint(w, "Protected!\n")
-}
-
-func main() {
- user := []byte("gordon")
- pass := []byte("secret!")
-
- router := httprouter.New()
- router.GET("/", Index)
- router.GET("/protected/", BasicAuth(Protected, user, pass))
-
- log.Fatal(http.ListenAndServe(":8080", router))
-}
-```
-
-## Chaining with the NotFound handler
-
-**NOTE: It might be required to set [`Router.HandleMethodNotAllowed`][Router.HandleMethodNotAllowed] to `false` to avoid problems.**
-
-You can use another [`http.Handler`][http.Handler], for example another router, to handle requests which could not be matched by this router by using the [`Router.NotFound`][Router.NotFound] handler. This allows chaining.
-
-### Static files
-
-The `NotFound` handler can for example be used to serve static files from the root path `/` (like an `index.html` file along with other assets):
-
-```go
-// Serve static files from the ./public directory
-router.NotFound = http.FileServer(http.Dir("public"))
-```
-
-But this approach sidesteps the strict core rules of this router to avoid routing problems. A cleaner approach is to use a distinct sub-path for serving files, like `/static/*filepath` or `/files/*filepath`.
-
-## Web Frameworks based on HttpRouter
-
-If the HttpRouter is a bit too minimalistic for you, you might try one of the following more high-level 3rd-party web frameworks building upon the HttpRouter package:
-
-* [Ace](https://github.com/plimble/ace): Blazing fast Go Web Framework
-* [api2go](https://github.com/manyminds/api2go): A JSON API Implementation for Go
-* [Gin](https://github.com/gin-gonic/gin): Features a martini-like API with much better performance
-* [Goat](https://github.com/bahlo/goat): A minimalistic REST API server in Go
-* [Hikaru](https://github.com/najeira/hikaru): Supports standalone and Google AppEngine
-* [Hitch](https://github.com/nbio/hitch): Hitch ties httprouter, [httpcontext](https://github.com/nbio/httpcontext), and middleware up in a bow
-* [httpway](https://github.com/corneldamian/httpway): Simple middleware extension with context for httprouter and a server with gracefully shutdown support
-* [kami](https://github.com/guregu/kami): A tiny web framework using x/net/context
-* [Medeina](https://github.com/imdario/medeina): Inspired by Ruby's Roda and Cuba
-* [Neko](https://github.com/rocwong/neko): A lightweight web application framework for Golang
-* [Roxanna](https://github.com/iamthemuffinman/Roxanna): An amalgamation of httprouter, better logging, and hot reload
-* [siesta](https://github.com/VividCortex/siesta): Composable HTTP handlers with contexts
-
-[benchmark]: <https://github.com/julienschmidt/go-http-routing-benchmark>
-[http.Handler]: <https://golang.org/pkg/net/http/#Handler
-[http.ServeMux]: <https://golang.org/pkg/net/http/#ServeMux>
-[Router.Handle]: <https://godoc.org/github.com/julienschmidt/httprouter#Router.Handle>
-[Router.HandleMethodNotAllowed]: <https://godoc.org/github.com/julienschmidt/httprouter#Router.HandleMethodNotAllowed>
-[Router.Handler]: <https://godoc.org/github.com/julienschmidt/httprouter#Router.Handler>
-[Router.HandlerFunc]: <https://godoc.org/github.com/julienschmidt/httprouter#Router.HandlerFunc>
-[Router.NotFound]: <https://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound>
-[Router.PanicHandler]: <https://godoc.org/github.com/julienschmidt/httprouter#Router.PanicHandler>
-[Router.ServeFiles]: <https://godoc.org/github.com/julienschmidt/httprouter#Router.ServeFiles>
diff --git a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/path.go b/src/dict2rest/vendor/github.com/julienschmidt/httprouter/path.go
deleted file mode 100644
index 486134d..0000000
--- a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/path.go
+++ /dev/null
@@ -1,123 +0,0 @@
-// Copyright 2013 Julien Schmidt. All rights reserved.
-// Based on the path package, Copyright 2009 The Go Authors.
-// Use of this source code is governed by a BSD-style license that can be found
-// in the LICENSE file.
-
-package httprouter
-
-// CleanPath is the URL version of path.Clean, it returns a canonical URL path
-// for p, eliminating . and .. elements.
-//
-// The following rules are applied iteratively until no further processing can
-// be done:
-// 1. Replace multiple slashes with a single slash.
-// 2. Eliminate each . path name element (the current directory).
-// 3. Eliminate each inner .. path name element (the parent directory)
-// along with the non-.. element that precedes it.
-// 4. Eliminate .. elements that begin a rooted path:
-// that is, replace "/.." by "/" at the beginning of a path.
-//
-// If the result of this process is an empty string, "/" is returned
-func CleanPath(p string) string {
- // Turn empty string into "/"
- if p == "" {
- return "/"
- }
-
- n := len(p)
- var buf []byte
-
- // Invariants:
- // reading from path; r is index of next byte to process.
- // writing to buf; w is index of next byte to write.
-
- // path must start with '/'
- r := 1
- w := 1
-
- if p[0] != '/' {
- r = 0
- buf = make([]byte, n+1)
- buf[0] = '/'
- }
-
- trailing := n > 2 && p[n-1] == '/'
-
- // A bit more clunky without a 'lazybuf' like the path package, but the loop
- // gets completely inlined (bufApp). So in contrast to the path package this
- // loop has no expensive function calls (except 1x make)
-
- for r < n {
- switch {
- case p[r] == '/':
- // empty path element, trailing slash is added after the end
- r++
-
- case p[r] == '.' && r+1 == n:
- trailing = true
- r++
-
- case p[r] == '.' && p[r+1] == '/':
- // . element
- r++
-
- case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'):
- // .. element: remove to last /
- r += 2
-
- if w > 1 {
- // can backtrack
- w--
-
- if buf == nil {
- for w > 1 && p[w] != '/' {
- w--
- }
- } else {
- for w > 1 && buf[w] != '/' {
- w--
- }
- }
- }
-
- default:
- // real path element.
- // add slash if needed
- if w > 1 {
- bufApp(&buf, p, w, '/')
- w++
- }
-
- // copy element
- for r < n && p[r] != '/' {
- bufApp(&buf, p, w, p[r])
- w++
- r++
- }
- }
- }
-
- // re-append trailing slash
- if trailing && w > 1 {
- bufApp(&buf, p, w, '/')
- w++
- }
-
- if buf == nil {
- return p[:w]
- }
- return string(buf[:w])
-}
-
-// internal helper to lazily create a buffer if necessary
-func bufApp(buf *[]byte, s string, w int, c byte) {
- if *buf == nil {
- if s[w] == c {
- return
- }
-
- *buf = make([]byte, len(s))
- copy(*buf, s[:w])
- }
- (*buf)[w] = c
-}
diff --git a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/path_test.go b/src/dict2rest/vendor/github.com/julienschmidt/httprouter/path_test.go
deleted file mode 100644
index c4ceda5..0000000
--- a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/path_test.go
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2013 Julien Schmidt. All rights reserved.
-// Based on the path package, Copyright 2009 The Go Authors.
-// Use of this source code is governed by a BSD-style license that can be found
-// in the LICENSE file.
-
-package httprouter
-
-import (
- "runtime"
- "testing"
-)
-
-var cleanTests = []struct {
- path, result string
-}{
- // Already clean
- {"/", "/"},
- {"/abc", "/abc"},
- {"/a/b/c", "/a/b/c"},
- {"/abc/", "/abc/"},
- {"/a/b/c/", "/a/b/c/"},
-
- // missing root
- {"", "/"},
- {"abc", "/abc"},
- {"abc/def", "/abc/def"},
- {"a/b/c", "/a/b/c"},
-
- // Remove doubled slash
- {"//", "/"},
- {"/abc//", "/abc/"},
- {"/abc/def//", "/abc/def/"},
- {"/a/b/c//", "/a/b/c/"},
- {"/abc//def//ghi", "/abc/def/ghi"},
- {"//abc", "/abc"},
- {"///abc", "/abc"},
- {"//abc//", "/abc/"},
-
- // Remove . elements
- {".", "/"},
- {"./", "/"},
- {"/abc/./def", "/abc/def"},
- {"/./abc/def", "/abc/def"},
- {"/abc/.", "/abc/"},
-
- // Remove .. elements
- {"..", "/"},
- {"../", "/"},
- {"../../", "/"},
- {"../..", "/"},
- {"../../abc", "/abc"},
- {"/abc/def/ghi/../jkl", "/abc/def/jkl"},
- {"/abc/def/../ghi/../jkl", "/abc/jkl"},
- {"/abc/def/..", "/abc"},
- {"/abc/def/../..", "/"},
- {"/abc/def/../../..", "/"},
- {"/abc/def/../../..", "/"},
- {"/abc/def/../../../ghi/jkl/../../../mno", "/mno"},
-
- // Combinations
- {"abc/./../def", "/def"},
- {"abc//./../def", "/def"},
- {"abc/../../././../def", "/def"},
-}
-
-func TestPathClean(t *testing.T) {
- for _, test := range cleanTests {
- if s := CleanPath(test.path); s != test.result {
- t.Errorf("CleanPath(%q) = %q, want %q", test.path, s, test.result)
- }
- if s := CleanPath(test.result); s != test.result {
- t.Errorf("CleanPath(%q) = %q, want %q", test.result, s, test.result)
- }
- }
-}
-
-func TestPathCleanMallocs(t *testing.T) {
- if testing.Short() {
- t.Skip("skipping malloc count in short mode")
- }
- if runtime.GOMAXPROCS(0) > 1 {
- t.Log("skipping AllocsPerRun checks; GOMAXPROCS>1")
- return
- }
-
- for _, test := range cleanTests {
- allocs := testing.AllocsPerRun(100, func() { CleanPath(test.result) })
- if allocs > 0 {
- t.Errorf("CleanPath(%q): %v allocs, want zero", test.result, allocs)
- }
- }
-}
diff --git a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/router.go b/src/dict2rest/vendor/github.com/julienschmidt/httprouter/router.go
deleted file mode 100644
index 8b5ff34..0000000
--- a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/router.go
+++ /dev/null
@@ -1,363 +0,0 @@
-// Copyright 2013 Julien Schmidt. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be found
-// in the LICENSE file.
-
-// Package httprouter is a trie based high performance HTTP request router.
-//
-// A trivial example is:
-//
-// package main
-//
-// import (
-// "fmt"
-// "github.com/julienschmidt/httprouter"
-// "net/http"
-// "log"
-// )
-//
-// func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
-// fmt.Fprint(w, "Welcome!\n")
-// }
-//
-// func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
-// fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
-// }
-//
-// func main() {
-// router := httprouter.New()
-// router.GET("/", Index)
-// router.GET("/hello/:name", Hello)
-//
-// log.Fatal(http.ListenAndServe(":8080", router))
-// }
-//
-// The router matches incoming requests by the request method and the path.
-// If a handle is registered for this path and method, the router delegates the
-// request to that function.
-// For the methods GET, POST, PUT, PATCH and DELETE shortcut functions exist to
-// register handles, for all other methods router.Handle can be used.
-//
-// The registered path, against which the router matches incoming requests, can
-// contain two types of parameters:
-// Syntax Type
-// :name named parameter
-// *name catch-all parameter
-//
-// Named parameters are dynamic path segments. They match anything until the
-// next '/' or the path end:
-// Path: /blog/:category/:post
-//
-// Requests:
-// /blog/go/request-routers match: category="go", post="request-routers"
-// /blog/go/request-routers/ no match, but the router would redirect
-// /blog/go/ no match
-// /blog/go/request-routers/comments no match
-//
-// Catch-all parameters match anything until the path end, including the
-// directory index (the '/' before the catch-all). Since they match anything
-// until the end, catch-all parameters must always be the final path element.
-// Path: /files/*filepath
-//
-// Requests:
-// /files/ match: filepath="/"
-// /files/LICENSE match: filepath="/LICENSE"
-// /files/templates/article.html match: filepath="/templates/article.html"
-// /files no match, but the router would redirect
-//
-// The value of parameters is saved as a slice of the Param struct, consisting
-// each of a key and a value. The slice is passed to the Handle func as a third
-// parameter.
-// There are two ways to retrieve the value of a parameter:
-// // by the name of the parameter
-// user := ps.ByName("user") // defined by :user or *user
-//
-// // by the index of the parameter. This way you can also get the name (key)
-// thirdKey := ps[2].Key // the name of the 3rd parameter
-// thirdValue := ps[2].Value // the value of the 3rd parameter
-package httprouter
-
-import (
- "net/http"
-)
-
-// Handle is a function that can be registered to a route to handle HTTP
-// requests. Like http.HandlerFunc, but has a third parameter for the values of
-// wildcards (variables).
-type Handle func(http.ResponseWriter, *http.Request, Params)
-
-// Param is a single URL parameter, consisting of a key and a value.
-type Param struct {
- Key string
- Value string
-}
-
-// Params is a Param-slice, as returned by the router.
-// The slice is ordered, the first URL parameter is also the first slice value.
-// It is therefore safe to read values by the index.
-type Params []Param
-
-// ByName returns the value of the first Param which key matches the given name.
-// If no matching Param is found, an empty string is returned.
-func (ps Params) ByName(name string) string {
- for i := range ps {
- if ps[i].Key == name {
- return ps[i].Value
- }
- }
- return ""
-}
-
-// Router is a http.Handler which can be used to dispatch requests to different
-// handler functions via configurable routes
-type Router struct {
- trees map[string]*node
-
- // Enables automatic redirection if the current route can't be matched but a
- // handler for the path with (without) the trailing slash exists.
- // For example if /foo/ is requested but a route only exists for /foo, the
- // client is redirected to /foo with http status code 301 for GET requests
- // and 307 for all other request methods.
- RedirectTrailingSlash bool
-
- // If enabled, the router tries to fix the current request path, if no
- // handle is registered for it.
- // First superfluous path elements like ../ or // are removed.
- // Afterwards the router does a case-insensitive lookup of the cleaned path.
- // If a handle can be found for this route, the router makes a redirection
- // to the corrected path with status code 301 for GET requests and 307 for
- // all other request methods.
- // For example /FOO and /..//Foo could be redirected to /foo.
- // RedirectTrailingSlash is independent of this option.
- RedirectFixedPath bool
-
- // If enabled, the router checks if another method is allowed for the
- // current route, if the current request can not be routed.
- // If this is the case, the request is answered with 'Method Not Allowed'
- // and HTTP status code 405.
- // If no other Method is allowed, the request is delegated to the NotFound
- // handler.
- HandleMethodNotAllowed bool
-
- // Configurable http.Handler which is called when no matching route is
- // found. If it is not set, http.NotFound is used.
- NotFound http.Handler
-
- // Configurable http.Handler which is called when a request
- // cannot be routed and HandleMethodNotAllowed is true.
- // If it is not set, http.Error with http.StatusMethodNotAllowed is used.
- MethodNotAllowed http.Handler
-
- // Function to handle panics recovered from http handlers.
- // It should be used to generate a error page and return the http error code
- // 500 (Internal Server Error).
- // The handler can be used to keep your server from crashing because of
- // unrecovered panics.
- PanicHandler func(http.ResponseWriter, *http.Request, interface{})
-}
-
-// Make sure the Router conforms with the http.Handler interface
-var _ http.Handler = New()
-
-// New returns a new initialized Router.
-// Path auto-correction, including trailing slashes, is enabled by default.
-func New() *Router {
- return &Router{
- RedirectTrailingSlash: true,
- RedirectFixedPath: true,
- HandleMethodNotAllowed: true,
- }
-}
-
-// GET is a shortcut for router.Handle("GET", path, handle)
-func (r *Router) GET(path string, handle Handle) {
- r.Handle("GET", path, handle)
-}
-
-// HEAD is a shortcut for router.Handle("HEAD", path, handle)
-func (r *Router) HEAD(path string, handle Handle) {
- r.Handle("HEAD", path, handle)
-}
-
-// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)
-func (r *Router) OPTIONS(path string, handle Handle) {
- r.Handle("OPTIONS", path, handle)
-}
-
-// POST is a shortcut for router.Handle("POST", path, handle)
-func (r *Router) POST(path string, handle Handle) {
- r.Handle("POST", path, handle)
-}
-
-// PUT is a shortcut for router.Handle("PUT", path, handle)
-func (r *Router) PUT(path string, handle Handle) {
- r.Handle("PUT", path, handle)
-}
-
-// PATCH is a shortcut for router.Handle("PATCH", path, handle)
-func (r *Router) PATCH(path string, handle Handle) {
- r.Handle("PATCH", path, handle)
-}
-
-// DELETE is a shortcut for router.Handle("DELETE", path, handle)
-func (r *Router) DELETE(path string, handle Handle) {
- r.Handle("DELETE", path, handle)
-}
-
-// Handle registers a new request handle with the given path and method.
-//
-// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
-// functions can be used.
-//
-// This function is intended for bulk loading and to allow the usage of less
-// frequently used, non-standardized or custom methods (e.g. for internal
-// communication with a proxy).
-func (r *Router) Handle(method, path string, handle Handle) {
- if path[0] != '/' {
- panic("path must begin with '/' in path '" + path + "'")
- }
-
- if r.trees == nil {
- r.trees = make(map[string]*node)
- }
-
- root := r.trees[method]
- if root == nil {
- root = new(node)
- r.trees[method] = root
- }
-
- root.addRoute(path, handle)
-}
-
-// Handler is an adapter which allows the usage of an http.Handler as a
-// request handle.
-func (r *Router) Handler(method, path string, handler http.Handler) {
- r.Handle(method, path,
- func(w http.ResponseWriter, req *http.Request, _ Params) {
- handler.ServeHTTP(w, req)
- },
- )
-}
-
-// HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a
-// request handle.
-func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc) {
- r.Handler(method, path, handler)
-}
-
-// ServeFiles serves files from the given file system root.
-// The path must end with "/*filepath", files are then served from the local
-// path /defined/root/dir/*filepath.
-// For example if root is "/etc" and *filepath is "passwd", the local file
-// "/etc/passwd" would be served.
-// Internally a http.FileServer is used, therefore http.NotFound is used instead
-// of the Router's NotFound handler.
-// To use the operating system's file system implementation,
-// use http.Dir:
-// router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
-func (r *Router) ServeFiles(path string, root http.FileSystem) {
- if len(path) < 10 || path[len(path)-10:] != "/*filepath" {
- panic("path must end with /*filepath in path '" + path + "'")
- }
-
- fileServer := http.FileServer(root)
-
- r.GET(path, func(w http.ResponseWriter, req *http.Request, ps Params) {
- req.URL.Path = ps.ByName("filepath")
- fileServer.ServeHTTP(w, req)
- })
-}
-
-func (r *Router) recv(w http.ResponseWriter, req *http.Request) {
- if rcv := recover(); rcv != nil {
- r.PanicHandler(w, req, rcv)
- }
-}
-
-// Lookup allows the manual lookup of a method + path combo.
-// This is e.g. useful to build a framework around this router.
-// If the path was found, it returns the handle function and the path parameter
-// values. Otherwise the third return value indicates whether a redirection to
-// the same path with an extra / without the trailing slash should be performed.
-func (r *Router) Lookup(method, path string) (Handle, Params, bool) {
- if root := r.trees[method]; root != nil {
- return root.getValue(path)
- }
- return nil, nil, false
-}
-
-// ServeHTTP makes the router implement the http.Handler interface.
-func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
- if r.PanicHandler != nil {
- defer r.recv(w, req)
- }
-
- if root := r.trees[req.Method]; root != nil {
- path := req.URL.Path
-
- if handle, ps, tsr := root.getValue(path); handle != nil {
- handle(w, req, ps)
- return
- } else if req.Method != "CONNECT" && path != "/" {
- code := 301 // Permanent redirect, request with GET method
- if req.Method != "GET" {
- // Temporary redirect, request with same method
- // As of Go 1.3, Go does not support status code 308.
- code = 307
- }
-
- if tsr && r.RedirectTrailingSlash {
- if len(path) > 1 && path[len(path)-1] == '/' {
- req.URL.Path = path[:len(path)-1]
- } else {
- req.URL.Path = path + "/"
- }
- http.Redirect(w, req, req.URL.String(), code)
- return
- }
-
- // Try to fix the request path
- if r.RedirectFixedPath {
- fixedPath, found := root.findCaseInsensitivePath(
- CleanPath(path),
- r.RedirectTrailingSlash,
- )
- if found {
- req.URL.Path = string(fixedPath)
- http.Redirect(w, req, req.URL.String(), code)
- return
- }
- }
- }
- }
-
- // Handle 405
- if r.HandleMethodNotAllowed {
- for method := range r.trees {
- // Skip the requested method - we already tried this one
- if method == req.Method {
- continue
- }
-
- handle, _, _ := r.trees[method].getValue(req.URL.Path)
- if handle != nil {
- if r.MethodNotAllowed != nil {
- r.MethodNotAllowed.ServeHTTP(w, req)
- } else {
- http.Error(w,
- http.StatusText(http.StatusMethodNotAllowed),
- http.StatusMethodNotAllowed,
- )
- }
- return
- }
- }
- }
-
- // Handle 404
- if r.NotFound != nil {
- r.NotFound.ServeHTTP(w, req)
- } else {
- http.NotFound(w, req)
- }
-}
diff --git a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/router_test.go b/src/dict2rest/vendor/github.com/julienschmidt/httprouter/router_test.go
deleted file mode 100644
index e3141bd..0000000
--- a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/router_test.go
+++ /dev/null
@@ -1,420 +0,0 @@
-// Copyright 2013 Julien Schmidt. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be found
-// in the LICENSE file.
-
-package httprouter
-
-import (
- "errors"
- "fmt"
- "net/http"
- "net/http/httptest"
- "reflect"
- "testing"
-)
-
-type mockResponseWriter struct{}
-
-func (m *mockResponseWriter) Header() (h http.Header) {
- return http.Header{}
-}
-
-func (m *mockResponseWriter) Write(p []byte) (n int, err error) {
- return len(p), nil
-}
-
-func (m *mockResponseWriter) WriteString(s string) (n int, err error) {
- return len(s), nil
-}
-
-func (m *mockResponseWriter) WriteHeader(int) {}
-
-func TestParams(t *testing.T) {
- ps := Params{
- Param{"param1", "value1"},
- Param{"param2", "value2"},
- Param{"param3", "value3"},
- }
- for i := range ps {
- if val := ps.ByName(ps[i].Key); val != ps[i].Value {
- t.Errorf("Wrong value for %s: Got %s; Want %s", ps[i].Key, val, ps[i].Value)
- }
- }
- if val := ps.ByName("noKey"); val != "" {
- t.Errorf("Expected empty string for not found key; got: %s", val)
- }
-}
-
-func TestRouter(t *testing.T) {
- router := New()
-
- routed := false
- router.Handle("GET", "/user/:name", func(w http.ResponseWriter, r *http.Request, ps Params) {
- routed = true
- want := Params{Param{"name", "gopher"}}
- if !reflect.DeepEqual(ps, want) {
- t.Fatalf("wrong wildcard values: want %v, got %v", want, ps)
- }
- })
-
- w := new(mockResponseWriter)
-
- req, _ := http.NewRequest("GET", "/user/gopher", nil)
- router.ServeHTTP(w, req)
-
- if !routed {
- t.Fatal("routing failed")
- }
-}
-
-type handlerStruct struct {
- handeled *bool
-}
-
-func (h handlerStruct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- *h.handeled = true
-}
-
-func TestRouterAPI(t *testing.T) {
- var get, head, options, post, put, patch, delete, handler, handlerFunc bool
-
- httpHandler := handlerStruct{&handler}
-
- router := New()
- router.GET("/GET", func(w http.ResponseWriter, r *http.Request, _ Params) {
- get = true
- })
- router.HEAD("/GET", func(w http.ResponseWriter, r *http.Request, _ Params) {
- head = true
- })
- router.OPTIONS("/GET", func(w http.ResponseWriter, r *http.Request, _ Params) {
- options = true
- })
- router.POST("/POST", func(w http.ResponseWriter, r *http.Request, _ Params) {
- post = true
- })
- router.PUT("/PUT", func(w http.ResponseWriter, r *http.Request, _ Params) {
- put = true
- })
- router.PATCH("/PATCH", func(w http.ResponseWriter, r *http.Request, _ Params) {
- patch = true
- })
- router.DELETE("/DELETE", func(w http.ResponseWriter, r *http.Request, _ Params) {
- delete = true
- })
- router.Handler("GET", "/Handler", httpHandler)
- router.HandlerFunc("GET", "/HandlerFunc", func(w http.ResponseWriter, r *http.Request) {
- handlerFunc = true
- })
-
- w := new(mockResponseWriter)
-
- r, _ := http.NewRequest("GET", "/GET", nil)
- router.ServeHTTP(w, r)
- if !get {
- t.Error("routing GET failed")
- }
-
- r, _ = http.NewRequest("HEAD", "/GET", nil)
- router.ServeHTTP(w, r)
- if !head {
- t.Error("routing HEAD failed")
- }
-
- r, _ = http.NewRequest("OPTIONS", "/GET", nil)
- router.ServeHTTP(w, r)
- if !options {
- t.Error("routing OPTIONS failed")
- }
-
- r, _ = http.NewRequest("POST", "/POST", nil)
- router.ServeHTTP(w, r)
- if !post {
- t.Error("routing POST failed")
- }
-
- r, _ = http.NewRequest("PUT", "/PUT", nil)
- router.ServeHTTP(w, r)
- if !put {
- t.Error("routing PUT failed")
- }
-
- r, _ = http.NewRequest("PATCH", "/PATCH", nil)
- router.ServeHTTP(w, r)
- if !patch {
- t.Error("routing PATCH failed")
- }
-
- r, _ = http.NewRequest("DELETE", "/DELETE", nil)
- router.ServeHTTP(w, r)
- if !delete {
- t.Error("routing DELETE failed")
- }
-
- r, _ = http.NewRequest("GET", "/Handler", nil)
- router.ServeHTTP(w, r)
- if !handler {
- t.Error("routing Handler failed")
- }
-
- r, _ = http.NewRequest("GET", "/HandlerFunc", nil)
- router.ServeHTTP(w, r)
- if !handlerFunc {
- t.Error("routing HandlerFunc failed")
- }
-}
-
-func TestRouterRoot(t *testing.T) {
- router := New()
- recv := catchPanic(func() {
- router.GET("noSlashRoot", nil)
- })
- if recv == nil {
- t.Fatal("registering path not beginning with '/' did not panic")
- }
-}
-
-func TestRouterChaining(t *testing.T) {
- router1 := New()
- router2 := New()
- router1.NotFound = router2
-
- fooHit := false
- router1.POST("/foo", func(w http.ResponseWriter, req *http.Request, _ Params) {
- fooHit = true
- w.WriteHeader(http.StatusOK)
- })
-
- barHit := false
- router2.POST("/bar", func(w http.ResponseWriter, req *http.Request, _ Params) {
- barHit = true
- w.WriteHeader(http.StatusOK)
- })
-
- r, _ := http.NewRequest("POST", "/foo", nil)
- w := httptest.NewRecorder()
- router1.ServeHTTP(w, r)
- if !(w.Code == http.StatusOK && fooHit) {
- t.Errorf("Regular routing failed with router chaining.")
- t.FailNow()
- }
-
- r, _ = http.NewRequest("POST", "/bar", nil)
- w = httptest.NewRecorder()
- router1.ServeHTTP(w, r)
- if !(w.Code == http.StatusOK && barHit) {
- t.Errorf("Chained routing failed with router chaining.")
- t.FailNow()
- }
-
- r, _ = http.NewRequest("POST", "/qax", nil)
- w = httptest.NewRecorder()
- router1.ServeHTTP(w, r)
- if !(w.Code == http.StatusNotFound) {
- t.Errorf("NotFound behavior failed with router chaining.")
- t.FailNow()
- }
-}
-
-func TestRouterNotAllowed(t *testing.T) {
- handlerFunc := func(_ http.ResponseWriter, _ *http.Request, _ Params) {}
-
- router := New()
- router.POST("/path", handlerFunc)
-
- // Test not allowed
- r, _ := http.NewRequest("GET", "/path", nil)
- w := httptest.NewRecorder()
- router.ServeHTTP(w, r)
- if !(w.Code == http.StatusMethodNotAllowed) {
- t.Errorf("NotAllowed handling failed: Code=%d, Header=%v", w.Code, w.Header())
- }
-
- w = httptest.NewRecorder()
- responseText := "custom method"
- router.MethodNotAllowed = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
- w.WriteHeader(http.StatusTeapot)
- w.Write([]byte(responseText))
- })
- router.ServeHTTP(w, r)
- if got := w.Body.String(); !(got == responseText) {
- t.Errorf("unexpected response got %q want %q", got, responseText)
- }
- if w.Code != http.StatusTeapot {
- t.Errorf("unexpected response code %d want %d", w.Code, http.StatusTeapot)
- }
-}
-
-func TestRouterNotFound(t *testing.T) {
- handlerFunc := func(_ http.ResponseWriter, _ *http.Request, _ Params) {}
-
- router := New()
- router.GET("/path", handlerFunc)
- router.GET("/dir/", handlerFunc)
- router.GET("/", handlerFunc)
-
- testRoutes := []struct {
- route string
- code int
- header string
- }{
- {"/path/", 301, "map[Location:[/path]]"}, // TSR -/
- {"/dir", 301, "map[Location:[/dir/]]"}, // TSR +/
- {"", 301, "map[Location:[/]]"}, // TSR +/
- {"/PATH", 301, "map[Location:[/path]]"}, // Fixed Case
- {"/DIR/", 301, "map[Location:[/dir/]]"}, // Fixed Case
- {"/PATH/", 301, "map[Location:[/path]]"}, // Fixed Case -/
- {"/DIR", 301, "map[Location:[/dir/]]"}, // Fixed Case +/
- {"/../path", 301, "map[Location:[/path]]"}, // CleanPath
- {"/nope", 404, ""}, // NotFound
- }
- for _, tr := range testRoutes {
- r, _ := http.NewRequest("GET", tr.route, nil)
- w := httptest.NewRecorder()
- router.ServeHTTP(w, r)
- if !(w.Code == tr.code && (w.Code == 404 || fmt.Sprint(w.Header()) == tr.header)) {
- t.Errorf("NotFound handling route %s failed: Code=%d, Header=%v", tr.route, w.Code, w.Header())
- }
- }
-
- // Test custom not found handler
- var notFound bool
- router.NotFound = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
- rw.WriteHeader(404)
- notFound = true
- })
- r, _ := http.NewRequest("GET", "/nope", nil)
- w := httptest.NewRecorder()
- router.ServeHTTP(w, r)
- if !(w.Code == 404 && notFound == true) {
- t.Errorf("Custom NotFound handler failed: Code=%d, Header=%v", w.Code, w.Header())
- }
-
- // Test other method than GET (want 307 instead of 301)
- router.PATCH("/path", handlerFunc)
- r, _ = http.NewRequest("PATCH", "/path/", nil)
- w = httptest.NewRecorder()
- router.ServeHTTP(w, r)
- if !(w.Code == 307 && fmt.Sprint(w.Header()) == "map[Location:[/path]]") {
- t.Errorf("Custom NotFound handler failed: Code=%d, Header=%v", w.Code, w.Header())
- }
-
- // Test special case where no node for the prefix "/" exists
- router = New()
- router.GET("/a", handlerFunc)
- r, _ = http.NewRequest("GET", "/", nil)
- w = httptest.NewRecorder()
- router.ServeHTTP(w, r)
- if !(w.Code == 404) {
- t.Errorf("NotFound handling route / failed: Code=%d", w.Code)
- }
-}
-
-func TestRouterPanicHandler(t *testing.T) {
- router := New()
- panicHandled := false
-
- router.PanicHandler = func(rw http.ResponseWriter, r *http.Request, p interface{}) {
- panicHandled = true
- }
-
- router.Handle("PUT", "/user/:name", func(_ http.ResponseWriter, _ *http.Request, _ Params) {
- panic("oops!")
- })
-
- w := new(mockResponseWriter)
- req, _ := http.NewRequest("PUT", "/user/gopher", nil)
-
- defer func() {
- if rcv := recover(); rcv != nil {
- t.Fatal("handling panic failed")
- }
- }()
-
- router.ServeHTTP(w, req)
-
- if !panicHandled {
- t.Fatal("simulating failed")
- }
-}
-
-func TestRouterLookup(t *testing.T) {
- routed := false
- wantHandle := func(_ http.ResponseWriter, _ *http.Request, _ Params) {
- routed = true
- }
- wantParams := Params{Param{"name", "gopher"}}
-
- router := New()
-
- // try empty router first
- handle, _, tsr := router.Lookup("GET", "/nope")
- if handle != nil {
- t.Fatalf("Got handle for unregistered pattern: %v", handle)
- }
- if tsr {
- t.Error("Got wrong TSR recommendation!")
- }
-
- // insert route and try again
- router.GET("/user/:name", wantHandle)
-
- handle, params, tsr := router.Lookup("GET", "/user/gopher")
- if handle == nil {
- t.Fatal("Got no handle!")
- } else {
- handle(nil, nil, nil)
- if !routed {
- t.Fatal("Routing failed!")
- }
- }
-
- if !reflect.DeepEqual(params, wantParams) {
- t.Fatalf("Wrong parameter values: want %v, got %v", wantParams, params)
- }
-
- handle, _, tsr = router.Lookup("GET", "/user/gopher/")
- if handle != nil {
- t.Fatalf("Got handle for unregistered pattern: %v", handle)
- }
- if !tsr {
- t.Error("Got no TSR recommendation!")
- }
-
- handle, _, tsr = router.Lookup("GET", "/nope")
- if handle != nil {
- t.Fatalf("Got handle for unregistered pattern: %v", handle)
- }
- if tsr {
- t.Error("Got wrong TSR recommendation!")
- }
-}
-
-type mockFileSystem struct {
- opened bool
-}
-
-func (mfs *mockFileSystem) Open(name string) (http.File, error) {
- mfs.opened = true
- return nil, errors.New("this is just a mock")
-}
-
-func TestRouterServeFiles(t *testing.T) {
- router := New()
- mfs := &mockFileSystem{}
-
- recv := catchPanic(func() {
- router.ServeFiles("/noFilepath", mfs)
- })
- if recv == nil {
- t.Fatal("registering path not ending with '*filepath' did not panic")
- }
-
- router.ServeFiles("/*filepath", mfs)
- w := new(mockResponseWriter)
- r, _ := http.NewRequest("GET", "/favicon.ico", nil)
- router.ServeHTTP(w, r)
- if !mfs.opened {
- t.Error("serving file failed")
- }
-}
diff --git a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/tree.go b/src/dict2rest/vendor/github.com/julienschmidt/httprouter/tree.go
deleted file mode 100644
index faf5fdc..0000000
--- a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/tree.go
+++ /dev/null
@@ -1,562 +0,0 @@
-// Copyright 2013 Julien Schmidt. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be found
-// in the LICENSE file.
-
-package httprouter
-
-import (
- "strings"
- "unicode"
-)
-
-func min(a, b int) int {
- if a <= b {
- return a
- }
- return b
-}
-
-func countParams(path string) uint8 {
- var n uint
- for i := 0; i < len(path); i++ {
- if path[i] != ':' && path[i] != '*' {
- continue
- }
- n++
- }
- if n >= 255 {
- return 255
- }
- return uint8(n)
-}
-
-type nodeType uint8
-
-const (
- static nodeType = iota // default
- root
- param
- catchAll
-)
-
-type node struct {
- path string
- wildChild bool
- nType nodeType
- maxParams uint8
- indices string
- children []*node
- handle Handle
- priority uint32
-}
-
-// increments priority of the given child and reorders if necessary
-func (n *node) incrementChildPrio(pos int) int {
- n.children[pos].priority++
- prio := n.children[pos].priority
-
- // adjust position (move to front)
- newPos := pos
- for newPos > 0 && n.children[newPos-1].priority < prio {
- // swap node positions
- tmpN := n.children[newPos-1]
- n.children[newPos-1] = n.children[newPos]
- n.children[newPos] = tmpN
-
- newPos--
- }
-
- // build new index char string
- if newPos != pos {
- n.indices = n.indices[:newPos] + // unchanged prefix, might be empty
- n.indices[pos:pos+1] + // the index char we move
- n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos'
- }
-
- return newPos
-}
-
-// addRoute adds a node with the given handle to the path.
-// Not concurrency-safe!
-func (n *node) addRoute(path string, handle Handle) {
- fullPath := path
- n.priority++
- numParams := countParams(path)
-
- // non-empty tree
- if len(n.path) > 0 || len(n.children) > 0 {
- walk:
- for {
- // Update maxParams of the current node
- if numParams > n.maxParams {
- n.maxParams = numParams
- }
-
- // Find the longest common prefix.
- // This also implies that the common prefix contains no ':' or '*'
- // since the existing key can't contain those chars.
- i := 0
- max := min(len(path), len(n.path))
- for i < max && path[i] == n.path[i] {
- i++
- }
-
- // Split edge
- if i < len(n.path) {
- child := node{
- path: n.path[i:],
- wildChild: n.wildChild,
- indices: n.indices,
- children: n.children,
- handle: n.handle,
- priority: n.priority - 1,
- }
-
- // Update maxParams (max of all children)
- for i := range child.children {
- if child.children[i].maxParams > child.maxParams {
- child.maxParams = child.children[i].maxParams
- }
- }
-
- n.children = []*node{&child}
- // []byte for proper unicode char conversion, see #65
- n.indices = string([]byte{n.path[i]})
- n.path = path[:i]
- n.handle = nil
- n.wildChild = false
- }
-
- // Make new node a child of this node
- if i < len(path) {
- path = path[i:]
-
- if n.wildChild {
- n = n.children[0]
- n.priority++
-
- // Update maxParams of the child node
- if numParams > n.maxParams {
- n.maxParams = numParams
- }
- numParams--
-
- // Check if the wildcard matches
- if len(path) >= len(n.path) && n.path == path[:len(n.path)] {
- // check for longer wildcard, e.g. :name and :names
- if len(n.path) >= len(path) || path[len(n.path)] == '/' {
- continue walk
- }
- }
-
- panic("path segment '" + path +
- "' conflicts with existing wildcard '" + n.path +
- "' in path '" + fullPath + "'")
- }
-
- c := path[0]
-
- // slash after param
- if n.nType == param && c == '/' && len(n.children) == 1 {
- n = n.children[0]
- n.priority++
- continue walk
- }
-
- // Check if a child with the next path byte exists
- for i := 0; i < len(n.indices); i++ {
- if c == n.indices[i] {
- i = n.incrementChildPrio(i)
- n = n.children[i]
- continue walk
- }
- }
-
- // Otherwise insert it
- if c != ':' && c != '*' {
- // []byte for proper unicode char conversion, see #65
- n.indices += string([]byte{c})
- child := &node{
- maxParams: numParams,
- }
- n.children = append(n.children, child)
- n.incrementChildPrio(len(n.indices) - 1)
- n = child
- }
- n.insertChild(numParams, path, fullPath, handle)
- return
-
- } else if i == len(path) { // Make node a (in-path) leaf
- if n.handle != nil {
- panic("a handle is already registered for path '" + fullPath + "'")
- }
- n.handle = handle
- }
- return
- }
- } else { // Empty tree
- n.insertChild(numParams, path, fullPath, handle)
- n.nType = root
- }
-}
-
-func (n *node) insertChild(numParams uint8, path, fullPath string, handle Handle) {
- var offset int // already handled bytes of the path
-
- // find prefix until first wildcard (beginning with ':'' or '*'')
- for i, max := 0, len(path); numParams > 0; i++ {
- c := path[i]
- if c != ':' && c != '*' {
- continue
- }
-
- // find wildcard end (either '/' or path end)
- end := i + 1
- for end < max && path[end] != '/' {
- switch path[end] {
- // the wildcard name must not contain ':' and '*'
- case ':', '*':
- panic("only one wildcard per path segment is allowed, has: '" +
- path[i:] + "' in path '" + fullPath + "'")
- default:
- end++
- }
- }
-
- // check if this Node existing children which would be
- // unreachable if we insert the wildcard here
- if len(n.children) > 0 {
- panic("wildcard route '" + path[i:end] +
- "' conflicts with existing children in path '" + fullPath + "'")
- }
-
- // check if the wildcard has a name
- if end-i < 2 {
- panic("wildcards must be named with a non-empty name in path '" + fullPath + "'")
- }
-
- if c == ':' { // param
- // split path at the beginning of the wildcard
- if i > 0 {
- n.path = path[offset:i]
- offset = i
- }
-
- child := &node{
- nType: param,
- maxParams: numParams,
- }
- n.children = []*node{child}
- n.wildChild = true
- n = child
- n.priority++
- numParams--
-
- // if the path doesn't end with the wildcard, then there
- // will be another non-wildcard subpath starting with '/'
- if end < max {
- n.path = path[offset:end]
- offset = end
-
- child := &node{
- maxParams: numParams,
- priority: 1,
- }
- n.children = []*node{child}
- n = child
- }
-
- } else { // catchAll
- if end != max || numParams > 1 {
- panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'")
- }
-
- if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {
- panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'")
- }
-
- // currently fixed width 1 for '/'
- i--
- if path[i] != '/' {
- panic("no / before catch-all in path '" + fullPath + "'")
- }
-
- n.path = path[offset:i]
-
- // first node: catchAll node with empty path
- child := &node{
- wildChild: true,
- nType: catchAll,
- maxParams: 1,
- }
- n.children = []*node{child}
- n.indices = string(path[i])
- n = child
- n.priority++
-
- // second node: node holding the variable
- child = &node{
- path: path[i:],
- nType: catchAll,
- maxParams: 1,
- handle: handle,
- priority: 1,
- }
- n.children = []*node{child}
-
- return
- }
- }
-
- // insert remaining path part and handle to the leaf
- n.path = path[offset:]
- n.handle = handle
-}
-
-// Returns the handle registered with the given path (key). The values of
-// wildcards are saved to a map.
-// If no handle can be found, a TSR (trailing slash redirect) recommendation is
-// made if a handle exists with an extra (without the) trailing slash for the
-// given path.
-func (n *node) getValue(path string) (handle Handle, p Params, tsr bool) {
-walk: // Outer loop for walking the tree
- for {
- if len(path) > len(n.path) {
- if path[:len(n.path)] == n.path {
- path = path[len(n.path):]
- // If this node does not have a wildcard (param or catchAll)
- // child, we can just look up the next child node and continue
- // to walk down the tree
- if !n.wildChild {
- c := path[0]
- for i := 0; i < len(n.indices); i++ {
- if c == n.indices[i] {
- n = n.children[i]
- continue walk
- }
- }
-
- // Nothing found.
- // We can recommend to redirect to the same URL without a
- // trailing slash if a leaf exists for that path.
- tsr = (path == "/" && n.handle != nil)
- return
-
- }
-
- // handle wildcard child
- n = n.children[0]
- switch n.nType {
- case param:
- // find param end (either '/' or path end)
- end := 0
- for end < len(path) && path[end] != '/' {
- end++
- }
-
- // save param value
- if p == nil {
- // lazy allocation
- p = make(Params, 0, n.maxParams)
- }
- i := len(p)
- p = p[:i+1] // expand slice within preallocated capacity
- p[i].Key = n.path[1:]
- p[i].Value = path[:end]
-
- // we need to go deeper!
- if end < len(path) {
- if len(n.children) > 0 {
- path = path[end:]
- n = n.children[0]
- continue walk
- }
-
- // ... but we can't
- tsr = (len(path) == end+1)
- return
- }
-
- if handle = n.handle; handle != nil {
- return
- } else if len(n.children) == 1 {
- // No handle found. Check if a handle for this path + a
- // trailing slash exists for TSR recommendation
- n = n.children[0]
- tsr = (n.path == "/" && n.handle != nil)
- }
-
- return
-
- case catchAll:
- // save param value
- if p == nil {
- // lazy allocation
- p = make(Params, 0, n.maxParams)
- }
- i := len(p)
- p = p[:i+1] // expand slice within preallocated capacity
- p[i].Key = n.path[2:]
- p[i].Value = path
-
- handle = n.handle
- return
-
- default:
- panic("invalid node type")
- }
- }
- } else if path == n.path {
- // We should have reached the node containing the handle.
- // Check if this node has a handle registered.
- if handle = n.handle; handle != nil {
- return
- }
-
- if path == "/" && n.wildChild && n.nType != root {
- tsr = true
- return
- }
-
- // No handle found. Check if a handle for this path + a
- // trailing slash exists for trailing slash recommendation
- for i := 0; i < len(n.indices); i++ {
- if n.indices[i] == '/' {
- n = n.children[i]
- tsr = (len(n.path) == 1 && n.handle != nil) ||
- (n.nType == catchAll && n.children[0].handle != nil)
- return
- }
- }
-
- return
- }
-
- // Nothing found. We can recommend to redirect to the same URL with an
- // extra trailing slash if a leaf exists for that path
- tsr = (path == "/") ||
- (len(n.path) == len(path)+1 && n.path[len(path)] == '/' &&
- path == n.path[:len(n.path)-1] && n.handle != nil)
- return
- }
-}
-
-// Makes a case-insensitive lookup of the given path and tries to find a handler.
-// It can optionally also fix trailing slashes.
-// It returns the case-corrected path and a bool indicating whether the lookup
-// was successful.
-func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPath []byte, found bool) {
- ciPath = make([]byte, 0, len(path)+1) // preallocate enough memory
-
- // Outer loop for walking the tree
- for len(path) >= len(n.path) && strings.ToLower(path[:len(n.path)]) == strings.ToLower(n.path) {
- path = path[len(n.path):]
- ciPath = append(ciPath, n.path...)
-
- if len(path) > 0 {
- // If this node does not have a wildcard (param or catchAll) child,
- // we can just look up the next child node and continue to walk down
- // the tree
- if !n.wildChild {
- r := unicode.ToLower(rune(path[0]))
- for i, index := range n.indices {
- // must use recursive approach since both index and
- // ToLower(index) could exist. We must check both.
- if r == unicode.ToLower(index) {
- out, found := n.children[i].findCaseInsensitivePath(path, fixTrailingSlash)
- if found {
- return append(ciPath, out...), true
- }
- }
- }
-
- // Nothing found. We can recommend to redirect to the same URL
- // without a trailing slash if a leaf exists for that path
- found = (fixTrailingSlash && path == "/" && n.handle != nil)
- return
- }
-
- n = n.children[0]
- switch n.nType {
- case param:
- // find param end (either '/' or path end)
- k := 0
- for k < len(path) && path[k] != '/' {
- k++
- }
-
- // add param value to case insensitive path
- ciPath = append(ciPath, path[:k]...)
-
- // we need to go deeper!
- if k < len(path) {
- if len(n.children) > 0 {
- path = path[k:]
- n = n.children[0]
- continue
- }
-
- // ... but we can't
- if fixTrailingSlash && len(path) == k+1 {
- return ciPath, true
- }
- return
- }
-
- if n.handle != nil {
- return ciPath, true
- } else if fixTrailingSlash && len(n.children) == 1 {
- // No handle found. Check if a handle for this path + a
- // trailing slash exists
- n = n.children[0]
- if n.path == "/" && n.handle != nil {
- return append(ciPath, '/'), true
- }
- }
- return
-
- case catchAll:
- return append(ciPath, path...), true
-
- default:
- panic("invalid node type")
- }
- } else {
- // We should have reached the node containing the handle.
- // Check if this node has a handle registered.
- if n.handle != nil {
- return ciPath, true
- }
-
- // No handle found.
- // Try to fix the path by adding a trailing slash
- if fixTrailingSlash {
- for i := 0; i < len(n.indices); i++ {
- if n.indices[i] == '/' {
- n = n.children[i]
- if (len(n.path) == 1 && n.handle != nil) ||
- (n.nType == catchAll && n.children[0].handle != nil) {
- return append(ciPath, '/'), true
- }
- return
- }
- }
- }
- return
- }
- }
-
- // Nothing found.
- // Try to fix the path by adding / removing a trailing slash
- if fixTrailingSlash {
- if path == "/" {
- return ciPath, true
- }
- if len(path)+1 == len(n.path) && n.path[len(path)] == '/' &&
- strings.ToLower(path) == strings.ToLower(n.path[:len(path)]) &&
- n.handle != nil {
- return append(ciPath, n.path...), true
- }
- }
- return
-}
diff --git a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/tree_test.go b/src/dict2rest/vendor/github.com/julienschmidt/httprouter/tree_test.go
deleted file mode 100644
index 46d3299..0000000
--- a/src/dict2rest/vendor/github.com/julienschmidt/httprouter/tree_test.go
+++ /dev/null
@@ -1,635 +0,0 @@
-// Copyright 2013 Julien Schmidt. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be found
-// in the LICENSE file.
-
-package httprouter
-
-import (
- "fmt"
- "net/http"
- "reflect"
- "strings"
- "testing"
-)
-
-func printChildren(n *node, prefix string) {
- fmt.Printf(" %02d:%02d %s%s[%d] %v %t %d \r\n", n.priority, n.maxParams, prefix, n.path, len(n.children), n.handle, n.wildChild, n.nType)
- for l := len(n.path); l > 0; l-- {
- prefix += " "
- }
- for _, child := range n.children {
- printChildren(child, prefix)
- }
-}
-
-// Used as a workaround since we can't compare functions or their adresses
-var fakeHandlerValue string
-
-func fakeHandler(val string) Handle {
- return func(http.ResponseWriter, *http.Request, Params) {
- fakeHandlerValue = val
- }
-}
-
-type testRequests []struct {
- path string
- nilHandler bool
- route string
- ps Params
-}
-
-func checkRequests(t *testing.T, tree *node, requests testRequests) {
- for _, request := range requests {
- handler, ps, _ := tree.getValue(request.path)
-
- if handler == nil {
- if !request.nilHandler {
- t.Errorf("handle mismatch for route '%s': Expected non-nil handle", request.path)
- }
- } else if request.nilHandler {
- t.Errorf("handle mismatch for route '%s': Expected nil handle", request.path)
- } else {
- handler(nil, nil, nil)
- if fakeHandlerValue != request.route {
- t.Errorf("handle mismatch for route '%s': Wrong handle (%s != %s)", request.path, fakeHandlerValue, request.route)
- }
- }
-
- if !reflect.DeepEqual(ps, request.ps) {
- t.Errorf("Params mismatch for route '%s'", request.path)
- }
- }
-}
-
-func checkPriorities(t *testing.T, n *node) uint32 {
- var prio uint32
- for i := range n.children {
- prio += checkPriorities(t, n.children[i])
- }
-
- if n.handle != nil {
- prio++
- }
-
- if n.priority != prio {
- t.Errorf(
- "priority mismatch for node '%s': is %d, should be %d",
- n.path, n.priority, prio,
- )
- }
-
- return prio
-}
-
-func checkMaxParams(t *testing.T, n *node) uint8 {
- var maxParams uint8
- for i := range n.children {
- params := checkMaxParams(t, n.children[i])
- if params > maxParams {
- maxParams = params
- }
- }
- if n.nType > root && !n.wildChild {
- maxParams++
- }
-
- if n.maxParams != maxParams {
- t.Errorf(
- "maxParams mismatch for node '%s': is %d, should be %d",
- n.path, n.maxParams, maxParams,
- )
- }
-
- return maxParams
-}
-
-func TestCountParams(t *testing.T) {
- if countParams("/path/:param1/static/*catch-all") != 2 {
- t.Fail()
- }
- if countParams(strings.Repeat("/:param", 256)) != 255 {
- t.Fail()
- }
-}
-
-func TestTreeAddAndGet(t *testing.T) {
- tree := &node{}
-
- routes := [...]string{
- "/hi",
- "/contact",
- "/co",
- "/c",
- "/a",
- "/ab",
- "/doc/",
- "/doc/go_faq.html",
- "/doc/go1.html",
- "/α",
- "/β",
- }
- for _, route := range routes {
- tree.addRoute(route, fakeHandler(route))
- }
-
- //printChildren(tree, "")
-
- checkRequests(t, tree, testRequests{
- {"/a", false, "/a", nil},
- {"/", true, "", nil},
- {"/hi", false, "/hi", nil},
- {"/contact", false, "/contact", nil},
- {"/co", false, "/co", nil},
- {"/con", true, "", nil}, // key mismatch
- {"/cona", true, "", nil}, // key mismatch
- {"/no", true, "", nil}, // no matching child
- {"/ab", false, "/ab", nil},
- {"/α", false, "/α", nil},
- {"/β", false, "/β", nil},
- })
-
- checkPriorities(t, tree)
- checkMaxParams(t, tree)
-}
-
-func TestTreeWildcard(t *testing.T) {
- tree := &node{}
-
- routes := [...]string{
- "/",
- "/cmd/:tool/:sub",
- "/cmd/:tool/",
- "/src/*filepath",
- "/search/",
- "/search/:query",
- "/user_:name",
- "/user_:name/about",
- "/files/:dir/*filepath",
- "/doc/",
- "/doc/go_faq.html",
- "/doc/go1.html",
- "/info/:user/public",
- "/info/:user/project/:project",
- }
- for _, route := range routes {
- tree.addRoute(route, fakeHandler(route))
- }
-
- //printChildren(tree, "")
-
- checkRequests(t, tree, testRequests{
- {"/", false, "/", nil},
- {"/cmd/test/", false, "/cmd/:tool/", Params{Param{"tool", "test"}}},
- {"/cmd/test", true, "", Params{Param{"tool", "test"}}},
- {"/cmd/test/3", false, "/cmd/:tool/:sub", Params{Param{"tool", "test"}, Param{"sub", "3"}}},
- {"/src/", false, "/src/*filepath", Params{Param{"filepath", "/"}}},
- {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}},
- {"/search/", false, "/search/", nil},
- {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}},
- {"/search/someth!ng+in+ünìcodé/", true, "", Params{Param{"query", "someth!ng+in+ünìcodé"}}},
- {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}},
- {"/user_gopher/about", false, "/user_:name/about", Params{Param{"name", "gopher"}}},
- {"/files/js/inc/framework.js", false, "/files/:dir/*filepath", Params{Param{"dir", "js"}, Param{"filepath", "/inc/framework.js"}}},
- {"/info/gordon/public", false, "/info/:user/public", Params{Param{"user", "gordon"}}},
- {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{"user", "gordon"}, Param{"project", "go"}}},
- })
-
- checkPriorities(t, tree)
- checkMaxParams(t, tree)
-}
-
-func catchPanic(testFunc func()) (recv interface{}) {
- defer func() {
- recv = recover()
- }()
-
- testFunc()
- return
-}
-
-type testRoute struct {
- path string
- conflict bool
-}
-
-func testRoutes(t *testing.T, routes []testRoute) {
- tree := &node{}
-
- for _, route := range routes {
- recv := catchPanic(func() {
- tree.addRoute(route.path, nil)
- })
-
- if route.conflict {
- if recv == nil {
- t.Errorf("no panic for conflicting route '%s'", route.path)
- }
- } else if recv != nil {
- t.Errorf("unexpected panic for route '%s': %v", route.path, recv)
- }
- }
-
- //printChildren(tree, "")
-}
-
-func TestTreeWildcardConflict(t *testing.T) {
- routes := []testRoute{
- {"/cmd/:tool/:sub", false},
- {"/cmd/vet", true},
- {"/src/*filepath", false},
- {"/src/*filepathx", true},
- {"/src/", true},
- {"/src1/", false},
- {"/src1/*filepath", true},
- {"/src2*filepath", true},
- {"/search/:query", false},
- {"/search/invalid", true},
- {"/user_:name", false},
- {"/user_x", true},
- {"/user_:name", false},
- {"/id:id", false},
- {"/id/:id", true},
- }
- testRoutes(t, routes)
-}
-
-func TestTreeChildConflict(t *testing.T) {
- routes := []testRoute{
- {"/cmd/vet", false},
- {"/cmd/:tool/:sub", true},
- {"/src/AUTHORS", false},
- {"/src/*filepath", true},
- {"/user_x", false},
- {"/user_:name", true},
- {"/id/:id", false},
- {"/id:id", true},
- {"/:id", true},
- {"/*filepath", true},
- }
- testRoutes(t, routes)
-}
-
-func TestTreeDupliatePath(t *testing.T) {
- tree := &node{}
-
- routes := [...]string{
- "/",
- "/doc/",
- "/src/*filepath",
- "/search/:query",
- "/user_:name",
- }
- for _, route := range routes {
- recv := catchPanic(func() {
- tree.addRoute(route, fakeHandler(route))
- })
- if recv != nil {
- t.Fatalf("panic inserting route '%s': %v", route, recv)
- }
-
- // Add again
- recv = catchPanic(func() {
- tree.addRoute(route, nil)
- })
- if recv == nil {
- t.Fatalf("no panic while inserting duplicate route '%s", route)
- }
- }
-
- //printChildren(tree, "")
-
- checkRequests(t, tree, testRequests{
- {"/", false, "/", nil},
- {"/doc/", false, "/doc/", nil},
- {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}},
- {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}},
- {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}},
- })
-}
-
-func TestEmptyWildcardName(t *testing.T) {
- tree := &node{}
-
- routes := [...]string{
- "/user:",
- "/user:/",
- "/cmd/:/",
- "/src/*",
- }
- for _, route := range routes {
- recv := catchPanic(func() {
- tree.addRoute(route, nil)
- })
- if recv == nil {
- t.Fatalf("no panic while inserting route with empty wildcard name '%s", route)
- }
- }
-}
-
-func TestTreeCatchAllConflict(t *testing.T) {
- routes := []testRoute{
- {"/src/*filepath/x", true},
- {"/src2/", false},
- {"/src2/*filepath/x", true},
- }
- testRoutes(t, routes)
-}
-
-func TestTreeCatchAllConflictRoot(t *testing.T) {
- routes := []testRoute{
- {"/", false},
- {"/*filepath", true},
- }
- testRoutes(t, routes)
-}
-
-func TestTreeDoubleWildcard(t *testing.T) {
- const panicMsg = "only one wildcard per path segment is allowed"
-
- routes := [...]string{
- "/:foo:bar",
- "/:foo:bar/",
- "/:foo*bar",
- }
-
- for _, route := range routes {
- tree := &node{}
- recv := catchPanic(func() {
- tree.addRoute(route, nil)
- })
-
- if rs, ok := recv.(string); !ok || !strings.HasPrefix(rs, panicMsg) {
- t.Fatalf(`"Expected panic "%s" for route '%s', got "%v"`, panicMsg, route, recv)
- }
- }
-}
-
-/*func TestTreeDuplicateWildcard(t *testing.T) {
- tree := &node{}
-
- routes := [...]string{
- "/:id/:name/:id",
- }
- for _, route := range routes {
- ...
- }
-}*/
-
-func TestTreeTrailingSlashRedirect(t *testing.T) {
- tree := &node{}
-
- routes := [...]string{
- "/hi",
- "/b/",
- "/search/:query",
- "/cmd/:tool/",
- "/src/*filepath",
- "/x",
- "/x/y",
- "/y/",
- "/y/z",
- "/0/:id",
- "/0/:id/1",
- "/1/:id/",
- "/1/:id/2",
- "/aa",
- "/a/",
- "/admin",
- "/admin/:category",
- "/admin/:category/:page",
- "/doc",
- "/doc/go_faq.html",
- "/doc/go1.html",
- "/no/a",
- "/no/b",
- "/api/hello/:name",
- }
- for _, route := range routes {
- recv := catchPanic(func() {
- tree.addRoute(route, fakeHandler(route))
- })
- if recv != nil {
- t.Fatalf("panic inserting route '%s': %v", route, recv)
- }
- }
-
- //printChildren(tree, "")
-
- tsrRoutes := [...]string{
- "/hi/",
- "/b",
- "/search/gopher/",
- "/cmd/vet",
- "/src",
- "/x/",
- "/y",
- "/0/go/",
- "/1/go",
- "/a",
- "/admin/",
- "/admin/config/",
- "/admin/config/permissions/",
- "/doc/",
- }
- for _, route := range tsrRoutes {
- handler, _, tsr := tree.getValue(route)
- if handler != nil {
- t.Fatalf("non-nil handler for TSR route '%s", route)
- } else if !tsr {
- t.Errorf("expected TSR recommendation for route '%s'", route)
- }
- }
-
- noTsrRoutes := [...]string{
- "/",
- "/no",
- "/no/",
- "/_",
- "/_/",
- "/api/world/abc",
- }
- for _, route := range noTsrRoutes {
- handler, _, tsr := tree.getValue(route)
- if handler != nil {
- t.Fatalf("non-nil handler for No-TSR route '%s", route)
- } else if tsr {
- t.Errorf("expected no TSR recommendation for route '%s'", route)
- }
- }
-}
-
-func TestTreeRootTrailingSlashRedirect(t *testing.T) {
- tree := &node{}
-
- recv := catchPanic(func() {
- tree.addRoute("/:test", fakeHandler("/:test"))
- })
- if recv != nil {
- t.Fatalf("panic inserting test route: %v", recv)
- }
-
- handler, _, tsr := tree.getValue("/")
- if handler != nil {
- t.Fatalf("non-nil handler")
- } else if tsr {
- t.Errorf("expected no TSR recommendation")
- }
-}
-
-func TestTreeFindCaseInsensitivePath(t *testing.T) {
- tree := &node{}
-
- routes := [...]string{
- "/hi",
- "/b/",
- "/ABC/",
- "/search/:query",
- "/cmd/:tool/",
- "/src/*filepath",
- "/x",
- "/x/y",
- "/y/",
- "/y/z",
- "/0/:id",
- "/0/:id/1",
- "/1/:id/",
- "/1/:id/2",
- "/aa",
- "/a/",
- "/doc",
- "/doc/go_faq.html",
- "/doc/go1.html",
- "/doc/go/away",
- "/no/a",
- "/no/b",
- }
-
- for _, route := range routes {
- recv := catchPanic(func() {
- tree.addRoute(route, fakeHandler(route))
- })
- if recv != nil {
- t.Fatalf("panic inserting route '%s': %v", route, recv)
- }
- }
-
- // Check out == in for all registered routes
- // With fixTrailingSlash = true
- for _, route := range routes {
- out, found := tree.findCaseInsensitivePath(route, true)
- if !found {
- t.Errorf("Route '%s' not found!", route)
- } else if string(out) != route {
- t.Errorf("Wrong result for route '%s': %s", route, string(out))
- }
- }
- // With fixTrailingSlash = false
- for _, route := range routes {
- out, found := tree.findCaseInsensitivePath(route, false)
- if !found {
- t.Errorf("Route '%s' not found!", route)
- } else if string(out) != route {
- t.Errorf("Wrong result for route '%s': %s", route, string(out))
- }
- }
-
- tests := []struct {
- in string
- out string
- found bool
- slash bool
- }{
- {"/HI", "/hi", true, false},
- {"/HI/", "/hi", true, true},
- {"/B", "/b/", true, true},
- {"/B/", "/b/", true, false},
- {"/abc", "/ABC/", true, true},
- {"/abc/", "/ABC/", true, false},
- {"/aBc", "/ABC/", true, true},
- {"/aBc/", "/ABC/", true, false},
- {"/abC", "/ABC/", true, true},
- {"/abC/", "/ABC/", true, false},
- {"/SEARCH/QUERY", "/search/QUERY", true, false},
- {"/SEARCH/QUERY/", "/search/QUERY", true, true},
- {"/CMD/TOOL/", "/cmd/TOOL/", true, false},
- {"/CMD/TOOL", "/cmd/TOOL/", true, true},
- {"/SRC/FILE/PATH", "/src/FILE/PATH", true, false},
- {"/x/Y", "/x/y", true, false},
- {"/x/Y/", "/x/y", true, true},
- {"/X/y", "/x/y", true, false},
- {"/X/y/", "/x/y", true, true},
- {"/X/Y", "/x/y", true, false},
- {"/X/Y/", "/x/y", true, true},
- {"/Y/", "/y/", true, false},
- {"/Y", "/y/", true, true},
- {"/Y/z", "/y/z", true, false},
- {"/Y/z/", "/y/z", true, true},
- {"/Y/Z", "/y/z", true, false},
- {"/Y/Z/", "/y/z", true, true},
- {"/y/Z", "/y/z", true, false},
- {"/y/Z/", "/y/z", true, true},
- {"/Aa", "/aa", true, false},
- {"/Aa/", "/aa", true, true},
- {"/AA", "/aa", true, false},
- {"/AA/", "/aa", true, true},
- {"/aA", "/aa", true, false},
- {"/aA/", "/aa", true, true},
- {"/A/", "/a/", true, false},
- {"/A", "/a/", true, true},
- {"/DOC", "/doc", true, false},
- {"/DOC/", "/doc", true, true},
- {"/NO", "", false, true},
- {"/DOC/GO", "", false, true},
- }
- // With fixTrailingSlash = true
- for _, test := range tests {
- out, found := tree.findCaseInsensitivePath(test.in, true)
- if found != test.found || (found && (string(out) != test.out)) {
- t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t",
- test.in, string(out), found, test.out, test.found)
- return
- }
- }
- // With fixTrailingSlash = false
- for _, test := range tests {
- out, found := tree.findCaseInsensitivePath(test.in, false)
- if test.slash {
- if found { // test needs a trailingSlash fix. It must not be found!
- t.Errorf("Found without fixTrailingSlash: %s; got %s", test.in, string(out))
- }
- } else {
- if found != test.found || (found && (string(out) != test.out)) {
- t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t",
- test.in, string(out), found, test.out, test.found)
- return
- }
- }
- }
-}
-
-func TestTreeInvalidNodeType(t *testing.T) {
- const panicMsg = "invalid node type"
-
- tree := &node{}
- tree.addRoute("/", fakeHandler("/"))
- tree.addRoute("/:page", fakeHandler("/:page"))
-
- // set invalid node type
- tree.children[0].nType = 42
-
- // normal lookup
- recv := catchPanic(func() {
- tree.getValue("/test")
- })
- if rs, ok := recv.(string); !ok || rs != panicMsg {
- t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv)
- }
-
- // case-insensitive lookup
- recv = catchPanic(func() {
- tree.findCaseInsensitivePath("/test", true)
- })
- if rs, ok := recv.(string); !ok || rs != panicMsg {
- t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv)
- }
-}
diff --git a/src/dict2rest/vendor/github.com/justinas/alice/.travis.yml b/src/dict2rest/vendor/github.com/justinas/alice/.travis.yml
deleted file mode 100644
index 9398694..0000000
--- a/src/dict2rest/vendor/github.com/justinas/alice/.travis.yml
+++ /dev/null
@@ -1,11 +0,0 @@
-language: go
-
-install:
- - go get github.com/stretchr/testify/assert
-
-go:
- - 1.1
- - 1.2
- - 1.3
- - 1.4
- - tip
diff --git a/src/dict2rest/vendor/github.com/justinas/alice/LICENSE b/src/dict2rest/vendor/github.com/justinas/alice/LICENSE
deleted file mode 100644
index 0d0d352..0000000
--- a/src/dict2rest/vendor/github.com/justinas/alice/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Justinas Stankevicius
-
-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/src/dict2rest/vendor/github.com/justinas/alice/README.md b/src/dict2rest/vendor/github.com/justinas/alice/README.md
deleted file mode 100644
index 88d2134..0000000
--- a/src/dict2rest/vendor/github.com/justinas/alice/README.md
+++ /dev/null
@@ -1,92 +0,0 @@
-# Alice
-
-[![Build Status](https://travis-ci.org/justinas/alice.svg?branch=master)](https://travis-ci.org/justinas/alice)
-
-Alice provides a convenient way to chain
-your HTTP middleware functions and the app handler.
-
-In short, it transforms
-
- Middleware1(Middleware2(Middleware3(App)))
-
-to
-
- alice.New(Middleware1, Middleware2, Middleware3).Then(App).
-
-### Why?
-
-None of the other middleware chaining solutions
-behaves exactly like Alice.
-Alice is as minimal as it gets:
-in essence, it's just a for loop that does the wrapping for you.
-
-Check out [this blog post](http://justinas.org/alice-painless-middleware-chaining-for-go/)
-for explanation how Alice is different from other chaining solutions.
-
-### Usage
-
-Your middleware constructors should have the form of
-
- func (http.Handler) http.Handler
-
-Some middleware provide this out of the box.
-For ones that don't, it's trivial to write one yourself.
-
-```go
-func myStripPrefix(h http.Handler) http.Handler {
- return http.StripPrefix("/old", h)
-}
-```
-
-This complete example shows the full power of Alice.
-
-```go
-package main
-
-import (
- "net/http"
- "time"
-
- "github.com/PuerkitoBio/throttled"
- "github.com/justinas/alice"
- "github.com/justinas/nosurf"
-)
-
-func timeoutHandler(h http.Handler) http.Handler {
- return http.TimeoutHandler(h, 1*time.Second, "timed out")
-}
-
-func myApp(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("Hello world!"))
-}
-
-func main() {
- th := throttled.Interval(throttled.PerSec(10), 1, &throttled.VaryBy{Path: true}, 50)
- myHandler := http.HandlerFunc(myApp)
-
- chain := alice.New(th.Throttle, timeoutHandler, nosurf.NewPure).Then(myHandler)
- http.ListenAndServe(":8000", chain)
-}
-```
-
-Here, the request will pass [throttled](https://github.com/PuerkitoBio/throttled) first,
-then an http.TimeoutHandler we've set up,
-then [nosurf](https://github.com/justinas/nosurf)
-and will finally reach our handler.
-
-Note that Alice makes **no guarantees** for
-how one or another piece of middleware will behave.
-It executes all middleware sequentially so that if a
-piece of middleware were to stop the chain,
-the request will not reach the inner handlers.
-This is intentional behavior.
-
-Alice works with Go 1.0 and higher,
-but running tests requires at least Go 1.1.
-
-### Contributing
-
-0. Find an issue that bugs you / open a new one.
-1. Discuss.
-2. Branch off, commit, test.
-3. Make a pull request / attach the commits to the issue.
diff --git a/src/dict2rest/vendor/github.com/justinas/alice/chain.go b/src/dict2rest/vendor/github.com/justinas/alice/chain.go
deleted file mode 100644
index d281ad3..0000000
--- a/src/dict2rest/vendor/github.com/justinas/alice/chain.go
+++ /dev/null
@@ -1,119 +0,0 @@
-// Package alice provides a convenient way to chain http handlers.
-package alice
-
-import "net/http"
-
-// A constructor for a piece of middleware.
-// Some middleware use this constructor out of the box,
-// so in most cases you can just pass somepackage.New
-type Constructor func(http.Handler) http.Handler
-
-// Chain acts as a list of http.Handler constructors.
-// Chain is effectively immutable:
-// once created, it will always hold
-// the same set of constructors in the same order.
-type Chain struct {
- constructors []Constructor
-}
-
-// New creates a new chain,
-// memorizing the given list of middleware constructors.
-// New serves no other function,
-// constructors are only called upon a call to Then().
-func New(constructors ...Constructor) Chain {
- c := Chain{}
- c.constructors = append(c.constructors, constructors...)
-
- return c
-}
-
-// Then chains the middleware and returns the final http.Handler.
-// New(m1, m2, m3).Then(h)
-// is equivalent to:
-// m1(m2(m3(h)))
-// When the request comes in, it will be passed to m1, then m2, then m3
-// and finally, the given handler
-// (assuming every middleware calls the following one).
-//
-// A chain can be safely reused by calling Then() several times.
-// stdStack := alice.New(ratelimitHandler, csrfHandler)
-// indexPipe = stdStack.Then(indexHandler)
-// authPipe = stdStack.Then(authHandler)
-// Note that constructors are called on every call to Then()
-// and thus several instances of the same middleware will be created
-// when a chain is reused in this way.
-// For proper middleware, this should cause no problems.
-//
-// Then() treats nil as http.DefaultServeMux.
-func (c Chain) Then(h http.Handler) http.Handler {
- var final http.Handler
- if h != nil {
- final = h
- } else {
- final = http.DefaultServeMux
- }
-
- for i := len(c.constructors) - 1; i >= 0; i-- {
- final = c.constructors[i](final)
- }
-
- return final
-}
-
-// ThenFunc works identically to Then, but takes
-// a HandlerFunc instead of a Handler.
-//
-// The following two statements are equivalent:
-// c.Then(http.HandlerFunc(fn))
-// c.ThenFunc(fn)
-//
-// ThenFunc provides all the guarantees of Then.
-func (c Chain) ThenFunc(fn http.HandlerFunc) http.Handler {
- if fn == nil {
- return c.Then(nil)
- }
- return c.Then(http.HandlerFunc(fn))
-}
-
-// Append extends a chain, adding the specified constructors
-// as the last ones in the request flow.
-//
-// Append returns a new chain, leaving the original one untouched.
-//
-// stdChain := alice.New(m1, m2)
-// extChain := stdChain.Append(m3, m4)
-// // requests in stdChain go m1 -> m2
-// // requests in extChain go m1 -> m2 -> m3 -> m4
-func (c Chain) Append(constructors ...Constructor) Chain {
- newCons := make([]Constructor, len(c.constructors)+len(constructors))
- copy(newCons, c.constructors)
- copy(newCons[len(c.constructors):], constructors)
-
- newChain := New(newCons...)
- return newChain
-}
-
-// Extend extends a chain by adding the specified chain
-// as the last one in the request flow.
-//
-// Extend returns a new chain, leaving the original one untouched.
-//
-// stdChain := alice.New(m1, m2)
-// ext1Chain := alice.New(m3, m4)
-// ext2Chain := stdChain.Extend(ext1Chain)
-// // requests in stdChain go m1 -> m2
-// // requests in ext1Chain go m3 -> m4
-// // requests in ext2Chain go m1 -> m2 -> m3 -> m4
-//
-// Another example:
-// aHtmlAfterNosurf := alice.New(m2)
-// aHtml := alice.New(m1, func(h http.Handler) http.Handler {
-// csrf := nosurf.New(h)
-// csrf.SetFailureHandler(aHtmlAfterNosurf.ThenFunc(csrfFail))
-// return csrf
-// }).Extend(aHtmlAfterNosurf)
-// // requests to aHtml hitting nosurfs success handler go m1 -> nosurf -> m2 -> target-handler
-// // requests to aHtml hitting nosurfs failure handler go m1 -> nosurf -> m2 -> csrfFail
-func (c Chain) Extend(chain Chain) Chain {
- return c.Append(chain.constructors...)
-}
diff --git a/src/dict2rest/vendor/github.com/justinas/alice/chain_test.go b/src/dict2rest/vendor/github.com/justinas/alice/chain_test.go
deleted file mode 100644
index 49c0470..0000000
--- a/src/dict2rest/vendor/github.com/justinas/alice/chain_test.go
+++ /dev/null
@@ -1,144 +0,0 @@
-// Package alice implements a middleware chaining solution.
-package alice
-
-import (
- "net/http"
- "net/http/httptest"
- "reflect"
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-// A constructor for middleware
-// that writes its own "tag" into the RW and does nothing else.
-// Useful in checking if a chain is behaving in the right order.
-func tagMiddleware(tag string) Constructor {
- return func(h http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte(tag))
- h.ServeHTTP(w, r)
- })
- }
-}
-
-// Not recommended (https://golang.org/pkg/reflect/#Value.Pointer),
-// but the best we can do.
-func funcsEqual(f1, f2 interface{}) bool {
- val1 := reflect.ValueOf(f1)
- val2 := reflect.ValueOf(f2)
- return val1.Pointer() == val2.Pointer()
-}
-
-var testApp = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("app\n"))
-})
-
-// Tests creating a new chain
-func TestNew(t *testing.T) {
- c1 := func(h http.Handler) http.Handler {
- return nil
- }
- c2 := func(h http.Handler) http.Handler {
- return http.StripPrefix("potato", nil)
- }
-
- slice := []Constructor{c1, c2}
-
- chain := New(slice...)
- assert.True(t, funcsEqual(chain.constructors[0], slice[0]))
- assert.True(t, funcsEqual(chain.constructors[1], slice[1]))
-}
-
-func TestThenWorksWithNoMiddleware(t *testing.T) {
- assert.NotPanics(t, func() {
- chain := New()
- final := chain.Then(testApp)
-
- assert.True(t, funcsEqual(final, testApp))
- })
-}
-
-func TestThenTreatsNilAsDefaultServeMux(t *testing.T) {
- chained := New().Then(nil)
- assert.Equal(t, chained, http.DefaultServeMux)
-}
-
-func TestThenFuncTreatsNilAsDefaultServeMux(t *testing.T) {
- chained := New().ThenFunc(nil)
- assert.Equal(t, chained, http.DefaultServeMux)
-}
-
-func TestThenOrdersHandlersRight(t *testing.T) {
- t1 := tagMiddleware("t1\n")
- t2 := tagMiddleware("t2\n")
- t3 := tagMiddleware("t3\n")
-
- chained := New(t1, t2, t3).Then(testApp)
-
- w := httptest.NewRecorder()
- r, err := http.NewRequest("GET", "/", nil)
- if err != nil {
- t.Fatal(err)
- }
-
- chained.ServeHTTP(w, r)
-
- assert.Equal(t, w.Body.String(), "t1\nt2\nt3\napp\n")
-}
-
-func TestAppendAddsHandlersCorrectly(t *testing.T) {
- chain := New(tagMiddleware("t1\n"), tagMiddleware("t2\n"))
- newChain := chain.Append(tagMiddleware("t3\n"), tagMiddleware("t4\n"))
-
- assert.Equal(t, len(chain.constructors), 2)
- assert.Equal(t, len(newChain.constructors), 4)
-
- chained := newChain.Then(testApp)
-
- w := httptest.NewRecorder()
- r, err := http.NewRequest("GET", "/", nil)
- if err != nil {
- t.Fatal(err)
- }
-
- chained.ServeHTTP(w, r)
-
- assert.Equal(t, w.Body.String(), "t1\nt2\nt3\nt4\napp\n")
-}
-
-func TestAppendRespectsImmutability(t *testing.T) {
- chain := New(tagMiddleware(""))
- newChain := chain.Append(tagMiddleware(""))
-
- assert.NotEqual(t, &chain.constructors[0], &newChain.constructors[0])
-}
-
-func TestExtendAddsHandlersCorrectly(t *testing.T) {
- chain1 := New(tagMiddleware("t1\n"), tagMiddleware("t2\n"))
- chain2 := New(tagMiddleware("t3\n"), tagMiddleware("t4\n"))
- newChain := chain1.Extend(chain2)
-
- assert.Equal(t, len(chain1.constructors), 2)
- assert.Equal(t, len(chain2.constructors), 2)
- assert.Equal(t, len(newChain.constructors), 4)
-
- chained := newChain.Then(testApp)
-
- w := httptest.NewRecorder()
- r, err := http.NewRequest("GET", "/", nil)
- if err != nil {
- t.Fatal(err)
- }
-
- chained.ServeHTTP(w, r)
-
- assert.Equal(t, w.Body.String(), "t1\nt2\nt3\nt4\napp\n")
-}
-
-func TestExtendRespectsImmutability(t *testing.T) {
- chain := New(tagMiddleware(""))
- newChain := chain.Extend(New(tagMiddleware("")))
-
- assert.NotEqual(t, &chain.constructors[0], &newChain.constructors[0])
-}
diff --git a/src/dict2rest/vendor/github.com/rs/cors/.travis.yml b/src/dict2rest/vendor/github.com/rs/cors/.travis.yml
deleted file mode 100644
index bbb5185..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/.travis.yml
+++ /dev/null
@@ -1,4 +0,0 @@
-language: go
-go:
-- 1.3
-- 1.4
diff --git a/src/dict2rest/vendor/github.com/rs/cors/LICENSE b/src/dict2rest/vendor/github.com/rs/cors/LICENSE
deleted file mode 100644
index d8e2df5..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/LICENSE
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright (c) 2014 Olivier Poitrey <rs@dailymotion.com>
-
-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/src/dict2rest/vendor/github.com/rs/cors/README.md b/src/dict2rest/vendor/github.com/rs/cors/README.md
deleted file mode 100644
index 4bf5672..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/README.md
+++ /dev/null
@@ -1,99 +0,0 @@
-# Go CORS handler [![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/rs/cors) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/rs/cors/master/LICENSE) [![build](https://img.shields.io/travis/rs/cors.svg?style=flat)](https://travis-ci.org/rs/cors) [![Coverage](http://gocover.io/_badge/github.com/rs/cors)](http://gocover.io/github.com/rs/cors)
-
-CORS is a `net/http` handler implementing [Cross Origin Resource Sharing W3 specification](http://www.w3.org/TR/cors/) in Golang.
-
-## Getting Started
-
-After installing Go and setting up your [GOPATH](http://golang.org/doc/code.html#GOPATH), create your first `.go` file. We'll call it `server.go`.
-
-```go
-package main
-
-import (
- "net/http"
-
- "github.com/rs/cors"
-)
-
-func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- w.Write([]byte("{\"hello\": \"world\"}"))
- })
-
- // cors.Default() setup the middleware with default options being
- // all origins accepted with simple methods (GET, POST). See
- // documentation below for more options.
- handler := cors.Default().Handler(mux)
- http.ListenAndServe(":8080", handler)
-}
-```
-
-Install `cors`:
-
- go get github.com/rs/cors
-
-Then run your server:
-
- go run server.go
-
-The server now runs on `localhost:8080`:
-
- $ curl -D - -H 'Origin: http://foo.com' http://localhost:8080/
- HTTP/1.1 200 OK
- Access-Control-Allow-Origin: foo.com
- Content-Type: application/json
- Date: Sat, 25 Oct 2014 03:43:57 GMT
- Content-Length: 18
-
- {"hello": "world"}
-
-### More Examples
-
-* `net/http`: [examples/nethttp/server.go](https://github.com/rs/cors/blob/master/examples/nethttp/server.go)
-* [Goji](https://goji.io): [examples/goji/server.go](https://github.com/rs/cors/blob/master/examples/goji/server.go)
-* [Martini](http://martini.codegangsta.io): [examples/martini/server.go](https://github.com/rs/cors/blob/master/examples/martini/server.go)
-* [Negroni](https://github.com/codegangsta/negroni): [examples/negroni/server.go](https://github.com/rs/cors/blob/master/examples/negroni/server.go)
-* [Alice](https://github.com/justinas/alice): [examples/alice/server.go](https://github.com/rs/cors/blob/master/examples/alice/server.go)
-
-## Parameters
-
-Parameters are passed to the middleware thru the `cors.New` method as follow:
-
-```go
-c := cors.New(cors.Options{
- AllowedOrigins: []string{"http://foo.com"},
- AllowCredentials: true,
-})
-
-// Insert the middleware
-handler = c.Handler(handler)
-```
-
-* **AllowedOrigins** `[]string`: A list of origins a cross-domain request can be executed from. If the special `*` value is present in the list, all origins will be allowed. An origin may contain a wildcard (`*`) to replace 0 or more characters (i.e.: `http://*.domain.com`). Usage of wildcards implies a small performance penality. Only one wildcard can be used per origin. The default value is `*`.
-* **AllowOriginFunc** `func (origin string) bool`: A custom function to validate the origin. It take the origin as argument and returns true if allowed or false otherwise. If this option is set, the content of `AllowedOrigins` is ignored
-* **AllowedMethods** `[]string`: A list of methods the client is allowed to use with cross-domain requests. Default value is simple methods (`GET` and `POST`).
-* **AllowedHeaders** `[]string`: A list of non simple headers the client is allowed to use with cross-domain requests.
-* **ExposedHeaders** `[]string`: Indicates which headers are safe to expose to the API of a CORS API specification
-* **AllowCredentials** `bool`: Indicates whether the request can include user credentials like cookies, HTTP authentication or client side SSL certificates. The default is `false`.
-* **MaxAge** `int`: Indicates how long (in seconds) the results of a preflight request can be cached. The default is `0` which stands for no max age.
-* **OptionsPassthrough** `bool`: Instructs preflight to let other potential next handlers to process the `OPTIONS` method. Turn this on if your application handles `OPTIONS`.
-* **Debug** `bool`: Debugging flag adds additional output to debug server side CORS issues.
-
-See [API documentation](http://godoc.org/github.com/rs/cors) for more info.
-
-## Benchmarks
-
- BenchmarkWithout 20000000 64.6 ns/op 8 B/op 1 allocs/op
- BenchmarkDefault 3000000 469 ns/op 114 B/op 2 allocs/op
- BenchmarkAllowedOrigin 3000000 608 ns/op 114 B/op 2 allocs/op
- BenchmarkPreflight 20000000 73.2 ns/op 0 B/op 0 allocs/op
- BenchmarkPreflightHeader 20000000 73.6 ns/op 0 B/op 0 allocs/op
- BenchmarkParseHeaderList 2000000 847 ns/op 184 B/op 6 allocs/op
- BenchmarkParse…Single 5000000 290 ns/op 32 B/op 3 allocs/op
- BenchmarkParse…Normalized 2000000 776 ns/op 160 B/op 6 allocs/op
-
-## Licenses
-
-All source code is licensed under the [MIT License](https://raw.github.com/rs/cors/master/LICENSE).
diff --git a/src/dict2rest/vendor/github.com/rs/cors/bench_test.go b/src/dict2rest/vendor/github.com/rs/cors/bench_test.go
deleted file mode 100644
index b6e3721..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/bench_test.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package cors
-
-import (
- "net/http"
- "testing"
-)
-
-type FakeResponse struct {
- header http.Header
-}
-
-func (r FakeResponse) Header() http.Header {
- return r.header
-}
-
-func (r FakeResponse) WriteHeader(n int) {
-}
-
-func (r FakeResponse) Write(b []byte) (n int, err error) {
- return len(b), nil
-}
-
-func BenchmarkWithout(b *testing.B) {
- res := FakeResponse{http.Header{}}
- req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
-
- b.ReportAllocs()
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- testHandler.ServeHTTP(res, req)
- }
-}
-
-func BenchmarkDefault(b *testing.B) {
- res := FakeResponse{http.Header{}}
- req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
- req.Header.Add("Origin", "somedomain.com")
- handler := Default().Handler(testHandler)
-
- b.ReportAllocs()
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- handler.ServeHTTP(res, req)
- }
-}
-
-func BenchmarkAllowedOrigin(b *testing.B) {
- res := FakeResponse{http.Header{}}
- req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
- req.Header.Add("Origin", "somedomain.com")
- c := New(Options{
- AllowedOrigins: []string{"somedomain.com"},
- })
- handler := c.Handler(testHandler)
-
- b.ReportAllocs()
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- handler.ServeHTTP(res, req)
- }
-}
-
-func BenchmarkPreflight(b *testing.B) {
- res := FakeResponse{http.Header{}}
- req, _ := http.NewRequest("OPTIONS", "http://example.com/foo", nil)
- req.Header.Add("Access-Control-Request-Method", "GET")
- handler := Default().Handler(testHandler)
-
- b.ReportAllocs()
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- handler.ServeHTTP(res, req)
- }
-}
-
-func BenchmarkPreflightHeader(b *testing.B) {
- res := FakeResponse{http.Header{}}
- req, _ := http.NewRequest("OPTIONS", "http://example.com/foo", nil)
- req.Header.Add("Access-Control-Request-Method", "GET")
- req.Header.Add("Access-Control-Request-Headers", "Accept")
- handler := Default().Handler(testHandler)
-
- b.ReportAllocs()
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- handler.ServeHTTP(res, req)
- }
-}
diff --git a/src/dict2rest/vendor/github.com/rs/cors/cors.go b/src/dict2rest/vendor/github.com/rs/cors/cors.go
deleted file mode 100644
index 6616061..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/cors.go
+++ /dev/null
@@ -1,406 +0,0 @@
-/*
-Package cors is net/http handler to handle CORS related requests
-as defined by http://www.w3.org/TR/cors/
-
-You can configure it by passing an option struct to cors.New:
-
- c := cors.New(cors.Options{
- AllowedOrigins: []string{"foo.com"},
- AllowedMethods: []string{"GET", "POST", "DELETE"},
- AllowCredentials: true,
- })
-
-Then insert the handler in the chain:
-
- handler = c.Handler(handler)
-
-See Options documentation for more options.
-
-The resulting handler is a standard net/http handler.
-*/
-package cors
-
-import (
- "log"
- "net/http"
- "os"
- "strconv"
- "strings"
-
- "github.com/rs/xhandler"
- "golang.org/x/net/context"
-)
-
-// Options is a configuration container to setup the CORS middleware.
-type Options struct {
- // AllowedOrigins is a list of origins a cross-domain request can be executed from.
- // If the special "*" value is present in the list, all origins will be allowed.
- // An origin may contain a wildcard (*) to replace 0 or more characters
- // (i.e.: http://*.domain.com). Usage of wildcards implies a small performance penality.
- // Only one wildcard can be used per origin.
- // Default value is ["*"]
- AllowedOrigins []string
- // AllowOriginFunc is a custom function to validate the origin. It take the origin
- // as argument and returns true if allowed or false otherwise. If this option is
- // set, the content of AllowedOrigins is ignored.
- AllowOriginFunc func(origin string) bool
- // AllowedMethods is a list of methods the client is allowed to use with
- // cross-domain requests. Default value is simple methods (GET and POST)
- AllowedMethods []string
- // AllowedHeaders is list of non simple headers the client is allowed to use with
- // cross-domain requests.
- // If the special "*" value is present in the list, all headers will be allowed.
- // Default value is [] but "Origin" is always appended to the list.
- AllowedHeaders []string
- // ExposedHeaders indicates which headers are safe to expose to the API of a CORS
- // API specification
- ExposedHeaders []string
- // AllowCredentials indicates whether the request can include user credentials like
- // cookies, HTTP authentication or client side SSL certificates.
- AllowCredentials bool
- // MaxAge indicates how long (in seconds) the results of a preflight request
- // can be cached
- MaxAge int
- // OptionsPassthrough instructs preflight to let other potential next handlers to
- // process the OPTIONS method. Turn this on if your application handles OPTIONS.
- OptionsPassthrough bool
- // Debugging flag adds additional output to debug server side CORS issues
- Debug bool
-}
-
-// Cors http handler
-type Cors struct {
- // Debug logger
- Log *log.Logger
- // Set to true when allowed origins contains a "*"
- allowedOriginsAll bool
- // Normalized list of plain allowed origins
- allowedOrigins []string
- // List of allowed origins containing wildcards
- allowedWOrigins []wildcard
- // Optional origin validator function
- allowOriginFunc func(origin string) bool
- // Set to true when allowed headers contains a "*"
- allowedHeadersAll bool
- // Normalized list of allowed headers
- allowedHeaders []string
- // Normalized list of allowed methods
- allowedMethods []string
- // Normalized list of exposed headers
- exposedHeaders []string
- allowCredentials bool
- maxAge int
- optionPassthrough bool
-}
-
-// New creates a new Cors handler with the provided options.
-func New(options Options) *Cors {
- c := &Cors{
- exposedHeaders: convert(options.ExposedHeaders, http.CanonicalHeaderKey),
- allowOriginFunc: options.AllowOriginFunc,
- allowCredentials: options.AllowCredentials,
- maxAge: options.MaxAge,
- optionPassthrough: options.OptionsPassthrough,
- }
- if options.Debug {
- c.Log = log.New(os.Stdout, "[cors] ", log.LstdFlags)
- }
-
- // Normalize options
- // Note: for origins and methods matching, the spec requires a case-sensitive matching.
- // As it may error prone, we chose to ignore the spec here.
-
- // Allowed Origins
- if len(options.AllowedOrigins) == 0 {
- // Default is all origins
- c.allowedOriginsAll = true
- } else {
- c.allowedOrigins = []string{}
- c.allowedWOrigins = []wildcard{}
- for _, origin := range options.AllowedOrigins {
- // Normalize
- origin = strings.ToLower(origin)
- if origin == "*" {
- // If "*" is present in the list, turn the whole list into a match all
- c.allowedOriginsAll = true
- c.allowedOrigins = nil
- c.allowedWOrigins = nil
- break
- } else if i := strings.IndexByte(origin, '*'); i >= 0 {
- // Split the origin in two: start and end string without the *
- w := wildcard{origin[0:i], origin[i+1 : len(origin)]}
- c.allowedWOrigins = append(c.allowedWOrigins, w)
- } else {
- c.allowedOrigins = append(c.allowedOrigins, origin)
- }
- }
- }
-
- // Allowed Headers
- if len(options.AllowedHeaders) == 0 {
- // Use sensible defaults
- c.allowedHeaders = []string{"Origin", "Accept", "Content-Type"}
- } else {
- // Origin is always appended as some browsers will always request for this header at preflight
- c.allowedHeaders = convert(append(options.AllowedHeaders, "Origin"), http.CanonicalHeaderKey)
- for _, h := range options.AllowedHeaders {
- if h == "*" {
- c.allowedHeadersAll = true
- c.allowedHeaders = nil
- break
- }
- }
- }
-
- // Allowed Methods
- if len(options.AllowedMethods) == 0 {
- // Default is spec's "simple" methods
- c.allowedMethods = []string{"GET", "POST"}
- } else {
- c.allowedMethods = convert(options.AllowedMethods, strings.ToUpper)
- }
-
- return c
-}
-
-// Default creates a new Cors handler with default options
-func Default() *Cors {
- return New(Options{})
-}
-
-// Handler apply the CORS specification on the request, and add relevant CORS headers
-// as necessary.
-func (c *Cors) Handler(h http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.Method == "OPTIONS" {
- c.logf("Handler: Preflight request")
- c.handlePreflight(w, r)
- // Preflight requests are standalone and should stop the chain as some other
- // middleware may not handle OPTIONS requests correctly. One typical example
- // is authentication middleware ; OPTIONS requests won't carry authentication
- // headers (see #1)
- if c.optionPassthrough {
- h.ServeHTTP(w, r)
- }
- } else {
- c.logf("Handler: Actual request")
- c.handleActualRequest(w, r)
- h.ServeHTTP(w, r)
- }
- })
-}
-
-// HandlerC is net/context aware handler
-func (c *Cors) HandlerC(h xhandler.HandlerC) xhandler.HandlerC {
- return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- if r.Method == "OPTIONS" {
- c.logf("Handler: Preflight request")
- c.handlePreflight(w, r)
- // Preflight requests are standalone and should stop the chain as some other
- // middleware may not handle OPTIONS requests correctly. One typical example
- // is authentication middleware ; OPTIONS requests won't carry authentication
- // headers (see #1)
- if c.optionPassthrough {
- h.ServeHTTPC(ctx, w, r)
- }
- } else {
- c.logf("Handler: Actual request")
- c.handleActualRequest(w, r)
- h.ServeHTTPC(ctx, w, r)
- }
- })
-}
-
-// HandlerFunc provides Martini compatible handler
-func (c *Cors) HandlerFunc(w http.ResponseWriter, r *http.Request) {
- if r.Method == "OPTIONS" {
- c.logf("HandlerFunc: Preflight request")
- c.handlePreflight(w, r)
- } else {
- c.logf("HandlerFunc: Actual request")
- c.handleActualRequest(w, r)
- }
-}
-
-// Negroni compatible interface
-func (c *Cors) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
- if r.Method == "OPTIONS" {
- c.logf("ServeHTTP: Preflight request")
- c.handlePreflight(w, r)
- // Preflight requests are standalone and should stop the chain as some other
- // middleware may not handle OPTIONS requests correctly. One typical example
- // is authentication middleware ; OPTIONS requests won't carry authentication
- // headers (see #1)
- if c.optionPassthrough {
- next(w, r)
- }
- } else {
- c.logf("ServeHTTP: Actual request")
- c.handleActualRequest(w, r)
- next(w, r)
- }
-}
-
-// handlePreflight handles pre-flight CORS requests
-func (c *Cors) handlePreflight(w http.ResponseWriter, r *http.Request) {
- headers := w.Header()
- origin := r.Header.Get("Origin")
-
- if r.Method != "OPTIONS" {
- c.logf(" Preflight aborted: %s!=OPTIONS", r.Method)
- return
- }
- // Always set Vary headers
- // see https://github.com/rs/cors/issues/10,
- // https://github.com/rs/cors/commit/dbdca4d95feaa7511a46e6f1efb3b3aa505bc43f#commitcomment-12352001
- headers.Add("Vary", "Origin")
- headers.Add("Vary", "Access-Control-Request-Method")
- headers.Add("Vary", "Access-Control-Request-Headers")
-
- if origin == "" {
- c.logf(" Preflight aborted: empty origin")
- return
- }
- if !c.isOriginAllowed(origin) {
- c.logf(" Preflight aborted: origin '%s' not allowed", origin)
- return
- }
-
- reqMethod := r.Header.Get("Access-Control-Request-Method")
- if !c.isMethodAllowed(reqMethod) {
- c.logf(" Preflight aborted: method '%s' not allowed", reqMethod)
- return
- }
- reqHeaders := parseHeaderList(r.Header.Get("Access-Control-Request-Headers"))
- if !c.areHeadersAllowed(reqHeaders) {
- c.logf(" Preflight aborted: headers '%v' not allowed", reqHeaders)
- return
- }
- headers.Set("Access-Control-Allow-Origin", origin)
- // Spec says: Since the list of methods can be unbounded, simply returning the method indicated
- // by Access-Control-Request-Method (if supported) can be enough
- headers.Set("Access-Control-Allow-Methods", strings.ToUpper(reqMethod))
- if len(reqHeaders) > 0 {
-
- // Spec says: Since the list of headers can be unbounded, simply returning supported headers
- // from Access-Control-Request-Headers can be enough
- headers.Set("Access-Control-Allow-Headers", strings.Join(reqHeaders, ", "))
- }
- if c.allowCredentials {
- headers.Set("Access-Control-Allow-Credentials", "true")
- }
- if c.maxAge > 0 {
- headers.Set("Access-Control-Max-Age", strconv.Itoa(c.maxAge))
- }
- c.logf(" Preflight response headers: %v", headers)
-}
-
-// handleActualRequest handles simple cross-origin requests, actual request or redirects
-func (c *Cors) handleActualRequest(w http.ResponseWriter, r *http.Request) {
- headers := w.Header()
- origin := r.Header.Get("Origin")
-
- if r.Method == "OPTIONS" {
- c.logf(" Actual request no headers added: method == %s", r.Method)
- return
- }
- // Always set Vary, see https://github.com/rs/cors/issues/10
- headers.Add("Vary", "Origin")
- if origin == "" {
- c.logf(" Actual request no headers added: missing origin")
- return
- }
- if !c.isOriginAllowed(origin) {
- c.logf(" Actual request no headers added: origin '%s' not allowed", origin)
- return
- }
-
- // Note that spec does define a way to specifically disallow a simple method like GET or
- // POST. Access-Control-Allow-Methods is only used for pre-flight requests and the
- // spec doesn't instruct to check the allowed methods for simple cross-origin requests.
- // We think it's a nice feature to be able to have control on those methods though.
- if !c.isMethodAllowed(r.Method) {
- c.logf(" Actual request no headers added: method '%s' not allowed", r.Method)
-
- return
- }
- headers.Set("Access-Control-Allow-Origin", origin)
- if len(c.exposedHeaders) > 0 {
- headers.Set("Access-Control-Expose-Headers", strings.Join(c.exposedHeaders, ", "))
- }
- if c.allowCredentials {
- headers.Set("Access-Control-Allow-Credentials", "true")
- }
- c.logf(" Actual response added headers: %v", headers)
-}
-
-// convenience method. checks if debugging is turned on before printing
-func (c *Cors) logf(format string, a ...interface{}) {
- if c.Log != nil {
- c.Log.Printf(format, a...)
- }
-}
-
-// isOriginAllowed checks if a given origin is allowed to perform cross-domain requests
-// on the endpoint
-func (c *Cors) isOriginAllowed(origin string) bool {
- if c.allowOriginFunc != nil {
- return c.allowOriginFunc(origin)
- }
- if c.allowedOriginsAll {
- return true
- }
- origin = strings.ToLower(origin)
- for _, o := range c.allowedOrigins {
- if o == origin {
- return true
- }
- }
- for _, w := range c.allowedWOrigins {
- if w.match(origin) {
- return true
- }
- }
- return false
-}
-
-// isMethodAllowed checks if a given method can be used as part of a cross-domain request
-// on the endpoing
-func (c *Cors) isMethodAllowed(method string) bool {
- if len(c.allowedMethods) == 0 {
- // If no method allowed, always return false, even for preflight request
- return false
- }
- method = strings.ToUpper(method)
- if method == "OPTIONS" {
- // Always allow preflight requests
- return true
- }
- for _, m := range c.allowedMethods {
- if m == method {
- return true
- }
- }
- return false
-}
-
-// areHeadersAllowed checks if a given list of headers are allowed to used within
-// a cross-domain request.
-func (c *Cors) areHeadersAllowed(requestedHeaders []string) bool {
- if c.allowedHeadersAll || len(requestedHeaders) == 0 {
- return true
- }
- for _, header := range requestedHeaders {
- header = http.CanonicalHeaderKey(header)
- found := false
- for _, h := range c.allowedHeaders {
- if h == header {
- found = true
- }
- }
- if !found {
- return false
- }
- }
- return true
-}
diff --git a/src/dict2rest/vendor/github.com/rs/cors/cors_test.go b/src/dict2rest/vendor/github.com/rs/cors/cors_test.go
deleted file mode 100644
index 28672a0..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/cors_test.go
+++ /dev/null
@@ -1,371 +0,0 @@
-package cors
-
-import (
- "net/http"
- "net/http/httptest"
- "regexp"
- "strings"
- "testing"
-)
-
-var testHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("bar"))
-})
-
-func assertHeaders(t *testing.T, resHeaders http.Header, reqHeaders map[string]string) {
- for name, value := range reqHeaders {
- if actual := strings.Join(resHeaders[name], ", "); actual != value {
- t.Errorf("Invalid header `%s', wanted `%s', got `%s'", name, value, actual)
- }
- }
-}
-
-func TestNoConfig(t *testing.T) {
- s := New(Options{
- // Intentionally left blank.
- })
-
- res := httptest.NewRecorder()
- req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
-
- s.Handler(testHandler).ServeHTTP(res, req)
-
- assertHeaders(t, res.Header(), map[string]string{
- "Vary": "Origin",
- "Access-Control-Allow-Origin": "",
- "Access-Control-Allow-Methods": "",
- "Access-Control-Allow-Headers": "",
- "Access-Control-Allow-Credentials": "",
- "Access-Control-Max-Age": "",
- "Access-Control-Expose-Headers": "",
- })
-}
-
-func TestMatchAllOrigin(t *testing.T) {
- s := New(Options{
- AllowedOrigins: []string{"*"},
- })
-
- res := httptest.NewRecorder()
- req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
- req.Header.Add("Origin", "http://foobar.com")
-
- s.Handler(testHandler).ServeHTTP(res, req)
-
- assertHeaders(t, res.Header(), map[string]string{
- "Vary": "Origin",
- "Access-Control-Allow-Origin": "http://foobar.com",
- "Access-Control-Allow-Methods": "",
- "Access-Control-Allow-Headers": "",
- "Access-Control-Allow-Credentials": "",
- "Access-Control-Max-Age": "",
- "Access-Control-Expose-Headers": "",
- })
-}
-
-func TestAllowedOrigin(t *testing.T) {
- s := New(Options{
- AllowedOrigins: []string{"http://foobar.com"},
- })
-
- res := httptest.NewRecorder()
- req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
- req.Header.Add("Origin", "http://foobar.com")
-
- s.Handler(testHandler).ServeHTTP(res, req)
-
- assertHeaders(t, res.Header(), map[string]string{
- "Vary": "Origin",
- "Access-Control-Allow-Origin": "http://foobar.com",
- "Access-Control-Allow-Methods": "",
- "Access-Control-Allow-Headers": "",
- "Access-Control-Allow-Credentials": "",
- "Access-Control-Max-Age": "",
- "Access-Control-Expose-Headers": "",
- })
-}
-
-func TestWildcardOrigin(t *testing.T) {
- s := New(Options{
- AllowedOrigins: []string{"http://*.bar.com"},
- })
-
- res := httptest.NewRecorder()
- req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
- req.Header.Add("Origin", "http://foo.bar.com")
-
- s.Handler(testHandler).ServeHTTP(res, req)
-
- assertHeaders(t, res.Header(), map[string]string{
- "Vary": "Origin",
- "Access-Control-Allow-Origin": "http://foo.bar.com",
- "Access-Control-Allow-Methods": "",
- "Access-Control-Allow-Headers": "",
- "Access-Control-Allow-Credentials": "",
- "Access-Control-Max-Age": "",
- "Access-Control-Expose-Headers": "",
- })
-}
-
-func TestDisallowedOrigin(t *testing.T) {
- s := New(Options{
- AllowedOrigins: []string{"http://foobar.com"},
- })
-
- res := httptest.NewRecorder()
- req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
- req.Header.Add("Origin", "http://barbaz.com")
-
- s.Handler(testHandler).ServeHTTP(res, req)
-
- assertHeaders(t, res.Header(), map[string]string{
- "Vary": "Origin",
- "Access-Control-Allow-Origin": "",
- "Access-Control-Allow-Methods": "",
- "Access-Control-Allow-Headers": "",
- "Access-Control-Allow-Credentials": "",
- "Access-Control-Max-Age": "",
- "Access-Control-Expose-Headers": "",
- })
-}
-
-func TestDisallowedWildcardOrigin(t *testing.T) {
- s := New(Options{
- AllowedOrigins: []string{"http://*.bar.com"},
- })
-
- res := httptest.NewRecorder()
- req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
- req.Header.Add("Origin", "http://foo.baz.com")
-
- s.Handler(testHandler).ServeHTTP(res, req)
-
- assertHeaders(t, res.Header(), map[string]string{
- "Vary": "Origin",
- "Access-Control-Allow-Origin": "",
- "Access-Control-Allow-Methods": "",
- "Access-Control-Allow-Headers": "",
- "Access-Control-Allow-Credentials": "",
- "Access-Control-Max-Age": "",
- "Access-Control-Expose-Headers": "",
- })
-}
-
-func TestAllowedOriginFunc(t *testing.T) {
- r, _ := regexp.Compile("^http://foo")
- s := New(Options{
- AllowOriginFunc: func(o string) bool {
- return r.MatchString(o)
- },
- })
-
- req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
-
- res := httptest.NewRecorder()
- req.Header.Set("Origin", "http://foobar.com")
- s.Handler(testHandler).ServeHTTP(res, req)
- assertHeaders(t, res.Header(), map[string]string{
- "Access-Control-Allow-Origin": "http://foobar.com",
- })
-
- res = httptest.NewRecorder()
- req.Header.Set("Origin", "http://barfoo.com")
- s.Handler(testHandler).ServeHTTP(res, req)
- assertHeaders(t, res.Header(), map[string]string{
- "Access-Control-Allow-Origin": "",
- })
-}
-
-func TestAllowedMethod(t *testing.T) {
- s := New(Options{
- AllowedOrigins: []string{"http://foobar.com"},
- AllowedMethods: []string{"PUT", "DELETE"},
- })
-
- res := httptest.NewRecorder()
- req, _ := http.NewRequest("OPTIONS", "http://example.com/foo", nil)
- req.Header.Add("Origin", "http://foobar.com")
- req.Header.Add("Access-Control-Request-Method", "PUT")
-
- s.Handler(testHandler).ServeHTTP(res, req)
-
- assertHeaders(t, res.Header(), map[string]string{
- "Vary": "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
- "Access-Control-Allow-Origin": "http://foobar.com",
- "Access-Control-Allow-Methods": "PUT",
- "Access-Control-Allow-Headers": "",
- "Access-Control-Allow-Credentials": "",
- "Access-Control-Max-Age": "",
- "Access-Control-Expose-Headers": "",
- })
-}
-
-func TestDisallowedMethod(t *testing.T) {
- s := New(Options{
- AllowedOrigins: []string{"http://foobar.com"},
- AllowedMethods: []string{"PUT", "DELETE"},
- })
-
- res := httptest.NewRecorder()
- req, _ := http.NewRequest("OPTIONS", "http://example.com/foo", nil)
- req.Header.Add("Origin", "http://foobar.com")
- req.Header.Add("Access-Control-Request-Method", "PATCH")
-
- s.Handler(testHandler).ServeHTTP(res, req)
-
- assertHeaders(t, res.Header(), map[string]string{
- "Vary": "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
- "Access-Control-Allow-Origin": "",
- "Access-Control-Allow-Methods": "",
- "Access-Control-Allow-Headers": "",
- "Access-Control-Allow-Credentials": "",
- "Access-Control-Max-Age": "",
- "Access-Control-Expose-Headers": "",
- })
-}
-
-func TestAllowedHeader(t *testing.T) {
- s := New(Options{
- AllowedOrigins: []string{"http://foobar.com"},
- AllowedHeaders: []string{"X-Header-1", "x-header-2"},
- })
-
- res := httptest.NewRecorder()
- req, _ := http.NewRequest("OPTIONS", "http://example.com/foo", nil)
- req.Header.Add("Origin", "http://foobar.com")
- req.Header.Add("Access-Control-Request-Method", "GET")
- req.Header.Add("Access-Control-Request-Headers", "X-Header-2, X-HEADER-1")
-
- s.Handler(testHandler).ServeHTTP(res, req)
-
- assertHeaders(t, res.Header(), map[string]string{
- "Vary": "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
- "Access-Control-Allow-Origin": "http://foobar.com",
- "Access-Control-Allow-Methods": "GET",
- "Access-Control-Allow-Headers": "X-Header-2, X-Header-1",
- "Access-Control-Allow-Credentials": "",
- "Access-Control-Max-Age": "",
- "Access-Control-Expose-Headers": "",
- })
-}
-
-func TestAllowedWildcardHeader(t *testing.T) {
- s := New(Options{
- AllowedOrigins: []string{"http://foobar.com"},
- AllowedHeaders: []string{"*"},
- })
-
- res := httptest.NewRecorder()
- req, _ := http.NewRequest("OPTIONS", "http://example.com/foo", nil)
- req.Header.Add("Origin", "http://foobar.com")
- req.Header.Add("Access-Control-Request-Method", "GET")
- req.Header.Add("Access-Control-Request-Headers", "X-Header-2, X-HEADER-1")
-
- s.Handler(testHandler).ServeHTTP(res, req)
-
- assertHeaders(t, res.Header(), map[string]string{
- "Vary": "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
- "Access-Control-Allow-Origin": "http://foobar.com",
- "Access-Control-Allow-Methods": "GET",
- "Access-Control-Allow-Headers": "X-Header-2, X-Header-1",
- "Access-Control-Allow-Credentials": "",
- "Access-Control-Max-Age": "",
- "Access-Control-Expose-Headers": "",
- })
-}
-
-func TestDisallowedHeader(t *testing.T) {
- s := New(Options{
- AllowedOrigins: []string{"http://foobar.com"},
- AllowedHeaders: []string{"X-Header-1", "x-header-2"},
- })
-
- res := httptest.NewRecorder()
- req, _ := http.NewRequest("OPTIONS", "http://example.com/foo", nil)
- req.Header.Add("Origin", "http://foobar.com")
- req.Header.Add("Access-Control-Request-Method", "GET")
- req.Header.Add("Access-Control-Request-Headers", "X-Header-3, X-Header-1")
-
- s.Handler(testHandler).ServeHTTP(res, req)
-
- assertHeaders(t, res.Header(), map[string]string{
- "Vary": "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
- "Access-Control-Allow-Origin": "",
- "Access-Control-Allow-Methods": "",
- "Access-Control-Allow-Headers": "",
- "Access-Control-Allow-Credentials": "",
- "Access-Control-Max-Age": "",
- "Access-Control-Expose-Headers": "",
- })
-}
-
-func TestOriginHeader(t *testing.T) {
- s := New(Options{
- AllowedOrigins: []string{"http://foobar.com"},
- })
-
- res := httptest.NewRecorder()
- req, _ := http.NewRequest("OPTIONS", "http://example.com/foo", nil)
- req.Header.Add("Origin", "http://foobar.com")
- req.Header.Add("Access-Control-Request-Method", "GET")
- req.Header.Add("Access-Control-Request-Headers", "origin")
-
- s.Handler(testHandler).ServeHTTP(res, req)
-
- assertHeaders(t, res.Header(), map[string]string{
- "Vary": "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
- "Access-Control-Allow-Origin": "http://foobar.com",
- "Access-Control-Allow-Methods": "GET",
- "Access-Control-Allow-Headers": "Origin",
- "Access-Control-Allow-Credentials": "",
- "Access-Control-Max-Age": "",
- "Access-Control-Expose-Headers": "",
- })
-}
-
-func TestExposedHeader(t *testing.T) {
- s := New(Options{
- AllowedOrigins: []string{"http://foobar.com"},
- ExposedHeaders: []string{"X-Header-1", "x-header-2"},
- })
-
- res := httptest.NewRecorder()
- req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
- req.Header.Add("Origin", "http://foobar.com")
-
- s.Handler(testHandler).ServeHTTP(res, req)
-
- assertHeaders(t, res.Header(), map[string]string{
- "Vary": "Origin",
- "Access-Control-Allow-Origin": "http://foobar.com",
- "Access-Control-Allow-Methods": "",
- "Access-Control-Allow-Headers": "",
- "Access-Control-Allow-Credentials": "",
- "Access-Control-Max-Age": "",
- "Access-Control-Expose-Headers": "X-Header-1, X-Header-2",
- })
-}
-
-func TestAllowedCredentials(t *testing.T) {
- s := New(Options{
- AllowedOrigins: []string{"http://foobar.com"},
- AllowCredentials: true,
- })
-
- res := httptest.NewRecorder()
- req, _ := http.NewRequest("OPTIONS", "http://example.com/foo", nil)
- req.Header.Add("Origin", "http://foobar.com")
- req.Header.Add("Access-Control-Request-Method", "GET")
-
- s.Handler(testHandler).ServeHTTP(res, req)
-
- assertHeaders(t, res.Header(), map[string]string{
- "Vary": "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
- "Access-Control-Allow-Origin": "http://foobar.com",
- "Access-Control-Allow-Methods": "GET",
- "Access-Control-Allow-Headers": "",
- "Access-Control-Allow-Credentials": "true",
- "Access-Control-Max-Age": "",
- "Access-Control-Expose-Headers": "",
- })
-}
diff --git a/src/dict2rest/vendor/github.com/rs/cors/examples/alice/server.go b/src/dict2rest/vendor/github.com/rs/cors/examples/alice/server.go
deleted file mode 100644
index 0a3e15c..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/examples/alice/server.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package main
-
-import (
- "net/http"
-
- "github.com/justinas/alice"
- "github.com/rs/cors"
-)
-
-func main() {
- c := cors.New(cors.Options{
- AllowedOrigins: []string{"http://foo.com"},
- })
-
- mux := http.NewServeMux()
-
- mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- w.Write([]byte("{\"hello\": \"world\"}"))
- })
-
- chain := alice.New(c.Handler).Then(mux)
- http.ListenAndServe(":8080", chain)
-}
diff --git a/src/dict2rest/vendor/github.com/rs/cors/examples/default/server.go b/src/dict2rest/vendor/github.com/rs/cors/examples/default/server.go
deleted file mode 100644
index ccb5e1b..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/examples/default/server.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package main
-
-import (
- "net/http"
-
- "github.com/rs/cors"
-)
-
-func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- w.Write([]byte("{\"hello\": \"world\"}"))
- })
-
- // Use default options
- handler := cors.Default().Handler(mux)
- http.ListenAndServe(":8080", handler)
-}
diff --git a/src/dict2rest/vendor/github.com/rs/cors/examples/goji/server.go b/src/dict2rest/vendor/github.com/rs/cors/examples/goji/server.go
deleted file mode 100644
index 1fb4073..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/examples/goji/server.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package main
-
-import (
- "net/http"
-
- "github.com/rs/cors"
- "github.com/zenazn/goji"
-)
-
-func main() {
- c := cors.New(cors.Options{
- AllowedOrigins: []string{"http://foo.com"},
- })
- goji.Use(c.Handler)
-
- goji.Get("/", func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- w.Write([]byte("{\"hello\": \"world\"}"))
- })
-
- goji.Serve()
-}
diff --git a/src/dict2rest/vendor/github.com/rs/cors/examples/martini/server.go b/src/dict2rest/vendor/github.com/rs/cors/examples/martini/server.go
deleted file mode 100644
index 081af32..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/examples/martini/server.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package main
-
-import (
- "github.com/go-martini/martini"
- "github.com/martini-contrib/render"
- "github.com/rs/cors"
-)
-
-func main() {
- c := cors.New(cors.Options{
- AllowedOrigins: []string{"http://foo.com"},
- })
-
- m := martini.Classic()
- m.Use(render.Renderer())
- m.Use(c.HandlerFunc)
-
- m.Get("/", func(r render.Render) {
- r.JSON(200, map[string]interface{}{"hello": "world"})
- })
-
- m.Run()
-}
diff --git a/src/dict2rest/vendor/github.com/rs/cors/examples/negroni/server.go b/src/dict2rest/vendor/github.com/rs/cors/examples/negroni/server.go
deleted file mode 100644
index 3cb33bf..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/examples/negroni/server.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package main
-
-import (
- "net/http"
-
- "github.com/codegangsta/negroni"
- "github.com/rs/cors"
-)
-
-func main() {
- c := cors.New(cors.Options{
- AllowedOrigins: []string{"http://foo.com"},
- })
-
- mux := http.NewServeMux()
-
- mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- w.Write([]byte("{\"hello\": \"world\"}"))
- })
-
- n := negroni.Classic()
- n.Use(c)
- n.UseHandler(mux)
- n.Run(":3000")
-}
diff --git a/src/dict2rest/vendor/github.com/rs/cors/examples/nethttp/server.go b/src/dict2rest/vendor/github.com/rs/cors/examples/nethttp/server.go
deleted file mode 100644
index eaa775e..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/examples/nethttp/server.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package main
-
-import (
- "net/http"
-
- "github.com/rs/cors"
-)
-
-func main() {
- c := cors.New(cors.Options{
- AllowedOrigins: []string{"http://foo.com"},
- })
-
- handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- w.Write([]byte("{\"hello\": \"world\"}"))
- })
-
- http.ListenAndServe(":8080", c.Handler(handler))
-}
diff --git a/src/dict2rest/vendor/github.com/rs/cors/examples/openbar/server.go b/src/dict2rest/vendor/github.com/rs/cors/examples/openbar/server.go
deleted file mode 100644
index 0940423..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/examples/openbar/server.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package main
-
-import (
- "net/http"
-
- "github.com/rs/cors"
-)
-
-func main() {
- c := cors.New(cors.Options{
- AllowedOrigins: []string{"*"},
- AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
- AllowCredentials: true,
- })
-
- h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- w.Write([]byte("{\"hello\": \"world\"}"))
- })
-
- http.ListenAndServe(":8080", c.Handler(h))
-}
diff --git a/src/dict2rest/vendor/github.com/rs/cors/examples/xhandler/server.go b/src/dict2rest/vendor/github.com/rs/cors/examples/xhandler/server.go
deleted file mode 100644
index 649a1c7..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/examples/xhandler/server.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package main
-
-import (
- "net/http"
-
- "github.com/rs/cors"
- "github.com/rs/xhandler"
- "golang.org/x/net/context"
-)
-
-func main() {
- c := xhandler.Chain{}
-
- // Use default options
- c.UseC(cors.Default().HandlerC)
-
- mux := http.NewServeMux()
- mux.Handle("/", c.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- w.Write([]byte("{\"hello\": \"world\"}"))
- })))
-
- http.ListenAndServe(":8080", mux)
-}
diff --git a/src/dict2rest/vendor/github.com/rs/cors/utils.go b/src/dict2rest/vendor/github.com/rs/cors/utils.go
deleted file mode 100644
index cd24831..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/utils.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package cors
-
-import "strings"
-
-const toLower = 'a' - 'A'
-
-type converter func(string) string
-
-type wildcard struct {
- prefix string
- suffix string
-}
-
-func (w wildcard) match(s string) bool {
- return len(s) >= len(w.prefix+w.suffix) && strings.HasPrefix(s, w.prefix) && strings.HasSuffix(s, w.suffix)
-}
-
-// convert converts a list of string using the passed converter function
-func convert(s []string, c converter) []string {
- out := []string{}
- for _, i := range s {
- out = append(out, c(i))
- }
- return out
-}
-
-// parseHeaderList tokenize + normalize a string containing a list of headers
-func parseHeaderList(headerList string) []string {
- l := len(headerList)
- h := make([]byte, 0, l)
- upper := true
- // Estimate the number headers in order to allocate the right splice size
- t := 0
- for i := 0; i < l; i++ {
- if headerList[i] == ',' {
- t++
- }
- }
- headers := make([]string, 0, t)
- for i := 0; i < l; i++ {
- b := headerList[i]
- if b >= 'a' && b <= 'z' {
- if upper {
- h = append(h, b-toLower)
- } else {
- h = append(h, b)
- }
- } else if b >= 'A' && b <= 'Z' {
- if !upper {
- h = append(h, b+toLower)
- } else {
- h = append(h, b)
- }
- } else if b == '-' || (b >= '0' && b <= '9') {
- h = append(h, b)
- }
-
- if b == ' ' || b == ',' || i == l-1 {
- if len(h) > 0 {
- // Flush the found header
- headers = append(headers, string(h))
- h = h[:0]
- upper = true
- }
- } else {
- upper = b == '-'
- }
- }
- return headers
-}
diff --git a/src/dict2rest/vendor/github.com/rs/cors/utils_test.go b/src/dict2rest/vendor/github.com/rs/cors/utils_test.go
deleted file mode 100644
index 83053b3..0000000
--- a/src/dict2rest/vendor/github.com/rs/cors/utils_test.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package cors
-
-import (
- "strings"
- "testing"
-)
-
-func TestWildcard(t *testing.T) {
- w := wildcard{"foo", "bar"}
- if !w.match("foobar") {
- t.Error("foo*bar should match foobar")
- }
- if !w.match("foobazbar") {
- t.Error("foo*bar should match foobazbar")
- }
- if w.match("foobaz") {
- t.Error("foo*bar should not match foobaz")
- }
-
- w = wildcard{"foo", "oof"}
- if w.match("foof") {
- t.Error("foo*oof should not match foof")
- }
-}
-
-func TestConvert(t *testing.T) {
- s := convert([]string{"A", "b", "C"}, strings.ToLower)
- e := []string{"a", "b", "c"}
- if s[0] != e[0] || s[1] != e[1] || s[2] != e[2] {
- t.Errorf("%v != %v", s, e)
- }
-}
-
-func TestParseHeaderList(t *testing.T) {
- h := parseHeaderList("header, second-header, THIRD-HEADER, Numb3r3d-H34d3r")
- e := []string{"Header", "Second-Header", "Third-Header", "Numb3r3d-H34d3r"}
- if h[0] != e[0] || h[1] != e[1] || h[2] != e[2] {
- t.Errorf("%v != %v", h, e)
- }
-}
-
-func TestParseHeaderListEmpty(t *testing.T) {
- if len(parseHeaderList("")) != 0 {
- t.Error("should be empty sclice")
- }
- if len(parseHeaderList(" , ")) != 0 {
- t.Error("should be empty sclice")
- }
-}
-
-func BenchmarkParseHeaderList(b *testing.B) {
- b.ReportAllocs()
- for i := 0; i < b.N; i++ {
- parseHeaderList("header, second-header, THIRD-HEADER")
- }
-}
-
-func BenchmarkParseHeaderListSingle(b *testing.B) {
- b.ReportAllocs()
- for i := 0; i < b.N; i++ {
- parseHeaderList("header")
- }
-}
-
-func BenchmarkParseHeaderListNormalized(b *testing.B) {
- b.ReportAllocs()
- for i := 0; i < b.N; i++ {
- parseHeaderList("Header1, Header2, Third-Header")
- }
-}
diff --git a/src/dict2rest/vendor/github.com/rs/xhandler/.travis.yml b/src/dict2rest/vendor/github.com/rs/xhandler/.travis.yml
deleted file mode 100644
index b65c7a9..0000000
--- a/src/dict2rest/vendor/github.com/rs/xhandler/.travis.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-language: go
-go:
-- 1.5
-- tip
-matrix:
- allow_failures:
- - go: tip
diff --git a/src/dict2rest/vendor/github.com/rs/xhandler/LICENSE b/src/dict2rest/vendor/github.com/rs/xhandler/LICENSE
deleted file mode 100644
index 47c5e9d..0000000
--- a/src/dict2rest/vendor/github.com/rs/xhandler/LICENSE
+++ /dev/null
@@ -1,19 +0,0 @@
-Copyright (c) 2015 Olivier Poitrey <rs@dailymotion.com>
-
-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/src/dict2rest/vendor/github.com/rs/xhandler/README.md b/src/dict2rest/vendor/github.com/rs/xhandler/README.md
deleted file mode 100644
index 91c594b..0000000
--- a/src/dict2rest/vendor/github.com/rs/xhandler/README.md
+++ /dev/null
@@ -1,134 +0,0 @@
-# XHandler
-
-[![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/rs/xhandler) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/rs/xhandler/master/LICENSE) [![Build Status](https://travis-ci.org/rs/xhandler.svg?branch=master)](https://travis-ci.org/rs/xhandler) [![Coverage](http://gocover.io/_badge/github.com/rs/xhandler)](http://gocover.io/github.com/rs/xhandler)
-
-XHandler is a bridge between [net/context](https://godoc.org/golang.org/x/net/context) and `http.Handler`.
-
-It lets you enforce `net/context` in your handlers without sacrificing compatibility with existing `http.Handlers` nor imposing a specific router.
-
-Thanks to `net/context` deadline management, `xhandler` is able to enforce a per request deadline and will cancel the context when the client closes the connection unexpectedly.
-
-You may create your own `net/context` aware handler pretty much the same way as you would do with http.Handler.
-
-Read more about xhandler on [Dailymotion engineering blog](http://engineering.dailymotion.com/our-way-to-go/).
-
-## Installing
-
- go get -u github.com/rs/xhandler
-
-## Usage
-
-```go
-package main
-
-import (
- "log"
- "net/http"
- "time"
-
- "github.com/rs/cors"
- "github.com/rs/xhandler"
- "golang.org/x/net/context"
-)
-
-type myMiddleware struct {
- next xhandler.HandlerC
-}
-
-func (h myMiddleware) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- ctx = context.WithValue(ctx, "test", "World")
- h.next.ServeHTTPC(ctx, w, r)
-}
-
-func main() {
- c := xhandler.Chain{}
-
- // Add close notifier handler so context is cancelled when the client closes
- // the connection
- c.UseC(xhandler.CloseHandler)
-
- // Add timeout handler
- c.UseC(xhandler.TimeoutHandler(2 * time.Second))
-
- // Middleware putting something in the context
- c.UseC(func(next xhandler.HandlerC) xhandler.HandlerC {
- return myMiddleware{next: next}
- })
-
- // Mix it with a non-context-aware middleware handler
- c.Use(cors.Default().Handler)
-
- // Final handler (using handlerFuncC), reading from the context
- xh := xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- value := ctx.Value("test").(string)
- w.Write([]byte("Hello " + value))
- })
-
- // Bridge context aware handlers with http.Handler using xhandler.Handle()
- http.Handle("/test", c.Handler(xh))
-
- if err := http.ListenAndServe(":8080", nil); err != nil {
- log.Fatal(err)
- }
-}
-```
-
-### Using xmux
-
-Xhandler comes with an optional context aware [muxer](https://github.com/rs/xmux) forked from [httprouter](https://github.com/julienschmidt/httprouter):
-
-```go
-package main
-
-import (
- "fmt"
- "log"
- "net/http"
- "time"
-
- "github.com/rs/xhandler"
- "github.com/rs/xmux"
- "golang.org/x/net/context"
-)
-
-func main() {
- c := xhandler.Chain{}
-
- // Append a context-aware middleware handler
- c.UseC(xhandler.CloseHandler)
-
- // Another context-aware middleware handler
- c.UseC(xhandler.TimeoutHandler(2 * time.Second))
-
- mux := xmux.New()
-
- // Use c.Handler to terminate the chain with your final handler
- mux.GET("/welcome/:name", xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
- fmt.Fprintf(w, "Welcome %s!", xmux.Params(ctx).Get("name"))
- }))
-
- if err := http.ListenAndServe(":8080", c.Handler(mux)); err != nil {
- log.Fatal(err)
- }
-}
-```
-
-See [xmux](https://github.com/rs/xmux) for more examples.
-
-## Context Aware Middleware
-
-Here is a list of `net/context` aware middleware handlers implementing `xhandler.HandlerC` interface.
-
-Feel free to put up a PR linking your middleware if you have built one:
-
-| Middleware | Author | Description |
-| ---------- | ------ | ----------- |
-| [xmux](https://github.com/rs/xmux) | [Olivier Poitrey](https://github.com/rs) | HTTP request muxer |
-| [xlog](https://github.com/rs/xlog) | [Olivier Poitrey](https://github.com/rs) | HTTP handler logger |
-| [xstats](https://github.com/rs/xstats) | [Olivier Poitrey](https://github.com/rs) | A generic client for service instrumentation |
-| [xaccess](https://github.com/rs/xaccess) | [Olivier Poitrey](https://github.com/rs) | HTTP handler access logger with [xlog](https://github.com/rs/xlog) and [xstats](https://github.com/rs/xstats) |
-| [cors](https://github.com/rs/cors) | [Olivier Poitrey](https://github.com/rs) | [Cross Origin Resource Sharing](http://www.w3.org/TR/cors/) (CORS) support |
-
-## Licenses
-
-All source code is licensed under the [MIT License](https://raw.github.com/rs/xhandler/master/LICENSE).
diff --git a/src/dict2rest/vendor/github.com/rs/xhandler/chain.go b/src/dict2rest/vendor/github.com/rs/xhandler/chain.go
deleted file mode 100644
index 042274d..0000000
--- a/src/dict2rest/vendor/github.com/rs/xhandler/chain.go
+++ /dev/null
@@ -1,93 +0,0 @@
-package xhandler
-
-import (
- "net/http"
-
- "golang.org/x/net/context"
-)
-
-// Chain is an helper to chain middleware handlers together for an easier
-// management.
-type Chain []func(next HandlerC) HandlerC
-
-// UseC appends a context-aware handler to the middleware chain.
-func (c *Chain) UseC(f func(next HandlerC) HandlerC) {
- *c = append(*c, f)
-}
-
-// Use appends a standard http.Handler to the middleware chain without
-// lossing track of the context when inserted between two context aware handlers.
-//
-// Caveat: the f function will be called on each request so you are better to put
-// any initialization sequence outside of this function.
-func (c *Chain) Use(f func(next http.Handler) http.Handler) {
- xf := func(next HandlerC) HandlerC {
- return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- n := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- next.ServeHTTPC(ctx, w, r)
- })
- f(n).ServeHTTP(w, r)
- })
- }
- *c = append(*c, xf)
-}
-
-// Handler wraps the provided final handler with all the middleware appended to
-// the chain and return a new standard http.Handler instance.
-// The context.Background() context is injected automatically.
-func (c Chain) Handler(xh HandlerC) http.Handler {
- ctx := context.Background()
- return c.HandlerCtx(ctx, xh)
-}
-
-// HandlerFC is an helper to provide a function (HandlerFuncC) to Handler().
-//
-// HandlerFC is equivalent to:
-// c.Handler(xhandler.HandlerFuncC(xhc))
-func (c Chain) HandlerFC(xhf HandlerFuncC) http.Handler {
- ctx := context.Background()
- return c.HandlerCtx(ctx, HandlerFuncC(xhf))
-}
-
-// HandlerH is an helper to provide a standard http handler (http.HandlerFunc)
-// to Handler(). Your final handler won't have access the context though.
-func (c Chain) HandlerH(h http.Handler) http.Handler {
- ctx := context.Background()
- return c.HandlerCtx(ctx, HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- h.ServeHTTP(w, r)
- }))
-}
-
-// HandlerF is an helper to provide a standard http handler function
-// (http.HandlerFunc) to Handler(). Your final handler won't have access
-// the context though.
-func (c Chain) HandlerF(hf http.HandlerFunc) http.Handler {
- ctx := context.Background()
- return c.HandlerCtx(ctx, HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- hf(w, r)
- }))
-}
-
-// HandlerCtx wraps the provided final handler with all the middleware appended to
-// the chain and return a new standard http.Handler instance.
-func (c Chain) HandlerCtx(ctx context.Context, xh HandlerC) http.Handler {
- return New(ctx, c.HandlerC(xh))
-}
-
-// HandlerC wraps the provided final handler with all the middleware appended to
-// the chain and returns a HandlerC instance.
-func (c Chain) HandlerC(xh HandlerC) HandlerC {
- for i := len(c) - 1; i >= 0; i-- {
- xh = c[i](xh)
- }
- return xh
-}
-
-// HandlerCF wraps the provided final handler func with all the middleware appended to
-// the chain and returns a HandlerC instance.
-//
-// HandlerCF is equivalent to:
-// c.HandlerC(xhandler.HandlerFuncC(xhc))
-func (c Chain) HandlerCF(xhc HandlerFuncC) HandlerC {
- return c.HandlerC(HandlerFuncC(xhc))
-}
diff --git a/src/dict2rest/vendor/github.com/rs/xhandler/chain_example_test.go b/src/dict2rest/vendor/github.com/rs/xhandler/chain_example_test.go
deleted file mode 100644
index 005b5b2..0000000
--- a/src/dict2rest/vendor/github.com/rs/xhandler/chain_example_test.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package xhandler_test
-
-import (
- "fmt"
- "net/http"
- "strings"
- "time"
-
- "github.com/rs/cors"
- "github.com/rs/xhandler"
- "golang.org/x/net/context"
-)
-
-func ExampleChain() {
- c := xhandler.Chain{}
- // Append a context-aware middleware handler
- c.UseC(xhandler.CloseHandler)
-
- // Mix it with a non-context-aware middleware handler
- c.Use(cors.Default().Handler)
-
- // Another context-aware middleware handler
- c.UseC(xhandler.TimeoutHandler(2 * time.Second))
-
- mux := http.NewServeMux()
-
- // Use c.Handler to terminate the chain with your final handler
- mux.Handle("/", c.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
- fmt.Fprintf(w, "Welcome to the home page!")
- })))
-
- // You can reuse the same chain for other handlers
- mux.Handle("/api", c.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
- fmt.Fprintf(w, "Welcome to the API!")
- })))
-}
-
-func ExampleIf() {
- c := xhandler.Chain{}
-
- // Add timeout handler only if the path match a prefix
- c.UseC(xhandler.If(
- func(ctx context.Context, w http.ResponseWriter, r *http.Request) bool {
- return strings.HasPrefix(r.URL.Path, "/with-timeout/")
- },
- xhandler.TimeoutHandler(2*time.Second),
- ))
-
- http.Handle("/", c.Handler(xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
- fmt.Fprintf(w, "Welcome to the home page!")
- })))
-}
diff --git a/src/dict2rest/vendor/github.com/rs/xhandler/chain_test.go b/src/dict2rest/vendor/github.com/rs/xhandler/chain_test.go
deleted file mode 100644
index 0ce9410..0000000
--- a/src/dict2rest/vendor/github.com/rs/xhandler/chain_test.go
+++ /dev/null
@@ -1,112 +0,0 @@
-package xhandler
-
-import (
- "net/http"
- "net/http/httptest"
- "testing"
-
- "github.com/stretchr/testify/assert"
- "golang.org/x/net/context"
-)
-
-func TestAppendHandlerC(t *testing.T) {
- init := 0
- h1 := func(next HandlerC) HandlerC {
- init++
- return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- ctx = context.WithValue(ctx, "test", 1)
- next.ServeHTTPC(ctx, w, r)
- })
- }
- h2 := func(next HandlerC) HandlerC {
- return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- ctx = context.WithValue(ctx, "test", 2)
- next.ServeHTTPC(ctx, w, r)
- })
- }
- c := Chain{}
- c.UseC(h1)
- c.UseC(h2)
- assert.Len(t, c, 2)
-
- h := c.Handler(HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- // Test ordering
- assert.Equal(t, 2, ctx.Value("test"), "second handler should overwrite first handler's context value")
- }))
-
- h.ServeHTTP(nil, nil)
- h.ServeHTTP(nil, nil)
- assert.Equal(t, 1, init, "handler init called once")
-}
-
-func TestAppendHandler(t *testing.T) {
- init := 0
- h1 := func(next HandlerC) HandlerC {
- return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- ctx = context.WithValue(ctx, "test", 1)
- next.ServeHTTPC(ctx, w, r)
- })
- }
- h2 := func(next http.Handler) http.Handler {
- init++
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // Change r and w values
- w = httptest.NewRecorder()
- r = &http.Request{}
- next.ServeHTTP(w, r)
- })
- }
- c := Chain{}
- c.UseC(h1)
- c.Use(h2)
- assert.Len(t, c, 2)
-
- h := c.Handler(HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- // Test ordering
- assert.Equal(t, 1, ctx.Value("test"),
- "the first handler value should be pass through the second (non-aware) one")
- // Test r and w overwrite
- assert.NotNil(t, w)
- assert.NotNil(t, r)
- }))
-
- h.ServeHTTP(nil, nil)
- h.ServeHTTP(nil, nil)
- // There's no safe way to not initialize non ctx aware handlers on each request :/
- //assert.Equal(t, 1, init, "handler init called once")
-}
-
-func TestChainHandlerC(t *testing.T) {
- handlerCalls := 0
- h1 := func(next HandlerC) HandlerC {
- return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- handlerCalls++
- ctx = context.WithValue(ctx, "test", 1)
- next.ServeHTTPC(ctx, w, r)
- })
- }
- h2 := func(next HandlerC) HandlerC {
- return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- handlerCalls++
- ctx = context.WithValue(ctx, "test", 2)
- next.ServeHTTPC(ctx, w, r)
- })
- }
-
- c := Chain{}
- c.UseC(h1)
- c.UseC(h2)
- h := c.HandlerC(HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- handlerCalls++
-
- assert.Equal(t, 2, ctx.Value("test"),
- "second handler should overwrite first handler's context value")
- assert.Equal(t, 1, ctx.Value("mainCtx"),
- "the mainCtx value should be pass through")
- }))
-
- mainCtx := context.WithValue(context.Background(), "mainCtx", 1)
- h.ServeHTTPC(mainCtx, nil, nil)
-
- assert.Equal(t, 3, handlerCalls, "all handler called once")
-}
diff --git a/src/dict2rest/vendor/github.com/rs/xhandler/middleware.go b/src/dict2rest/vendor/github.com/rs/xhandler/middleware.go
deleted file mode 100644
index 5de1364..0000000
--- a/src/dict2rest/vendor/github.com/rs/xhandler/middleware.go
+++ /dev/null
@@ -1,59 +0,0 @@
-package xhandler
-
-import (
- "net/http"
- "time"
-
- "golang.org/x/net/context"
-)
-
-// CloseHandler returns a Handler cancelling the context when the client
-// connection close unexpectedly.
-func CloseHandler(next HandlerC) HandlerC {
- return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- // Cancel the context if the client closes the connection
- if wcn, ok := w.(http.CloseNotifier); ok {
- var cancel context.CancelFunc
- ctx, cancel = context.WithCancel(ctx)
- defer cancel()
-
- notify := wcn.CloseNotify()
- go func() {
- select {
- case <-notify:
- cancel()
- case <-ctx.Done():
- }
- }()
- }
-
- next.ServeHTTPC(ctx, w, r)
- })
-}
-
-// TimeoutHandler returns a Handler which adds a timeout to the context.
-//
-// Child handlers have the responsability to obey the context deadline and to return
-// an appropriate error (or not) response in case of timeout.
-func TimeoutHandler(timeout time.Duration) func(next HandlerC) HandlerC {
- return func(next HandlerC) HandlerC {
- return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- ctx, _ = context.WithTimeout(ctx, timeout)
- next.ServeHTTPC(ctx, w, r)
- })
- }
-}
-
-// If is a special handler that will skip insert the condNext handler only if a condition
-// applies at runtime.
-func If(cond func(ctx context.Context, w http.ResponseWriter, r *http.Request) bool, condNext func(next HandlerC) HandlerC) func(next HandlerC) HandlerC {
- return func(next HandlerC) HandlerC {
- return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- if cond(ctx, w, r) {
- condNext(next).ServeHTTPC(ctx, w, r)
- } else {
- next.ServeHTTPC(ctx, w, r)
- }
- })
- }
-}
diff --git a/src/dict2rest/vendor/github.com/rs/xhandler/middleware_test.go b/src/dict2rest/vendor/github.com/rs/xhandler/middleware_test.go
deleted file mode 100644
index 51306e3..0000000
--- a/src/dict2rest/vendor/github.com/rs/xhandler/middleware_test.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package xhandler
-
-import (
- "log"
- "net/http"
- "net/http/httptest"
- "testing"
- "time"
-
- "github.com/stretchr/testify/assert"
- "golang.org/x/net/context"
-)
-
-func TestTimeoutHandler(t *testing.T) {
- ctx := context.WithValue(context.Background(), contextKey, "value")
- xh := TimeoutHandler(time.Second)(&handler{})
- h := New(ctx, xh)
- w := httptest.NewRecorder()
- r, err := http.NewRequest("GET", "http://example.com/foo", nil)
- if err != nil {
- log.Fatal(err)
- }
- h.ServeHTTP(w, r)
- assert.Equal(t, "value with deadline", w.Body.String())
-}
-
-type closeNotifyWriter struct {
- *httptest.ResponseRecorder
- closed bool
-}
-
-func (w *closeNotifyWriter) CloseNotify() <-chan bool {
- notify := make(chan bool, 1)
- if w.closed {
- // return an already "closed" notifier
- notify <- true
- }
- return notify
-}
-
-func TestCloseHandlerClientClose(t *testing.T) {
- ctx := context.WithValue(context.Background(), contextKey, "value")
- xh := CloseHandler(&handler{})
- h := New(ctx, xh)
- w := &closeNotifyWriter{ResponseRecorder: httptest.NewRecorder(), closed: true}
- r, err := http.NewRequest("GET", "http://example.com/foo", nil)
- if err != nil {
- log.Fatal(err)
- }
- h.ServeHTTP(w, r)
- assert.Equal(t, "value canceled", w.Body.String())
-}
-
-func TestCloseHandlerRequestEnds(t *testing.T) {
- ctx := context.WithValue(context.Background(), contextKey, "value")
- xh := CloseHandler(&handler{})
- h := New(ctx, xh)
- w := &closeNotifyWriter{ResponseRecorder: httptest.NewRecorder(), closed: false}
- r, err := http.NewRequest("GET", "http://example.com/foo", nil)
- if err != nil {
- log.Fatal(err)
- }
- h.ServeHTTP(w, r)
- assert.Equal(t, "value", w.Body.String())
-}
-
-func TestIf(t *testing.T) {
- trueHandler := HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- assert.Equal(t, "/true", r.URL.Path)
- })
- falseHandler := HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- assert.NotEqual(t, "/true", r.URL.Path)
- })
- ctx := context.WithValue(context.Background(), contextKey, "value")
- xh := If(
- func(ctx context.Context, w http.ResponseWriter, r *http.Request) bool {
- return r.URL.Path == "/true"
- },
- func(next HandlerC) HandlerC {
- return trueHandler
- },
- )(falseHandler)
- h := New(ctx, xh)
- r, _ := http.NewRequest("GET", "http://example.com/true", nil)
- h.ServeHTTP(nil, r)
- r, _ = http.NewRequest("GET", "http://example.com/false", nil)
- h.ServeHTTP(nil, r)
-}
diff --git a/src/dict2rest/vendor/github.com/rs/xhandler/xhandler.go b/src/dict2rest/vendor/github.com/rs/xhandler/xhandler.go
deleted file mode 100644
index 0dfcddf..0000000
--- a/src/dict2rest/vendor/github.com/rs/xhandler/xhandler.go
+++ /dev/null
@@ -1,42 +0,0 @@
-// Package xhandler provides a bridge between http.Handler and net/context.
-//
-// xhandler enforces net/context in your handlers without sacrificing
-// compatibility with existing http.Handlers nor imposing a specific router.
-//
-// Thanks to net/context deadline management, xhandler is able to enforce
-// a per request deadline and will cancel the context in when the client close
-// the connection unexpectedly.
-//
-// You may create net/context aware middlewares pretty much the same way as
-// you would do with http.Handler.
-package xhandler // import "github.com/rs/xhandler"
-
-import (
- "net/http"
-
- "golang.org/x/net/context"
-)
-
-// HandlerC is a net/context aware http.Handler
-type HandlerC interface {
- ServeHTTPC(context.Context, http.ResponseWriter, *http.Request)
-}
-
-// HandlerFuncC type is an adapter to allow the use of ordinary functions
-// as a xhandler.Handler. If f is a function with the appropriate signature,
-// xhandler.HandlerFuncC(f) is a xhandler.Handler object that calls f.
-type HandlerFuncC func(context.Context, http.ResponseWriter, *http.Request)
-
-// ServeHTTPC calls f(ctx, w, r).
-func (f HandlerFuncC) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- f(ctx, w, r)
-}
-
-// New creates a conventional http.Handler injecting the provided root
-// context to sub handlers. This handler is used as a bridge between conventional
-// http.Handler and context aware handlers.
-func New(ctx context.Context, h HandlerC) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- h.ServeHTTPC(ctx, w, r)
- })
-}
diff --git a/src/dict2rest/vendor/github.com/rs/xhandler/xhandler_example_test.go b/src/dict2rest/vendor/github.com/rs/xhandler/xhandler_example_test.go
deleted file mode 100644
index 9f6f8a5..0000000
--- a/src/dict2rest/vendor/github.com/rs/xhandler/xhandler_example_test.go
+++ /dev/null
@@ -1,67 +0,0 @@
-package xhandler_test
-
-import (
- "log"
- "net/http"
- "time"
-
- "github.com/rs/xhandler"
- "golang.org/x/net/context"
-)
-
-type key int
-
-const contextKey key = 0
-
-func newContext(ctx context.Context, value string) context.Context {
- return context.WithValue(ctx, contextKey, value)
-}
-
-func fromContext(ctx context.Context) (string, bool) {
- value, ok := ctx.Value(contextKey).(string)
- return value, ok
-}
-
-func ExampleHandle() {
- var xh xhandler.HandlerC
- xh = xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- value, _ := fromContext(ctx)
- w.Write([]byte("Hello " + value))
- })
-
- xh = (func(next xhandler.HandlerC) xhandler.HandlerC {
- return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- ctx = newContext(ctx, "World")
- next.ServeHTTPC(ctx, w, r)
- })
- })(xh)
-
- ctx := context.Background()
- // Bridge context aware handlers with http.Handler using xhandler.Handle()
- http.Handle("/", xhandler.New(ctx, xh))
-
- if err := http.ListenAndServe(":8080", nil); err != nil {
- log.Fatal(err)
- }
-}
-
-func ExampleHandleTimeout() {
- var xh xhandler.HandlerC
- xh = xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("Hello World"))
- if _, ok := ctx.Deadline(); ok {
- w.Write([]byte(" with deadline"))
- }
- })
-
- // This handler adds a timeout to the handler
- xh = xhandler.TimeoutHandler(5 * time.Second)(xh)
-
- ctx := context.Background()
- // Bridge context aware handlers with http.Handler using xhandler.Handle()
- http.Handle("/", xhandler.New(ctx, xh))
-
- if err := http.ListenAndServe(":8080", nil); err != nil {
- log.Fatal(err)
- }
-}
diff --git a/src/dict2rest/vendor/github.com/rs/xhandler/xhandler_test.go b/src/dict2rest/vendor/github.com/rs/xhandler/xhandler_test.go
deleted file mode 100644
index 3f5021f..0000000
--- a/src/dict2rest/vendor/github.com/rs/xhandler/xhandler_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-package xhandler
-
-import (
- "log"
- "net/http"
- "net/http/httptest"
- "testing"
- "time"
-
- "github.com/stretchr/testify/assert"
- "golang.org/x/net/context"
-)
-
-type handler struct{}
-
-type key int
-
-const contextKey key = 0
-
-func newContext(ctx context.Context, value string) context.Context {
- return context.WithValue(ctx, contextKey, value)
-}
-
-func fromContext(ctx context.Context) (string, bool) {
- value, ok := ctx.Value(contextKey).(string)
- return value, ok
-}
-
-func (h handler) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) {
- // Leave other go routines a chance to run
- time.Sleep(time.Nanosecond)
- value, _ := fromContext(ctx)
- if _, ok := ctx.Deadline(); ok {
- value += " with deadline"
- }
- if ctx.Err() == context.Canceled {
- value += " canceled"
- }
- w.Write([]byte(value))
-}
-
-func TestHandle(t *testing.T) {
- ctx := context.WithValue(context.Background(), contextKey, "value")
- h := New(ctx, &handler{})
- w := httptest.NewRecorder()
- r, err := http.NewRequest("GET", "http://example.com/foo", nil)
- if err != nil {
- log.Fatal(err)
- }
- h.ServeHTTP(w, r)
- assert.Equal(t, "value", w.Body.String())
-}
-
-func TestHandlerFunc(t *testing.T) {
- ok := false
- xh := HandlerFuncC(func(context.Context, http.ResponseWriter, *http.Request) {
- ok = true
- })
- xh.ServeHTTPC(nil, nil, nil)
- assert.True(t, ok)
-}
diff --git a/src/dict2rest/vendor/github.com/rs/xhandler/xmux/README.md b/src/dict2rest/vendor/github.com/rs/xhandler/xmux/README.md
deleted file mode 100644
index 6ea3c0f..0000000
--- a/src/dict2rest/vendor/github.com/rs/xhandler/xmux/README.md
+++ /dev/null
@@ -1 +0,0 @@
-Xmux did move to it's [own repository](https://github.com/rs/xmux/blob/master/README.md)
diff --git a/src/dict2rest/vendor/github.com/stretchr/graceful/.gitignore b/src/dict2rest/vendor/github.com/stretchr/graceful/.gitignore
deleted file mode 100644
index 8365624..0000000
--- a/src/dict2rest/vendor/github.com/stretchr/graceful/.gitignore
+++ /dev/null
@@ -1,23 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
-*.test
diff --git a/src/dict2rest/vendor/github.com/stretchr/graceful/LICENSE b/src/dict2rest/vendor/github.com/stretchr/graceful/LICENSE
deleted file mode 100644
index a4f2f28..0000000
--- a/src/dict2rest/vendor/github.com/stretchr/graceful/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Tyler Bunnell
-
-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/src/dict2rest/vendor/github.com/stretchr/graceful/README.md b/src/dict2rest/vendor/github.com/stretchr/graceful/README.md
deleted file mode 100644
index 531249a..0000000
--- a/src/dict2rest/vendor/github.com/stretchr/graceful/README.md
+++ /dev/null
@@ -1,137 +0,0 @@
-graceful [![GoDoc](https://godoc.org/github.com/tylerb/graceful?status.png)](http://godoc.org/github.com/tylerb/graceful) [![Build Status](https://drone.io/github.com/tylerb/graceful/status.png)](https://drone.io/github.com/tylerb/graceful/latest) [![Coverage Status](https://coveralls.io/repos/tylerb/graceful/badge.svg?branch=dronedebug)](https://coveralls.io/r/tylerb/graceful?branch=dronedebug) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tylerb/graceful?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
-========
-
-Graceful is a Go 1.3+ package enabling graceful shutdown of http.Handler servers.
-
-## Installation
-
-To install, simply execute:
-
-```
-go get gopkg.in/tylerb/graceful.v1
-```
-
-I am using [gopkg.in](http://labix.org/gopkg.in) to control releases.
-
-## Usage
-
-Using Graceful is easy. Simply create your http.Handler and pass it to the `Run` function:
-
-```go
-package main
-
-import (
- "gopkg.in/tylerb/graceful.v1"
- "net/http"
- "fmt"
- "time"
-)
-
-func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
- fmt.Fprintf(w, "Welcome to the home page!")
- })
-
- graceful.Run(":3001",10*time.Second,mux)
-}
-```
-
-Another example, using [Negroni](https://github.com/codegangsta/negroni), functions in much the same manner:
-
-```go
-package main
-
-import (
- "github.com/codegangsta/negroni"
- "gopkg.in/tylerb/graceful.v1"
- "net/http"
- "fmt"
- "time"
-)
-
-func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
- fmt.Fprintf(w, "Welcome to the home page!")
- })
-
- n := negroni.Classic()
- n.UseHandler(mux)
- //n.Run(":3000")
- graceful.Run(":3001",10*time.Second,n)
-}
-```
-
-In addition to Run there are the http.Server counterparts ListenAndServe, ListenAndServeTLS and Serve, which allow you to configure HTTPS, custom timeouts and error handling.
-Graceful may also be used by instantiating its Server type directly, which embeds an http.Server:
-
-```go
-mux := // ...
-
-srv := &graceful.Server{
- Timeout: 10 * time.Second,
-
- Server: &http.Server{
- Addr: ":1234",
- Handler: mux,
- },
-}
-
-srv.ListenAndServe()
-```
-
-This form allows you to set the ConnState callback, which works in the same way as in http.Server:
-
-```go
-mux := // ...
-
-srv := &graceful.Server{
- Timeout: 10 * time.Second,
-
- ConnState: func(conn net.Conn, state http.ConnState) {
- // conn has a new state
- },
-
- Server: &http.Server{
- Addr: ":1234",
- Handler: mux,
- },
-}
-
-srv.ListenAndServe()
-```
-
-## Behaviour
-
-When Graceful is sent a SIGINT or SIGTERM (possibly from ^C or a kill command), it:
-
-1. Disables keepalive connections.
-2. Closes the listening socket, allowing another process to listen on that port immediately.
-3. Starts a timer of `timeout` duration to give active requests a chance to finish.
-4. When timeout expires, closes all active connections.
-5. Closes the `stopChan`, waking up any blocking goroutines.
-6. Returns from the function, allowing the server to terminate.
-
-## Notes
-
-If the `timeout` argument to `Run` is 0, the server never times out, allowing all active requests to complete.
-
-If you wish to stop the server in some way other than an OS signal, you may call the `Stop()` function.
-This function stops the server, gracefully, using the new timeout value you provide. The `StopChan()` function
-returns a channel on which you can block while waiting for the server to stop. This channel will be closed when
-the server is stopped, allowing your execution to proceed. Multiple goroutines can block on this channel at the
-same time and all will be signalled when stopping is complete.
-
-## Contributing
-
-If you would like to contribute, please:
-
-1. Create a GitHub issue regarding the contribution. Features and bugs should be discussed beforehand.
-2. Fork the repository.
-3. Create a pull request with your solution. This pull request should reference and close the issues (Fix #2).
-
-All pull requests should:
-
-1. Pass [gometalinter -t .](https://github.com/alecthomas/gometalinter) with no warnings.
-2. Be `go fmt` formatted.
diff --git a/src/dict2rest/vendor/github.com/stretchr/graceful/graceful.go b/src/dict2rest/vendor/github.com/stretchr/graceful/graceful.go
deleted file mode 100644
index d3a7175..0000000
--- a/src/dict2rest/vendor/github.com/stretchr/graceful/graceful.go
+++ /dev/null
@@ -1,359 +0,0 @@
-package graceful
-
-import (
- "crypto/tls"
- "log"
- "net"
- "net/http"
- "os"
- "os/signal"
- "sync"
- "syscall"
- "time"
-
- "golang.org/x/net/netutil"
-)
-
-// Server wraps an http.Server with graceful connection handling.
-// It may be used directly in the same way as http.Server, or may
-// be constructed with the global functions in this package.
-//
-// Example:
-// srv := &graceful.Server{
-// Timeout: 5 * time.Second,
-// Server: &http.Server{Addr: ":1234", Handler: handler},
-// }
-// srv.ListenAndServe()
-type Server struct {
- *http.Server
-
- // Timeout is the duration to allow outstanding requests to survive
- // before forcefully terminating them.
- Timeout time.Duration
-
- // Limit the number of outstanding requests
- ListenLimit int
-
- // ConnState specifies an optional callback function that is
- // called when a client connection changes state. This is a proxy
- // to the underlying http.Server's ConnState, and the original
- // must not be set directly.
- ConnState func(net.Conn, http.ConnState)
-
- // BeforeShutdown is an optional callback function that is called
- // before the listener is closed.
- BeforeShutdown func()
-
- // ShutdownInitiated is an optional callback function that is called
- // when shutdown is initiated. It can be used to notify the client
- // side of long lived connections (e.g. websockets) to reconnect.
- ShutdownInitiated func()
-
- // NoSignalHandling prevents graceful from automatically shutting down
- // on SIGINT and SIGTERM. If set to true, you must shut down the server
- // manually with Stop().
- NoSignalHandling bool
-
- // interrupt signals the listener to stop serving connections,
- // and the server to shut down.
- interrupt chan os.Signal
-
- // stopLock is used to protect against concurrent calls to Stop
- stopLock sync.Mutex
-
- // stopChan is the channel on which callers may block while waiting for
- // the server to stop.
- stopChan chan struct{}
-
- // chanLock is used to protect access to the various channel constructors.
- chanLock sync.RWMutex
-
- // connections holds all connections managed by graceful
- connections map[net.Conn]struct{}
-}
-
-// Run serves the http.Handler with graceful shutdown enabled.
-//
-// timeout is the duration to wait until killing active requests and stopping the server.
-// If timeout is 0, the server never times out. It waits for all active requests to finish.
-func Run(addr string, timeout time.Duration, n http.Handler) {
- srv := &Server{
- Timeout: timeout,
- Server: &http.Server{Addr: addr, Handler: n},
- }
-
- if err := srv.ListenAndServe(); err != nil {
- if opErr, ok := err.(*net.OpError); !ok || (ok && opErr.Op != "accept") {
- logger := log.New(os.Stdout, "[graceful] ", 0)
- logger.Fatal(err)
- }
- }
-
-}
-
-// ListenAndServe is equivalent to http.Server.ListenAndServe with graceful shutdown enabled.
-//
-// timeout is the duration to wait until killing active requests and stopping the server.
-// If timeout is 0, the server never times out. It waits for all active requests to finish.
-func ListenAndServe(server *http.Server, timeout time.Duration) error {
- srv := &Server{Timeout: timeout, Server: server}
- return srv.ListenAndServe()
-}
-
-// ListenAndServe is equivalent to http.Server.ListenAndServe with graceful shutdown enabled.
-func (srv *Server) ListenAndServe() error {
- // Create the listener so we can control their lifetime
- addr := srv.Addr
- if addr == "" {
- addr = ":http"
- }
- l, err := net.Listen("tcp", addr)
- if err != nil {
- return err
- }
-
- return srv.Serve(l)
-}
-
-// ListenAndServeTLS is equivalent to http.Server.ListenAndServeTLS with graceful shutdown enabled.
-//
-// timeout is the duration to wait until killing active requests and stopping the server.
-// If timeout is 0, the server never times out. It waits for all active requests to finish.
-func ListenAndServeTLS(server *http.Server, certFile, keyFile string, timeout time.Duration) error {
- srv := &Server{Timeout: timeout, Server: server}
- return srv.ListenAndServeTLS(certFile, keyFile)
-}
-
-// ListenTLS is a convenience method that creates an https listener using the
-// provided cert and key files. Use this method if you need access to the
-// listener object directly. When ready, pass it to the Serve method.
-func (srv *Server) ListenTLS(certFile, keyFile string) (net.Listener, error) {
- // Create the listener ourselves so we can control its lifetime
- addr := srv.Addr
- if addr == "" {
- addr = ":https"
- }
-
- config := &tls.Config{}
- if srv.TLSConfig != nil {
- *config = *srv.TLSConfig
- }
- if config.NextProtos == nil {
- config.NextProtos = []string{"http/1.1"}
- }
-
- var err error
- config.Certificates = make([]tls.Certificate, 1)
- config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
- if err != nil {
- return nil, err
- }
-
- conn, err := net.Listen("tcp", addr)
- if err != nil {
- return nil, err
- }
-
- tlsListener := tls.NewListener(conn, config)
- return tlsListener, nil
-}
-
-// ListenAndServeTLS is equivalent to http.Server.ListenAndServeTLS with graceful shutdown enabled.
-func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
- l, err := srv.ListenTLS(certFile, keyFile)
- if err != nil {
- return err
- }
-
- return srv.Serve(l)
-}
-
-// ListenAndServeTLSConfig can be used with an existing TLS config and is equivalent to
-// http.Server.ListenAndServeTLS with graceful shutdown enabled,
-func (srv *Server) ListenAndServeTLSConfig(config *tls.Config) error {
- addr := srv.Addr
- if addr == "" {
- addr = ":https"
- }
-
- conn, err := net.Listen("tcp", addr)
- if err != nil {
- return err
- }
-
- tlsListener := tls.NewListener(conn, config)
- return srv.Serve(tlsListener)
-}
-
-// Serve is equivalent to http.Server.Serve with graceful shutdown enabled.
-//
-// timeout is the duration to wait until killing active requests and stopping the server.
-// If timeout is 0, the server never times out. It waits for all active requests to finish.
-func Serve(server *http.Server, l net.Listener, timeout time.Duration) error {
- srv := &Server{Timeout: timeout, Server: server}
- return srv.Serve(l)
-}
-
-// Serve is equivalent to http.Server.Serve with graceful shutdown enabled.
-func (srv *Server) Serve(listener net.Listener) error {
-
- if srv.ListenLimit != 0 {
- listener = netutil.LimitListener(listener, srv.ListenLimit)
- }
-
- // Track connection state
- add := make(chan net.Conn)
- remove := make(chan net.Conn)
-
- srv.Server.ConnState = func(conn net.Conn, state http.ConnState) {
- switch state {
- case http.StateNew:
- add <- conn
- case http.StateClosed, http.StateHijacked:
- remove <- conn
- }
- if srv.ConnState != nil {
- srv.ConnState(conn, state)
- }
- }
-
- // Manage open connections
- shutdown := make(chan chan struct{})
- kill := make(chan struct{})
- go srv.manageConnections(add, remove, shutdown, kill)
-
- interrupt := srv.interruptChan()
- // Set up the interrupt handler
- if !srv.NoSignalHandling {
- signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)
- }
- quitting := make(chan struct{})
- go srv.handleInterrupt(interrupt, quitting, listener)
-
- // Serve with graceful listener.
- // Execution blocks here until listener.Close() is called, above.
- err := srv.Server.Serve(listener)
- if err != nil {
- // If the underlying listening is closed, Serve returns an error
- // complaining about listening on a closed socket. This is expected, so
- // let's ignore the error if we are the ones who explicitly closed the
- // socket.
- select {
- case <-quitting:
- err = nil
- default:
- }
- }
-
- srv.shutdown(shutdown, kill)
-
- return err
-}
-
-// Stop instructs the type to halt operations and close
-// the stop channel when it is finished.
-//
-// timeout is grace period for which to wait before shutting
-// down the server. The timeout value passed here will override the
-// timeout given when constructing the server, as this is an explicit
-// command to stop the server.
-func (srv *Server) Stop(timeout time.Duration) {
- srv.stopLock.Lock()
- srv.Timeout = timeout
- interrupt := srv.interruptChan()
- interrupt <- syscall.SIGINT
- srv.stopLock.Unlock()
-}
-
-// StopChan gets the stop channel which will block until
-// stopping has completed, at which point it is closed.
-// Callers should never close the stop channel.
-func (srv *Server) StopChan() <-chan struct{} {
- srv.chanLock.Lock()
- if srv.stopChan == nil {
- srv.stopChan = make(chan struct{})
- }
- srv.chanLock.Unlock()
- return srv.stopChan
-}
-
-func (srv *Server) manageConnections(add, remove chan net.Conn, shutdown chan chan struct{}, kill chan struct{}) {
- var done chan struct{}
- srv.connections = map[net.Conn]struct{}{}
- for {
- select {
- case conn := <-add:
- srv.connections[conn] = struct{}{}
- case conn := <-remove:
- delete(srv.connections, conn)
- if done != nil && len(srv.connections) == 0 {
- done <- struct{}{}
- return
- }
- case done = <-shutdown:
- if len(srv.connections) == 0 {
- done <- struct{}{}
- return
- }
- case <-kill:
- for k := range srv.connections {
- _ = k.Close() // nothing to do here if it errors
- }
- return
- }
- }
-}
-
-func (srv *Server) interruptChan() chan os.Signal {
- srv.chanLock.Lock()
- if srv.interrupt == nil {
- srv.interrupt = make(chan os.Signal, 1)
- }
- srv.chanLock.Unlock()
-
- return srv.interrupt
-}
-
-func (srv *Server) handleInterrupt(interrupt chan os.Signal, quitting chan struct{}, listener net.Listener) {
- <-interrupt
-
- if srv.BeforeShutdown != nil {
- srv.BeforeShutdown()
- }
-
- close(quitting)
- srv.SetKeepAlivesEnabled(false)
- _ = listener.Close() // we are shutting down anyway. ignore error.
-
- if srv.ShutdownInitiated != nil {
- srv.ShutdownInitiated()
- }
-
- srv.stopLock.Lock()
- signal.Stop(interrupt)
- close(interrupt)
- srv.interrupt = nil
- srv.stopLock.Unlock()
-}
-
-func (srv *Server) shutdown(shutdown chan chan struct{}, kill chan struct{}) {
- // Request done notification
- done := make(chan struct{})
- shutdown <- done
-
- if srv.Timeout > 0 {
- select {
- case <-done:
- case <-time.After(srv.Timeout):
- close(kill)
- }
- } else {
- <-done
- }
- // Close the stopChan to wake up any blocked goroutines.
- srv.chanLock.Lock()
- if srv.stopChan != nil {
- close(srv.stopChan)
- }
- srv.chanLock.Unlock()
-}
diff --git a/src/dict2rest/vendor/github.com/stretchr/graceful/graceful_test.go b/src/dict2rest/vendor/github.com/stretchr/graceful/graceful_test.go
deleted file mode 100644
index 83acac3..0000000
--- a/src/dict2rest/vendor/github.com/stretchr/graceful/graceful_test.go
+++ /dev/null
@@ -1,439 +0,0 @@
-package graceful
-
-import (
- "fmt"
- "io"
- "net"
- "net/http"
- "net/url"
- "os"
- "reflect"
- "strings"
- "sync"
- "syscall"
- "testing"
- "time"
-)
-
-var (
- killTime = 500 * time.Millisecond
- timeoutTime = 1000 * time.Millisecond
- waitTime = 100 * time.Millisecond
-)
-
-func runQuery(t *testing.T, expected int, shouldErr bool, wg *sync.WaitGroup, once *sync.Once) {
- wg.Add(1)
- defer wg.Done()
- client := http.Client{}
- r, err := client.Get("http://localhost:9654")
- if shouldErr && err == nil {
- once.Do(func() {
- t.Fatal("Expected an error but none was encountered.")
- })
- } else if shouldErr && err != nil {
- if checkErr(t, err, once) {
- return
- }
- }
- if r != nil && r.StatusCode != expected {
- once.Do(func() {
- t.Fatalf("Incorrect status code on response. Expected %d. Got %d", expected, r.StatusCode)
- })
- } else if r == nil {
- once.Do(func() {
- t.Fatal("No response when a response was expected.")
- })
- }
-}
-
-func checkErr(t *testing.T, err error, once *sync.Once) bool {
- if err.(*url.Error).Err == io.EOF {
- return true
- }
- var errno syscall.Errno
- switch oe := err.(*url.Error).Err.(type) {
- case *net.OpError:
- switch e := oe.Err.(type) {
- case syscall.Errno:
- errno = e
- case *os.SyscallError:
- errno = e.Err.(syscall.Errno)
- }
- if errno == syscall.ECONNREFUSED {
- return true
- } else if err != nil {
- once.Do(func() {
- t.Fatal("Error on Get:", err)
- })
- }
- default:
- if strings.Contains(err.Error(), "transport closed before response was received") {
- return true
- }
- fmt.Printf("unknown err: %s, %#v\n", err, err)
- }
- return false
-}
-
-func createListener(sleep time.Duration) (*http.Server, net.Listener, error) {
- mux := http.NewServeMux()
- mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
- time.Sleep(sleep)
- rw.WriteHeader(http.StatusOK)
- })
-
- time.Sleep(1 * time.Second)
- server := &http.Server{Addr: ":9654", Handler: mux}
- l, err := net.Listen("tcp", ":9654")
- if err != nil {
- }
- return server, l, err
-}
-
-func runServer(timeout, sleep time.Duration, c chan os.Signal) error {
- server, l, err := createListener(sleep)
- if err != nil {
- return err
- }
-
- srv := &Server{Timeout: timeout, Server: server, interrupt: c}
- return srv.Serve(l)
-}
-
-func launchTestQueries(t *testing.T, wg *sync.WaitGroup, c chan os.Signal) {
- var once sync.Once
- for i := 0; i < 8; i++ {
- go runQuery(t, http.StatusOK, false, wg, &once)
- }
-
- time.Sleep(waitTime)
- c <- os.Interrupt
- time.Sleep(waitTime)
-
- for i := 0; i < 8; i++ {
- go runQuery(t, 0, true, wg, &once)
- }
-
- wg.Done()
-}
-
-func TestGracefulRun(t *testing.T) {
- c := make(chan os.Signal, 1)
-
- var wg sync.WaitGroup
- wg.Add(1)
-
- go func() {
- runServer(killTime, killTime/2, c)
- wg.Done()
- }()
- time.Sleep(1 * time.Second)
-
- wg.Add(1)
- go launchTestQueries(t, &wg, c)
- wg.Wait()
-}
-
-func TestGracefulRunTimesOut(t *testing.T) {
- c := make(chan os.Signal, 1)
-
- var wg sync.WaitGroup
- wg.Add(1)
-
- go func() {
- runServer(killTime, killTime*10, c)
- wg.Done()
- }()
- time.Sleep(2 * time.Second)
-
- var once sync.Once
- wg.Add(1)
- go func() {
- for i := 0; i < 8; i++ {
- go runQuery(t, 0, true, &wg, &once)
- }
- time.Sleep(waitTime)
- c <- os.Interrupt
- time.Sleep(waitTime)
- for i := 0; i < 8; i++ {
- go runQuery(t, 0, true, &wg, &once)
- }
- wg.Done()
- }()
-
- wg.Wait()
-
-}
-
-func TestGracefulRunDoesntTimeOut(t *testing.T) {
- c := make(chan os.Signal, 1)
-
- var wg sync.WaitGroup
- wg.Add(1)
-
- go func() {
- runServer(0, killTime*2, c)
- wg.Done()
- }()
- time.Sleep(1 * time.Second)
-
- wg.Add(1)
- go launchTestQueries(t, &wg, c)
- wg.Wait()
-}
-
-func TestGracefulRunNoRequests(t *testing.T) {
- c := make(chan os.Signal, 1)
-
- var wg sync.WaitGroup
- wg.Add(1)
-
- go func() {
- runServer(0, killTime*2, c)
- wg.Done()
- }()
- time.Sleep(1 * time.Second)
-
- c <- os.Interrupt
-
- wg.Wait()
-
-}
-
-func TestGracefulForwardsConnState(t *testing.T) {
- c := make(chan os.Signal, 1)
- states := make(map[http.ConnState]int)
- var stateLock sync.Mutex
-
- connState := func(conn net.Conn, state http.ConnState) {
- stateLock.Lock()
- states[state]++
- stateLock.Unlock()
- }
-
- var wg sync.WaitGroup
- wg.Add(1)
-
- expected := map[http.ConnState]int{
- http.StateNew: 8,
- http.StateActive: 8,
- http.StateClosed: 8,
- }
-
- go func() {
- server, l, _ := createListener(killTime / 2)
- srv := &Server{
- ConnState: connState,
- Timeout: killTime,
- Server: server,
- interrupt: c,
- }
- srv.Serve(l)
-
- wg.Done()
- }()
- time.Sleep(2 * time.Second)
-
- wg.Add(1)
- go launchTestQueries(t, &wg, c)
- wg.Wait()
-
- stateLock.Lock()
- if !reflect.DeepEqual(states, expected) {
- t.Errorf("Incorrect connection state tracking.\n actual: %v\nexpected: %v\n", states, expected)
- }
- stateLock.Unlock()
-}
-
-func TestGracefulExplicitStop(t *testing.T) {
- server, l, err := createListener(1 * time.Millisecond)
- if err != nil {
- t.Fatal(err)
- }
-
- srv := &Server{Timeout: killTime, Server: server}
-
- go func() {
- go srv.Serve(l)
- time.Sleep(waitTime)
- srv.Stop(killTime)
- }()
-
- // block on the stopChan until the server has shut down
- select {
- case <-srv.StopChan():
- case <-time.After(timeoutTime):
- t.Fatal("Timed out while waiting for explicit stop to complete")
- }
-}
-
-func TestGracefulExplicitStopOverride(t *testing.T) {
- server, l, err := createListener(1 * time.Millisecond)
- if err != nil {
- t.Fatal(err)
- }
-
- srv := &Server{Timeout: killTime, Server: server}
-
- go func() {
- go srv.Serve(l)
- time.Sleep(waitTime)
- srv.Stop(killTime / 2)
- }()
-
- // block on the stopChan until the server has shut down
- select {
- case <-srv.StopChan():
- case <-time.After(killTime):
- t.Fatal("Timed out while waiting for explicit stop to complete")
- }
-}
-
-func TestBeforeShutdownAndShutdownInitiatedCallbacks(t *testing.T) {
- server, l, err := createListener(1 * time.Millisecond)
- if err != nil {
- t.Fatal(err)
- }
-
- beforeShutdownCalled := make(chan struct{})
- cb1 := func() { close(beforeShutdownCalled) }
- shutdownInitiatedCalled := make(chan struct{})
- cb2 := func() { close(shutdownInitiatedCalled) }
-
- srv := &Server{Server: server, BeforeShutdown: cb1, ShutdownInitiated: cb2}
-
- go func() {
- go srv.Serve(l)
- time.Sleep(waitTime)
- srv.Stop(killTime)
- }()
-
- beforeShutdown := false
- shutdownInitiated := false
- for i := 0; i < 2; i++ {
- select {
- case <-beforeShutdownCalled:
- beforeShutdownCalled = nil
- beforeShutdown = true
- case <-shutdownInitiatedCalled:
- shutdownInitiatedCalled = nil
- shutdownInitiated = true
- case <-time.After(killTime):
- t.Fatal("Timed out while waiting for ShutdownInitiated callback to be called")
- }
- }
-
- if !beforeShutdown {
- t.Fatal("beforeShutdown should be true")
- }
- if !shutdownInitiated {
- t.Fatal("shutdownInitiated should be true")
- }
-}
-func hijackingListener(srv *Server) (*http.Server, net.Listener, error) {
- mux := http.NewServeMux()
- mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
- conn, bufrw, err := rw.(http.Hijacker).Hijack()
- if err != nil {
- http.Error(rw, "webserver doesn't support hijacking", http.StatusInternalServerError)
- return
- }
-
- defer conn.Close()
-
- bufrw.WriteString("HTTP/1.1 200 OK\r\n\r\n")
- bufrw.Flush()
- })
-
- server := &http.Server{Addr: ":9654", Handler: mux}
- l, err := net.Listen("tcp", ":9654")
- return server, l, err
-}
-
-func TestNotifyClosed(t *testing.T) {
- c := make(chan os.Signal, 1)
-
- var wg sync.WaitGroup
- wg.Add(1)
-
- srv := &Server{Timeout: killTime, interrupt: c}
- server, l, err := hijackingListener(srv)
- if err != nil {
- t.Fatal(err)
- }
-
- srv.Server = server
-
- go func() {
- srv.Serve(l)
- wg.Done()
- }()
-
- var once sync.Once
- for i := 0; i < 8; i++ {
- runQuery(t, http.StatusOK, false, &wg, &once)
- }
-
- srv.Stop(0)
-
- // block on the stopChan until the server has shut down
- select {
- case <-srv.StopChan():
- case <-time.After(timeoutTime):
- t.Fatal("Timed out while waiting for explicit stop to complete")
- }
-
- if len(srv.connections) > 0 {
- t.Fatal("hijacked connections should not be managed")
- }
-
-}
-
-func TestStopDeadlock(t *testing.T) {
- c := make(chan struct{})
-
- server, l, err := createListener(1 * time.Millisecond)
- if err != nil {
- t.Fatal(err)
- }
-
- srv := &Server{Server: server, NoSignalHandling: true}
-
- go func() {
- time.Sleep(waitTime)
- srv.Serve(l)
- }()
-
- go func() {
- srv.Stop(0)
- close(c)
- }()
-
- select {
- case <-c:
- l.Close()
- case <-time.After(timeoutTime):
- t.Fatal("Timed out while waiting for explicit stop to complete")
- }
-}
-
-// Run with --race
-func TestStopRace(t *testing.T) {
- server, l, err := createListener(1 * time.Millisecond)
- if err != nil {
- t.Fatal(err)
- }
-
- srv := &Server{Timeout: killTime, Server: server}
-
- go func() {
- go srv.Serve(l)
- srv.Stop(killTime)
- }()
- srv.Stop(0)
- select {
- case <-srv.StopChan():
- case <-time.After(timeoutTime):
- t.Fatal("Timed out while waiting for explicit stop to complete")
- }
-}
diff --git a/src/dict2rest/vendor/github.com/stretchr/graceful/tests/main.go b/src/dict2rest/vendor/github.com/stretchr/graceful/tests/main.go
deleted file mode 100644
index 8c8fa20..0000000
--- a/src/dict2rest/vendor/github.com/stretchr/graceful/tests/main.go
+++ /dev/null
@@ -1,40 +0,0 @@
-package main
-
-import (
- "fmt"
- "sync"
-
- "github.com/codegangsta/negroni"
- "github.com/tylerb/graceful"
-)
-
-func main() {
-
- var wg sync.WaitGroup
-
- wg.Add(3)
- go func() {
- n := negroni.New()
- fmt.Println("Launching server on :3000")
- graceful.Run(":3000", 0, n)
- fmt.Println("Terminated server on :3000")
- wg.Done()
- }()
- go func() {
- n := negroni.New()
- fmt.Println("Launching server on :3001")
- graceful.Run(":3001", 0, n)
- fmt.Println("Terminated server on :3001")
- wg.Done()
- }()
- go func() {
- n := negroni.New()
- fmt.Println("Launching server on :3002")
- graceful.Run(":3002", 0, n)
- fmt.Println("Terminated server on :3002")
- wg.Done()
- }()
- fmt.Println("Press ctrl+c. All servers should terminate.")
- wg.Wait()
-
-}