aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/gorilla
diff options
context:
space:
mode:
authorNiall Sheridan <nsheridan@gmail.com>2019-07-07 21:33:44 +0100
committerNiall Sheridan <nsheridan@gmail.com>2019-07-07 21:33:44 +0100
commit8c12c6939aab9106db14ec2d11d983bc5b29fb2c (patch)
treef9dc8a7d167c6355e47a65c52d4eb7b9ea03e6c8 /vendor/github.com/gorilla
parent0bd454cc448b812da6c693b451d86ff4cadbb6b2 (diff)
Switch to modules
Diffstat (limited to 'vendor/github.com/gorilla')
-rw-r--r--vendor/github.com/gorilla/context/LICENSE27
-rw-r--r--vendor/github.com/gorilla/context/README.md10
-rw-r--r--vendor/github.com/gorilla/context/context.go143
-rw-r--r--vendor/github.com/gorilla/context/doc.go88
-rw-r--r--vendor/github.com/gorilla/csrf/AUTHORS20
-rw-r--r--vendor/github.com/gorilla/csrf/Gopkg.lock27
-rw-r--r--vendor/github.com/gorilla/csrf/Gopkg.toml34
-rw-r--r--vendor/github.com/gorilla/csrf/LICENSE26
-rw-r--r--vendor/github.com/gorilla/csrf/README.md237
-rw-r--r--vendor/github.com/gorilla/csrf/context.go29
-rw-r--r--vendor/github.com/gorilla/csrf/context_legacy.go28
-rw-r--r--vendor/github.com/gorilla/csrf/csrf.go279
-rw-r--r--vendor/github.com/gorilla/csrf/doc.go176
-rw-r--r--vendor/github.com/gorilla/csrf/go.mod7
-rw-r--r--vendor/github.com/gorilla/csrf/helpers.go203
-rw-r--r--vendor/github.com/gorilla/csrf/options.go130
-rw-r--r--vendor/github.com/gorilla/csrf/store.go82
-rw-r--r--vendor/github.com/gorilla/handlers/LICENSE22
-rw-r--r--vendor/github.com/gorilla/handlers/README.md55
-rw-r--r--vendor/github.com/gorilla/handlers/canonical.go74
-rw-r--r--vendor/github.com/gorilla/handlers/compress.go148
-rw-r--r--vendor/github.com/gorilla/handlers/cors.go338
-rw-r--r--vendor/github.com/gorilla/handlers/doc.go9
-rw-r--r--vendor/github.com/gorilla/handlers/handlers.go174
-rw-r--r--vendor/github.com/gorilla/handlers/handlers_go18.go21
-rw-r--r--vendor/github.com/gorilla/handlers/handlers_pre18.go7
-rw-r--r--vendor/github.com/gorilla/handlers/logging.go252
-rw-r--r--vendor/github.com/gorilla/handlers/proxy_headers.go120
-rw-r--r--vendor/github.com/gorilla/handlers/recovery.go91
-rw-r--r--vendor/github.com/gorilla/mux/AUTHORS8
-rw-r--r--vendor/github.com/gorilla/mux/ISSUE_TEMPLATE.md11
-rw-r--r--vendor/github.com/gorilla/mux/LICENSE27
-rw-r--r--vendor/github.com/gorilla/mux/README.md649
-rw-r--r--vendor/github.com/gorilla/mux/context_gorilla.go26
-rw-r--r--vendor/github.com/gorilla/mux/context_native.go24
-rw-r--r--vendor/github.com/gorilla/mux/doc.go306
-rw-r--r--vendor/github.com/gorilla/mux/go.mod1
-rw-r--r--vendor/github.com/gorilla/mux/middleware.go72
-rw-r--r--vendor/github.com/gorilla/mux/mux.go588
-rw-r--r--vendor/github.com/gorilla/mux/regexp.go332
-rw-r--r--vendor/github.com/gorilla/mux/route.go763
-rw-r--r--vendor/github.com/gorilla/mux/test_helpers.go19
-rw-r--r--vendor/github.com/gorilla/securecookie/AUTHORS19
-rw-r--r--vendor/github.com/gorilla/securecookie/LICENSE27
-rw-r--r--vendor/github.com/gorilla/securecookie/README.md80
-rw-r--r--vendor/github.com/gorilla/securecookie/doc.go61
-rw-r--r--vendor/github.com/gorilla/securecookie/fuzz.go25
-rw-r--r--vendor/github.com/gorilla/securecookie/securecookie.go646
-rw-r--r--vendor/github.com/gorilla/sessions/AUTHORS43
-rw-r--r--vendor/github.com/gorilla/sessions/LICENSE27
-rw-r--r--vendor/github.com/gorilla/sessions/README.md92
-rw-r--r--vendor/github.com/gorilla/sessions/doc.go198
-rw-r--r--vendor/github.com/gorilla/sessions/go.mod6
-rw-r--r--vendor/github.com/gorilla/sessions/lex.go102
-rw-r--r--vendor/github.com/gorilla/sessions/sessions.go243
-rw-r--r--vendor/github.com/gorilla/sessions/store.go295
56 files changed, 0 insertions, 7547 deletions
diff --git a/vendor/github.com/gorilla/context/LICENSE b/vendor/github.com/gorilla/context/LICENSE
deleted file mode 100644
index 0e5fb87..0000000
--- a/vendor/github.com/gorilla/context/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2012 Rodrigo Moraes. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/gorilla/context/README.md b/vendor/github.com/gorilla/context/README.md
deleted file mode 100644
index 08f8669..0000000
--- a/vendor/github.com/gorilla/context/README.md
+++ /dev/null
@@ -1,10 +0,0 @@
-context
-=======
-[![Build Status](https://travis-ci.org/gorilla/context.png?branch=master)](https://travis-ci.org/gorilla/context)
-
-gorilla/context is a general purpose registry for global request variables.
-
-> Note: gorilla/context, having been born well before `context.Context` existed, does not play well
-> with the shallow copying of the request that [`http.Request.WithContext`](https://golang.org/pkg/net/http/#Request.WithContext) (added to net/http Go 1.7 onwards) performs. You should either use *just* gorilla/context, or moving forward, the new `http.Request.Context()`.
-
-Read the full documentation here: http://www.gorillatoolkit.org/pkg/context
diff --git a/vendor/github.com/gorilla/context/context.go b/vendor/github.com/gorilla/context/context.go
deleted file mode 100644
index 81cb128..0000000
--- a/vendor/github.com/gorilla/context/context.go
+++ /dev/null
@@ -1,143 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package context
-
-import (
- "net/http"
- "sync"
- "time"
-)
-
-var (
- mutex sync.RWMutex
- data = make(map[*http.Request]map[interface{}]interface{})
- datat = make(map[*http.Request]int64)
-)
-
-// Set stores a value for a given key in a given request.
-func Set(r *http.Request, key, val interface{}) {
- mutex.Lock()
- if data[r] == nil {
- data[r] = make(map[interface{}]interface{})
- datat[r] = time.Now().Unix()
- }
- data[r][key] = val
- mutex.Unlock()
-}
-
-// Get returns a value stored for a given key in a given request.
-func Get(r *http.Request, key interface{}) interface{} {
- mutex.RLock()
- if ctx := data[r]; ctx != nil {
- value := ctx[key]
- mutex.RUnlock()
- return value
- }
- mutex.RUnlock()
- return nil
-}
-
-// GetOk returns stored value and presence state like multi-value return of map access.
-func GetOk(r *http.Request, key interface{}) (interface{}, bool) {
- mutex.RLock()
- if _, ok := data[r]; ok {
- value, ok := data[r][key]
- mutex.RUnlock()
- return value, ok
- }
- mutex.RUnlock()
- return nil, false
-}
-
-// GetAll returns all stored values for the request as a map. Nil is returned for invalid requests.
-func GetAll(r *http.Request) map[interface{}]interface{} {
- mutex.RLock()
- if context, ok := data[r]; ok {
- result := make(map[interface{}]interface{}, len(context))
- for k, v := range context {
- result[k] = v
- }
- mutex.RUnlock()
- return result
- }
- mutex.RUnlock()
- return nil
-}
-
-// GetAllOk returns all stored values for the request as a map and a boolean value that indicates if
-// the request was registered.
-func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) {
- mutex.RLock()
- context, ok := data[r]
- result := make(map[interface{}]interface{}, len(context))
- for k, v := range context {
- result[k] = v
- }
- mutex.RUnlock()
- return result, ok
-}
-
-// Delete removes a value stored for a given key in a given request.
-func Delete(r *http.Request, key interface{}) {
- mutex.Lock()
- if data[r] != nil {
- delete(data[r], key)
- }
- mutex.Unlock()
-}
-
-// Clear removes all values stored for a given request.
-//
-// This is usually called by a handler wrapper to clean up request
-// variables at the end of a request lifetime. See ClearHandler().
-func Clear(r *http.Request) {
- mutex.Lock()
- clear(r)
- mutex.Unlock()
-}
-
-// clear is Clear without the lock.
-func clear(r *http.Request) {
- delete(data, r)
- delete(datat, r)
-}
-
-// Purge removes request data stored for longer than maxAge, in seconds.
-// It returns the amount of requests removed.
-//
-// If maxAge <= 0, all request data is removed.
-//
-// This is only used for sanity check: in case context cleaning was not
-// properly set some request data can be kept forever, consuming an increasing
-// amount of memory. In case this is detected, Purge() must be called
-// periodically until the problem is fixed.
-func Purge(maxAge int) int {
- mutex.Lock()
- count := 0
- if maxAge <= 0 {
- count = len(data)
- data = make(map[*http.Request]map[interface{}]interface{})
- datat = make(map[*http.Request]int64)
- } else {
- min := time.Now().Unix() - int64(maxAge)
- for r := range data {
- if datat[r] < min {
- clear(r)
- count++
- }
- }
- }
- mutex.Unlock()
- return count
-}
-
-// ClearHandler wraps an http.Handler and clears request values at the end
-// of a request lifetime.
-func ClearHandler(h http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- defer Clear(r)
- h.ServeHTTP(w, r)
- })
-}
diff --git a/vendor/github.com/gorilla/context/doc.go b/vendor/github.com/gorilla/context/doc.go
deleted file mode 100644
index 448d1bf..0000000
--- a/vendor/github.com/gorilla/context/doc.go
+++ /dev/null
@@ -1,88 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-/*
-Package context stores values shared during a request lifetime.
-
-Note: gorilla/context, having been born well before `context.Context` existed,
-does not play well > with the shallow copying of the request that
-[`http.Request.WithContext`](https://golang.org/pkg/net/http/#Request.WithContext)
-(added to net/http Go 1.7 onwards) performs. You should either use *just*
-gorilla/context, or moving forward, the new `http.Request.Context()`.
-
-For example, a router can set variables extracted from the URL and later
-application handlers can access those values, or it can be used to store
-sessions values to be saved at the end of a request. There are several
-others common uses.
-
-The idea was posted by Brad Fitzpatrick to the go-nuts mailing list:
-
- http://groups.google.com/group/golang-nuts/msg/e2d679d303aa5d53
-
-Here's the basic usage: first define the keys that you will need. The key
-type is interface{} so a key can be of any type that supports equality.
-Here we define a key using a custom int type to avoid name collisions:
-
- package foo
-
- import (
- "github.com/gorilla/context"
- )
-
- type key int
-
- const MyKey key = 0
-
-Then set a variable. Variables are bound to an http.Request object, so you
-need a request instance to set a value:
-
- context.Set(r, MyKey, "bar")
-
-The application can later access the variable using the same key you provided:
-
- func MyHandler(w http.ResponseWriter, r *http.Request) {
- // val is "bar".
- val := context.Get(r, foo.MyKey)
-
- // returns ("bar", true)
- val, ok := context.GetOk(r, foo.MyKey)
- // ...
- }
-
-And that's all about the basic usage. We discuss some other ideas below.
-
-Any type can be stored in the context. To enforce a given type, make the key
-private and wrap Get() and Set() to accept and return values of a specific
-type:
-
- type key int
-
- const mykey key = 0
-
- // GetMyKey returns a value for this package from the request values.
- func GetMyKey(r *http.Request) SomeType {
- if rv := context.Get(r, mykey); rv != nil {
- return rv.(SomeType)
- }
- return nil
- }
-
- // SetMyKey sets a value for this package in the request values.
- func SetMyKey(r *http.Request, val SomeType) {
- context.Set(r, mykey, val)
- }
-
-Variables must be cleared at the end of a request, to remove all values
-that were stored. This can be done in an http.Handler, after a request was
-served. Just call Clear() passing the request:
-
- context.Clear(r)
-
-...or use ClearHandler(), which conveniently wraps an http.Handler to clear
-variables at the end of a request lifetime.
-
-The Routers from the packages gorilla/mux and gorilla/pat call Clear()
-so if you are using either of them you don't need to clear the context manually.
-*/
-package context
diff --git a/vendor/github.com/gorilla/csrf/AUTHORS b/vendor/github.com/gorilla/csrf/AUTHORS
deleted file mode 100644
index 4e84c37..0000000
--- a/vendor/github.com/gorilla/csrf/AUTHORS
+++ /dev/null
@@ -1,20 +0,0 @@
-# This is the official list of gorilla/csrf authors for copyright purposes.
-# Please keep the list sorted.
-
-adiabatic <adiabatic@users.noreply.github.com>
-Google LLC (https://opensource.google.com)
-jamesgroat <james@groat.com>
-Joshua Carp <jm.carp@gmail.com>
-Kamil Kisiel <kamil@kamilkisiel.net>
-Kevin Burke <kev@inburke.com>
-Kévin Dunglas <dunglas@gmail.com>
-Kristoffer Berdal <web@flexd.net>
-Martin Angers <martin.n.angers@gmail.com>
-Matt Silverlock <matt@eatsleeprepeat.net>
-Philip I. Thomas <mail@philipithomas.com>
-Richard Musiol <mail@richard-musiol.de>
-Seth Hoenig <seth.a.hoenig@gmail.com>
-Stefano Vettorazzi <stefanovc@gmail.com>
-Wayne Ashley Berry <wayneashleyberry@gmail.com>
-田浩浩 <llitfkitfk@gmail.com>
-陈东海 <cdh_cjx@163.com>
diff --git a/vendor/github.com/gorilla/csrf/Gopkg.lock b/vendor/github.com/gorilla/csrf/Gopkg.lock
deleted file mode 100644
index 5db9540..0000000
--- a/vendor/github.com/gorilla/csrf/Gopkg.lock
+++ /dev/null
@@ -1,27 +0,0 @@
-# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
-
-
-[[projects]]
- name = "github.com/gorilla/context"
- packages = ["."]
- revision = "1ea25387ff6f684839d82767c1733ff4d4d15d0a"
- version = "v1.1"
-
-[[projects]]
- name = "github.com/gorilla/securecookie"
- packages = ["."]
- revision = "667fe4e3466a040b780561fe9b51a83a3753eefc"
- version = "v1.1"
-
-[[projects]]
- name = "github.com/pkg/errors"
- packages = ["."]
- revision = "645ef00459ed84a119197bfb8d8205042c6df63d"
- version = "v0.8.0"
-
-[solve-meta]
- analyzer-name = "dep"
- analyzer-version = 1
- inputs-digest = "1695686bc8fa0eb76df9fe8c5ca473686071ddcf795a0595a9465a03e8ac9bef"
- solver-name = "gps-cdcl"
- solver-version = 1
diff --git a/vendor/github.com/gorilla/csrf/Gopkg.toml b/vendor/github.com/gorilla/csrf/Gopkg.toml
deleted file mode 100644
index 02837b1..0000000
--- a/vendor/github.com/gorilla/csrf/Gopkg.toml
+++ /dev/null
@@ -1,34 +0,0 @@
-
-# Gopkg.toml example
-#
-# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
-# for detailed Gopkg.toml documentation.
-#
-# required = ["github.com/user/thing/cmd/thing"]
-# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
-#
-# [[constraint]]
-# name = "github.com/user/project"
-# version = "1.0.0"
-#
-# [[constraint]]
-# name = "github.com/user/project2"
-# branch = "dev"
-# source = "github.com/myfork/project2"
-#
-# [[override]]
-# name = "github.com/x/y"
-# version = "2.4.0"
-
-
-[[constraint]]
- name = "github.com/gorilla/context"
- version = "1.1.0"
-
-[[constraint]]
- name = "github.com/gorilla/securecookie"
- version = "1.1.0"
-
-[[constraint]]
- name = "github.com/pkg/errors"
- version = "0.8.0"
diff --git a/vendor/github.com/gorilla/csrf/LICENSE b/vendor/github.com/gorilla/csrf/LICENSE
deleted file mode 100644
index c1eb344..0000000
--- a/vendor/github.com/gorilla/csrf/LICENSE
+++ /dev/null
@@ -1,26 +0,0 @@
-Copyright (c) 2015-2018, The Gorilla Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification,
-are permitted provided that the following conditions are met:
-
-1. Redistributions of source code must retain the above copyright notice, this
-list of conditions and the following disclaimer.
-
-2. 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.
-
-3. Neither the name of the copyright holder nor the names of its contributors
-may be used to endorse or promote products derived from this software without
-specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
-ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
-ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/gorilla/csrf/README.md b/vendor/github.com/gorilla/csrf/README.md
deleted file mode 100644
index 6bcca60..0000000
--- a/vendor/github.com/gorilla/csrf/README.md
+++ /dev/null
@@ -1,237 +0,0 @@
-# gorilla/csrf
-
-[![GoDoc](https://godoc.org/github.com/gorilla/csrf?status.svg)](https://godoc.org/github.com/gorilla/csrf) [![Build Status](https://travis-ci.org/gorilla/csrf.svg?branch=master)](https://travis-ci.org/gorilla/csrf) [![Sourcegraph](https://sourcegraph.com/github.com/gorilla/csrf/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/csrf?badge)
-
-gorilla/csrf is a HTTP middleware library that provides [cross-site request
-forgery](http://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/) (CSRF)
-protection. It includes:
-
-- The `csrf.Protect` middleware/handler provides CSRF protection on routes
- attached to a router or a sub-router.
-- A `csrf.Token` function that provides the token to pass into your response,
- whether that be a HTML form or a JSON response body.
-- ... and a `csrf.TemplateField` helper that you can pass into your `html/template`
- templates to replace a `{{ .csrfField }}` template tag with a hidden input
- field.
-
-gorilla/csrf is designed to work with any Go web framework, including:
-
-- The [Gorilla](http://www.gorillatoolkit.org/) toolkit
-- Go's built-in [net/http](http://golang.org/pkg/net/http/) package
-- [Goji](https://goji.io) - see the [tailored fork](https://github.com/goji/csrf)
-- [Gin](https://github.com/gin-gonic/gin)
-- [Echo](https://github.com/labstack/echo)
-- ... and any other router/framework that rallies around Go's `http.Handler` interface.
-
-gorilla/csrf is also compatible with middleware 'helper' libraries like
-[Alice](https://github.com/justinas/alice) and [Negroni](https://github.com/codegangsta/negroni).
-
-## Install
-
-With a properly configured Go toolchain:
-
-```sh
-go get github.com/gorilla/csrf
-```
-
-## Examples
-
-- [HTML Forms](#html-forms)
-- [JavaScript Apps](#javascript-applications)
-- [Google App Engine](#google-app-engine)
-- [Setting Options](#setting-options)
-
-gorilla/csrf is easy to use: add the middleware to your router with
-the below:
-
-```go
-CSRF := csrf.Protect([]byte("32-byte-long-auth-key"))
-http.ListenAndServe(":8000", CSRF(r))
-```
-
-...and then collect the token with `csrf.Token(r)` in your handlers before
-passing it to the template, JSON body or HTTP header (see below).
-
-Note that the authentication key passed to `csrf.Protect([]byte(key))` should be
-32-bytes long and persist across application restarts. Generating a random key
-won't allow you to authenticate existing cookies and will break your CSRF
-validation.
-
-gorilla/csrf inspects the HTTP headers (first) and form body (second) on
-subsequent POST/PUT/PATCH/DELETE/etc. requests for the token.
-
-### HTML Forms
-
-Here's the common use-case: HTML forms you want to provide CSRF protection for,
-in order to protect malicious POST requests being made:
-
-```go
-package main
-
-import (
- "net/http"
-
- "github.com/gorilla/csrf"
- "github.com/gorilla/mux"
-)
-
-func main() {
- r := mux.NewRouter()
- r.HandleFunc("/signup", ShowSignupForm)
- // All POST requests without a valid token will return HTTP 403 Forbidden.
- // We should also ensure that our mutating (non-idempotent) handler only
- // matches on POST requests. We can check that here, at the router level, or
- // within the handler itself via r.Method.
- r.HandleFunc("/signup/post", SubmitSignupForm).Methods("POST")
-
- // Add the middleware to your router by wrapping it.
- http.ListenAndServe(":8000",
- csrf.Protect([]byte("32-byte-long-auth-key"))(r))
- // PS: Don't forget to pass csrf.Secure(false) if you're developing locally
- // over plain HTTP (just don't leave it on in production).
-}
-
-func ShowSignupForm(w http.ResponseWriter, r *http.Request) {
- // signup_form.tmpl just needs a {{ .csrfField }} template tag for
- // csrf.TemplateField to inject the CSRF token into. Easy!
- t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{}{
- csrf.TemplateTag: csrf.TemplateField(r),
- })
- // We could also retrieve the token directly from csrf.Token(r) and
- // set it in the request header - w.Header.Set("X-CSRF-Token", token)
- // This is useful if you're sending JSON to clients or a front-end JavaScript
- // framework.
-}
-
-func SubmitSignupForm(w http.ResponseWriter, r *http.Request) {
- // We can trust that requests making it this far have satisfied
- // our CSRF protection requirements.
-}
-```
-
-Note that the CSRF middleware will (by necessity) consume the request body if the
-token is passed via POST form values. If you need to consume this in your
-handler, insert your own middleware earlier in the chain to capture the request
-body.
-
-### JavaScript Applications
-
-This approach is useful if you're using a front-end JavaScript framework like
-React, Ember or Angular, or are providing a JSON API.
-
-We'll also look at applying selective CSRF protection using
-[gorilla/mux's](http://www.gorillatoolkit.org/pkg/mux) sub-routers,
-as we don't handle any POST/PUT/DELETE requests with our top-level router.
-
-```go
-package main
-
-import (
- "github.com/gorilla/csrf"
- "github.com/gorilla/mux"
-)
-
-func main() {
- r := mux.NewRouter()
-
- api := r.PathPrefix("/api").Subrouter()
- api.HandleFunc("/user/{id}", GetUser).Methods("GET")
-
- http.ListenAndServe(":8000",
- csrf.Protect([]byte("32-byte-long-auth-key"))(r))
-}
-
-func GetUser(w http.ResponseWriter, r *http.Request) {
- // Authenticate the request, get the id from the route params,
- // and fetch the user from the DB, etc.
-
- // Get the token and pass it in the CSRF header. Our JSON-speaking client
- // or JavaScript framework can now read the header and return the token in
- // in its own "X-CSRF-Token" request header on the subsequent POST.
- w.Header().Set("X-CSRF-Token", csrf.Token(r))
- b, err := json.Marshal(user)
- if err != nil {
- http.Error(w, err.Error(), 500)
- return
- }
-
- w.Write(b)
-}
-```
-
-### Google App Engine
-
-If you're using [Google App
-Engine](https://cloud.google.com/appengine/docs/go/how-requests-are-handled#Go_Requests_and_HTTP),
-which doesn't allow you to hook into the default `http.ServeMux` directly,
-you can still use gorilla/csrf (and gorilla/mux):
-
-```go
-package app
-
-// Remember: appengine has its own package main
-func init() {
- r := mux.NewRouter()
- r.HandleFunc("/", IndexHandler)
- // ...
-
- // We pass our CSRF-protected router to the DefaultServeMux
- http.Handle("/", csrf.Protect([]byte(your-key))(r))
-}
-```
-
-### Setting Options
-
-What about providing your own error handler and changing the HTTP header the
-package inspects on requests? (i.e. an existing API you're porting to Go). Well,
-gorilla/csrf provides options for changing these as you see fit:
-
-```go
-func main() {
- CSRF := csrf.Protect(
- []byte("a-32-byte-long-key-goes-here"),
- csrf.RequestHeader("Authenticity-Token"),
- csrf.FieldName("authenticity_token"),
- csrf.ErrorHandler(http.HandlerFunc(serverError(403))),
- )
-
- r := mux.NewRouter()
- r.HandleFunc("/signup", GetSignupForm)
- r.HandleFunc("/signup/post", PostSignupForm)
-
- http.ListenAndServe(":8000", CSRF(r))
-}
-```
-
-Not too bad, right?
-
-If there's something you're confused about or a feature you would like to see
-added, open an issue.
-
-## Design Notes
-
-Getting CSRF protection right is important, so here's some background:
-
-- This library generates unique-per-request (masked) tokens as a mitigation
- against the [BREACH attack](http://breachattack.com/).
-- The 'base' (unmasked) token is stored in the session, which means that
- multiple browser tabs won't cause a user problems as their per-request token
- is compared with the base token.
-- Operates on a "whitelist only" approach where safe (non-mutating) HTTP methods
- (GET, HEAD, OPTIONS, TRACE) are the _only_ methods where token validation is not
- enforced.
-- The design is based on the battle-tested
- [Django](https://docs.djangoproject.com/en/1.8/ref/csrf/) and [Ruby on
- Rails](http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html)
- approaches.
-- Cookies are authenticated and based on the [securecookie](https://github.com/gorilla/securecookie)
- library. They're also Secure (issued over HTTPS only) and are HttpOnly
- by default, because sane defaults are important.
-- Go's `crypto/rand` library is used to generate the 32 byte (256 bit) tokens
- and the one-time-pad used for masking them.
-
-This library does not seek to be adventurous.
-
-## License
-
-BSD licensed. See the LICENSE file for details.
diff --git a/vendor/github.com/gorilla/csrf/context.go b/vendor/github.com/gorilla/csrf/context.go
deleted file mode 100644
index d8bb42f..0000000
--- a/vendor/github.com/gorilla/csrf/context.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// +build go1.7
-
-package csrf
-
-import (
- "context"
- "net/http"
-
- "github.com/pkg/errors"
-)
-
-func contextGet(r *http.Request, key string) (interface{}, error) {
- val := r.Context().Value(key)
- if val == nil {
- return nil, errors.Errorf("no value exists in the context for key %q", key)
- }
-
- return val, nil
-}
-
-func contextSave(r *http.Request, key string, val interface{}) *http.Request {
- ctx := r.Context()
- ctx = context.WithValue(ctx, key, val)
- return r.WithContext(ctx)
-}
-
-func contextClear(r *http.Request) {
- // no-op for go1.7+
-}
diff --git a/vendor/github.com/gorilla/csrf/context_legacy.go b/vendor/github.com/gorilla/csrf/context_legacy.go
deleted file mode 100644
index f88c9eb..0000000
--- a/vendor/github.com/gorilla/csrf/context_legacy.go
+++ /dev/null
@@ -1,28 +0,0 @@
-// +build !go1.7
-
-package csrf
-
-import (
- "net/http"
-
- "github.com/gorilla/context"
-
- "github.com/pkg/errors"
-)
-
-func contextGet(r *http.Request, key string) (interface{}, error) {
- if val, ok := context.GetOk(r, key); ok {
- return val, nil
- }
-
- return nil, errors.Errorf("no value exists in the context for key %q", key)
-}
-
-func contextSave(r *http.Request, key string, val interface{}) *http.Request {
- context.Set(r, key, val)
- return r
-}
-
-func contextClear(r *http.Request) {
- context.Clear(r)
-}
diff --git a/vendor/github.com/gorilla/csrf/csrf.go b/vendor/github.com/gorilla/csrf/csrf.go
deleted file mode 100644
index cc7878f..0000000
--- a/vendor/github.com/gorilla/csrf/csrf.go
+++ /dev/null
@@ -1,279 +0,0 @@
-package csrf
-
-import (
- "fmt"
- "net/http"
- "net/url"
-
- "github.com/pkg/errors"
-
- "github.com/gorilla/securecookie"
-)
-
-// CSRF token length in bytes.
-const tokenLength = 32
-
-// Context/session keys & prefixes
-const (
- tokenKey string = "gorilla.csrf.Token"
- formKey string = "gorilla.csrf.Form"
- errorKey string = "gorilla.csrf.Error"
- skipCheckKey string = "gorilla.csrf.Skip"
- cookieName string = "_gorilla_csrf"
- errorPrefix string = "gorilla/csrf: "
-)
-
-var (
- // The name value used in form fields.
- fieldName = tokenKey
- // defaultAge sets the default MaxAge for cookies.
- defaultAge = 3600 * 12
- // The default HTTP request header to inspect
- headerName = "X-CSRF-Token"
- // Idempotent (safe) methods as defined by RFC7231 section 4.2.2.
- safeMethods = []string{"GET", "HEAD", "OPTIONS", "TRACE"}
-)
-
-// TemplateTag provides a default template tag - e.g. {{ .csrfField }} - for use
-// with the TemplateField function.
-var TemplateTag = "csrfField"
-
-var (
- // ErrNoReferer is returned when a HTTPS request provides an empty Referer
- // header.
- ErrNoReferer = errors.New("referer not supplied")
- // ErrBadReferer is returned when the scheme & host in the URL do not match
- // the supplied Referer header.
- ErrBadReferer = errors.New("referer invalid")
- // ErrNoToken is returned if no CSRF token is supplied in the request.
- ErrNoToken = errors.New("CSRF token not found in request")
- // ErrBadToken is returned if the CSRF token in the request does not match
- // the token in the session, or is otherwise malformed.
- ErrBadToken = errors.New("CSRF token invalid")
-)
-
-type csrf struct {
- h http.Handler
- sc *securecookie.SecureCookie
- st store
- opts options
-}
-
-// options contains the optional settings for the CSRF middleware.
-type options struct {
- MaxAge int
- Domain string
- Path string
- // Note that the function and field names match the case of the associated
- // http.Cookie field instead of the "correct" HTTPOnly name that golint suggests.
- HttpOnly bool
- Secure bool
- RequestHeader string
- FieldName string
- ErrorHandler http.Handler
- CookieName string
-}
-
-// Protect is HTTP middleware that provides Cross-Site Request Forgery
-// protection.
-//
-// It securely generates a masked (unique-per-request) token that
-// can be embedded in the HTTP response (e.g. form field or HTTP header).
-// The original (unmasked) token is stored in the session, which is inaccessible
-// by an attacker (provided you are using HTTPS). Subsequent requests are
-// expected to include this token, which is compared against the session token.
-// Requests that do not provide a matching token are served with a HTTP 403
-// 'Forbidden' error response.
-//
-// Example:
-// package main
-//
-// import (
-// "html/template"
-//
-// "github.com/gorilla/csrf"
-// "github.com/gorilla/mux"
-// )
-//
-// var t = template.Must(template.New("signup_form.tmpl").Parse(form))
-//
-// func main() {
-// r := mux.NewRouter()
-//
-// r.HandleFunc("/signup", GetSignupForm)
-// // POST requests without a valid token will return a HTTP 403 Forbidden.
-// r.HandleFunc("/signup/post", PostSignupForm)
-//
-// // Add the middleware to your router.
-// http.ListenAndServe(":8000",
-// // Note that the authentication key provided should be 32 bytes
-// // long and persist across application restarts.
-// csrf.Protect([]byte("32-byte-long-auth-key"))(r))
-// }
-//
-// func GetSignupForm(w http.ResponseWriter, r *http.Request) {
-// // signup_form.tmpl just needs a {{ .csrfField }} template tag for
-// // csrf.TemplateField to inject the CSRF token into. Easy!
-// t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{}{
-// csrf.TemplateTag: csrf.TemplateField(r),
-// })
-// // We could also retrieve the token directly from csrf.Token(r) and
-// // set it in the request header - w.Header.Set("X-CSRF-Token", token)
-// // This is useful if you're sending JSON to clients or a front-end JavaScript
-// // framework.
-// }
-//
-func Protect(authKey []byte, opts ...Option) func(http.Handler) http.Handler {
- return func(h http.Handler) http.Handler {
- cs := parseOptions(h, opts...)
-
- // Set the defaults if no options have been specified
- if cs.opts.ErrorHandler == nil {
- cs.opts.ErrorHandler = http.HandlerFunc(unauthorizedHandler)
- }
-
- if cs.opts.MaxAge < 0 {
- // Default of 12 hours
- cs.opts.MaxAge = defaultAge
- }
-
- if cs.opts.FieldName == "" {
- cs.opts.FieldName = fieldName
- }
-
- if cs.opts.CookieName == "" {
- cs.opts.CookieName = cookieName
- }
-
- if cs.opts.RequestHeader == "" {
- cs.opts.RequestHeader = headerName
- }
-
- // Create an authenticated securecookie instance.
- if cs.sc == nil {
- cs.sc = securecookie.New(authKey, nil)
- // Use JSON serialization (faster than one-off gob encoding)
- cs.sc.SetSerializer(securecookie.JSONEncoder{})
- // Set the MaxAge of the underlying securecookie.
- cs.sc.MaxAge(cs.opts.MaxAge)
- }
-
- if cs.st == nil {
- // Default to the cookieStore
- cs.st = &cookieStore{
- name: cs.opts.CookieName,
- maxAge: cs.opts.MaxAge,
- secure: cs.opts.Secure,
- httpOnly: cs.opts.HttpOnly,
- path: cs.opts.Path,
- domain: cs.opts.Domain,
- sc: cs.sc,
- }
- }
-
- return cs
- }
-}
-
-// Implements http.Handler for the csrf type.
-func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- // Skip the check if directed to. This should always be a bool.
- if val, err := contextGet(r, skipCheckKey); err == nil {
- if skip, ok := val.(bool); ok {
- if skip {
- cs.h.ServeHTTP(w, r)
- return
- }
- }
- }
-
- // Retrieve the token from the session.
- // An error represents either a cookie that failed HMAC validation
- // or that doesn't exist.
- realToken, err := cs.st.Get(r)
- if err != nil || len(realToken) != tokenLength {
- // If there was an error retrieving the token, the token doesn't exist
- // yet, or it's the wrong length, generate a new token.
- // Note that the new token will (correctly) fail validation downstream
- // as it will no longer match the request token.
- realToken, err = generateRandomBytes(tokenLength)
- if err != nil {
- r = envError(r, err)
- cs.opts.ErrorHandler.ServeHTTP(w, r)
- return
- }
-
- // Save the new (real) token in the session store.
- err = cs.st.Save(realToken, w)
- if err != nil {
- r = envError(r, err)
- cs.opts.ErrorHandler.ServeHTTP(w, r)
- return
- }
- }
-
- // Save the masked token to the request context
- r = contextSave(r, tokenKey, mask(realToken, r))
- // Save the field name to the request context
- r = contextSave(r, formKey, cs.opts.FieldName)
-
- // HTTP methods not defined as idempotent ("safe") under RFC7231 require
- // inspection.
- if !contains(safeMethods, r.Method) {
- // Enforce an origin check for HTTPS connections. As per the Django CSRF
- // implementation (https://goo.gl/vKA7GE) the Referer header is almost
- // always present for same-domain HTTP requests.
- if r.URL.Scheme == "https" {
- // Fetch the Referer value. Call the error handler if it's empty or
- // otherwise fails to parse.
- referer, err := url.Parse(r.Referer())
- if err != nil || referer.String() == "" {
- r = envError(r, ErrNoReferer)
- cs.opts.ErrorHandler.ServeHTTP(w, r)
- return
- }
-
- if sameOrigin(r.URL, referer) == false {
- r = envError(r, ErrBadReferer)
- cs.opts.ErrorHandler.ServeHTTP(w, r)
- return
- }
- }
-
- // If the token returned from the session store is nil for non-idempotent
- // ("unsafe") methods, call the error handler.
- if realToken == nil {
- r = envError(r, ErrNoToken)
- cs.opts.ErrorHandler.ServeHTTP(w, r)
- return
- }
-
- // Retrieve the combined token (pad + masked) token and unmask it.
- requestToken := unmask(cs.requestToken(r))
-
- // Compare the request token against the real token
- if !compareTokens(requestToken, realToken) {
- r = envError(r, ErrBadToken)
- cs.opts.ErrorHandler.ServeHTTP(w, r)
- return
- }
-
- }
-
- // Set the Vary: Cookie header to protect clients from caching the response.
- w.Header().Add("Vary", "Cookie")
-
- // Call the wrapped handler/router on success.
- cs.h.ServeHTTP(w, r)
- // Clear the request context after the handler has completed.
- contextClear(r)
-}
-
-// unauthorizedhandler sets a HTTP 403 Forbidden status and writes the
-// CSRF failure reason to the response.
-func unauthorizedHandler(w http.ResponseWriter, r *http.Request) {
- http.Error(w, fmt.Sprintf("%s - %s",
- http.StatusText(http.StatusForbidden), FailureReason(r)),
- http.StatusForbidden)
- return
-}
diff --git a/vendor/github.com/gorilla/csrf/doc.go b/vendor/github.com/gorilla/csrf/doc.go
deleted file mode 100644
index 503c948..0000000
--- a/vendor/github.com/gorilla/csrf/doc.go
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
-Package csrf (gorilla/csrf) provides Cross Site Request Forgery (CSRF)
-prevention middleware for Go web applications & services.
-
-It includes:
-
-* The `csrf.Protect` middleware/handler provides CSRF protection on routes
-attached to a router or a sub-router.
-
-* A `csrf.Token` function that provides the token to pass into your response,
-whether that be a HTML form or a JSON response body.
-
-* ... and a `csrf.TemplateField` helper that you can pass into your `html/template`
-templates to replace a `{{ .csrfField }}` template tag with a hidden input
-field.
-
-gorilla/csrf is easy to use: add the middleware to individual handlers with
-the below:
-
- CSRF := csrf.Protect([]byte("32-byte-long-auth-key"))
- http.HandlerFunc("/route", CSRF(YourHandler))
-
-... and then collect the token with `csrf.Token(r)` before passing it to the
-template, JSON body or HTTP header (you pick!). gorilla/csrf inspects the form body
-(first) and HTTP headers (second) on subsequent POST/PUT/PATCH/DELETE/etc. requests
-for the token.
-
-Note that the authentication key passed to `csrf.Protect([]byte(key))` should be
-32-bytes long and persist across application restarts. Generating a random key
-won't allow you to authenticate existing cookies and will break your CSRF
-validation.
-
-Here's the common use-case: HTML forms you want to provide CSRF protection for,
-in order to protect malicious POST requests being made:
-
- package main
-
- import (
- "fmt"
- "html/template"
- "net/http"
-
- "github.com/gorilla/csrf"
- "github.com/gorilla/mux"
- )
-
- var form = `
- <html>
- <head>
- <title>Sign Up!</title>
- </head>
- <body>
- <form method="POST" action="/signup/post" accept-charset="UTF-8">
- <input type="text" name="name">
- <input type="text" name="email">
- <!--
- The default template tag used by the CSRF middleware .
- This will be replaced with a hidden <input> field containing the
- masked CSRF token.
- -->
- {{ .csrfField }}
- <input type="submit" value="Sign up!">
- </form>
- </body>
- </html>
- `
-
- var t = template.Must(template.New("signup_form.tmpl").Parse(form))
-
- func main() {
- r := mux.NewRouter()
- r.HandleFunc("/signup", ShowSignupForm)
- // All POST requests without a valid token will return HTTP 403 Forbidden.
- // We should also ensure that our mutating (non-idempotent) handler only
- // matches on POST requests. We can check that here, at the router level, or
- // within the handler itself via r.Method.
- r.HandleFunc("/signup/post", SubmitSignupForm).Methods("POST")
-
- // Add the middleware to your router by wrapping it.
- http.ListenAndServe(":8000",
- csrf.Protect([]byte("32-byte-long-auth-key"))(r))
- // PS: Don't forget to pass csrf.Secure(false) if you're developing locally
- // over plain HTTP (just don't leave it on in production).
- }
-
- func ShowSignupForm(w http.ResponseWriter, r *http.Request) {
- // signup_form.tmpl just needs a {{ .csrfField }} template tag for
- // csrf.TemplateField to inject the CSRF token into. Easy!
- t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{}{
- csrf.TemplateTag: csrf.TemplateField(r),
- })
- }
-
- func SubmitSignupForm(w http.ResponseWriter, r *http.Request) {
- // We can trust that requests making it this far have satisfied
- // our CSRF protection requirements.
- fmt.Fprintf(w, "%v\n", r.PostForm)
- }
-
-Note that the CSRF middleware will (by necessity) consume the request body if the
-token is passed via POST form values. If you need to consume this in your
-handler, insert your own middleware earlier in the chain to capture the request
-body.
-
-You can also send the CSRF token in the response header. This approach is useful
-if you're using a front-end JavaScript framework like Ember or Angular, or are
-providing a JSON API:
-
- package main
-
- import (
- "github.com/gorilla/csrf"
- "github.com/gorilla/mux"
- )
-
- func main() {
- r := mux.NewRouter()
-
- api := r.PathPrefix("/api").Subrouter()
- api.HandleFunc("/user/:id", GetUser).Methods("GET")
-
- http.ListenAndServe(":8000",
- csrf.Protect([]byte("32-byte-long-auth-key"))(r))
- }
-
- func GetUser(w http.ResponseWriter, r *http.Request) {
- // Authenticate the request, get the id from the route params,
- // and fetch the user from the DB, etc.
-
- // Get the token and pass it in the CSRF header. Our JSON-speaking client
- // or JavaScript framework can now read the header and return the token in
- // in its own "X-CSRF-Token" request header on the subsequent POST.
- w.Header().Set("X-CSRF-Token", csrf.Token(r))
- b, err := json.Marshal(user)
- if err != nil {
- http.Error(w, err.Error(), 500)
- return
- }
-
- w.Write(b)
- }
-
-If you're writing a client that's supposed to mimic browser behavior, make sure to
-send back the CSRF cookie (the default name is _gorilla_csrf, but this can be changed
-with the CookieName Option) along with either the X-CSRF-Token header or the gorilla.csrf.Token form field.
-
-In addition: getting CSRF protection right is important, so here's some background:
-
-* This library generates unique-per-request (masked) tokens as a mitigation
-against the BREACH attack (http://breachattack.com/).
-
-* The 'base' (unmasked) token is stored in the session, which means that
-multiple browser tabs won't cause a user problems as their per-request token
-is compared with the base token.
-
-* Operates on a "whitelist only" approach where safe (non-mutating) HTTP methods
-(GET, HEAD, OPTIONS, TRACE) are the *only* methods where token validation is not
-enforced.
-
-* The design is based on the battle-tested Django
-(https://docs.djangoproject.com/en/1.8/ref/csrf/) and Ruby on Rails
-(http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html)
-approaches.
-
-* Cookies are authenticated and based on the securecookie
-(https://github.com/gorilla/securecookie) library. They're also Secure (issued
-over HTTPS only) and are HttpOnly by default, because sane defaults are
-important.
-
-* Go's `crypto/rand` library is used to generate the 32 byte (256 bit) tokens
-and the one-time-pad used for masking them.
-
-This library does not seek to be adventurous.
-
-*/
-package csrf
diff --git a/vendor/github.com/gorilla/csrf/go.mod b/vendor/github.com/gorilla/csrf/go.mod
deleted file mode 100644
index 2d2ce4d..0000000
--- a/vendor/github.com/gorilla/csrf/go.mod
+++ /dev/null
@@ -1,7 +0,0 @@
-module github.com/gorilla/csrf
-
-require (
- github.com/gorilla/context v1.1.1
- github.com/gorilla/securecookie v1.1.1
- github.com/pkg/errors v0.8.0
-)
diff --git a/vendor/github.com/gorilla/csrf/helpers.go b/vendor/github.com/gorilla/csrf/helpers.go
deleted file mode 100644
index 3dacfd2..0000000
--- a/vendor/github.com/gorilla/csrf/helpers.go
+++ /dev/null
@@ -1,203 +0,0 @@
-package csrf
-
-import (
- "crypto/rand"
- "crypto/subtle"
- "encoding/base64"
- "fmt"
- "html/template"
- "net/http"
- "net/url"
-)
-
-// Token returns a masked CSRF token ready for passing into HTML template or
-// a JSON response body. An empty token will be returned if the middleware
-// has not been applied (which will fail subsequent validation).
-func Token(r *http.Request) string {
- if val, err := contextGet(r, tokenKey); err == nil {
- if maskedToken, ok := val.(string); ok {
- return maskedToken
- }
- }
-
- return ""
-}
-
-// FailureReason makes CSRF validation errors available in the request context.
-// This is useful when you want to log the cause of the error or report it to
-// client.
-func FailureReason(r *http.Request) error {
- if val, err := contextGet(r, errorKey); err == nil {
- if err, ok := val.(error); ok {
- return err
- }
- }
-
- return nil
-}
-
-// UnsafeSkipCheck will skip the CSRF check for any requests. This must be
-// called before the CSRF middleware.
-//
-// Note: You should not set this without otherwise securing the request from
-// CSRF attacks. The primary use-case for this function is to turn off CSRF
-// checks for non-browser clients using authorization tokens against your API.
-func UnsafeSkipCheck(r *http.Request) *http.Request {
- return contextSave(r, skipCheckKey, true)
-}
-
-// TemplateField is a template helper for html/template that provides an <input> field
-// populated with a CSRF token.
-//
-// Example:
-//
-// // The following tag in our form.tmpl template:
-// {{ .csrfField }}
-//
-// // ... becomes:
-// <input type="hidden" name="gorilla.csrf.Token" value="<token>">
-//
-func TemplateField(r *http.Request) template.HTML {
- if name, err := contextGet(r, formKey); err == nil {
- fragment := fmt.Sprintf(`<input type="hidden" name="%s" value="%s">`,
- name, Token(r))
-
- return template.HTML(fragment)
- }
-
- return template.HTML("")
-}
-
-// mask returns a unique-per-request token to mitigate the BREACH attack
-// as per http://breachattack.com/#mitigations
-//
-// The token is generated by XOR'ing a one-time-pad and the base (session) CSRF
-// token and returning them together as a 64-byte slice. This effectively
-// randomises the token on a per-request basis without breaking multiple browser
-// tabs/windows.
-func mask(realToken []byte, r *http.Request) string {
- otp, err := generateRandomBytes(tokenLength)
- if err != nil {
- return ""
- }
-
- // XOR the OTP with the real token to generate a masked token. Append the
- // OTP to the front of the masked token to allow unmasking in the subsequent
- // request.
- return base64.StdEncoding.EncodeToString(append(otp, xorToken(otp, realToken)...))
-}
-
-// unmask splits the issued token (one-time-pad + masked token) and returns the
-// unmasked request token for comparison.
-func unmask(issued []byte) []byte {
- // Issued tokens are always masked and combined with the pad.
- if len(issued) != tokenLength*2 {
- return nil
- }
-
- // We now know the length of the byte slice.
- otp := issued[tokenLength:]
- masked := issued[:tokenLength]
-
- // Unmask the token by XOR'ing it against the OTP used to mask it.
- return xorToken(otp, masked)
-}
-
-// requestToken returns the issued token (pad + masked token) from the HTTP POST
-// body or HTTP header. It will return nil if the token fails to decode.
-func (cs *csrf) requestToken(r *http.Request) []byte {
- // 1. Check the HTTP header first.
- issued := r.Header.Get(cs.opts.RequestHeader)
-
- // 2. Fall back to the POST (form) value.
- if issued == "" {
- issued = r.PostFormValue(cs.opts.FieldName)
- }
-
- // 3. Finally, fall back to the multipart form (if set).
- if issued == "" && r.MultipartForm != nil {
- vals := r.MultipartForm.Value[cs.opts.FieldName]
-
- if len(vals) > 0 {
- issued = vals[0]
- }
- }
-
- // Decode the "issued" (pad + masked) token sent in the request. Return a
- // nil byte slice on a decoding error (this will fail upstream).
- decoded, err := base64.StdEncoding.DecodeString(issued)
- if err != nil {
- return nil
- }
-
- return decoded
-}
-
-// generateRandomBytes returns securely generated random bytes.
-// It will return an error if the system's secure random number generator
-// fails to function correctly.
-func generateRandomBytes(n int) ([]byte, error) {
- b := make([]byte, n)
- _, err := rand.Read(b)
- // err == nil only if len(b) == n
- if err != nil {
- return nil, err
- }
-
- return b, nil
-
-}
-
-// sameOrigin returns true if URLs a and b share the same origin. The same
-// origin is defined as host (which includes the port) and scheme.
-func sameOrigin(a, b *url.URL) bool {
- return (a.Scheme == b.Scheme && a.Host == b.Host)
-}
-
-// compare securely (constant-time) compares the unmasked token from the request
-// against the real token from the session.
-func compareTokens(a, b []byte) bool {
- // This is required as subtle.ConstantTimeCompare does not check for equal
- // lengths in Go versions prior to 1.3.
- if len(a) != len(b) {
- return false
- }
-
- return subtle.ConstantTimeCompare(a, b) == 1
-}
-
-// xorToken XORs tokens ([]byte) to provide unique-per-request CSRF tokens. It
-// will return a masked token if the base token is XOR'ed with a one-time-pad.
-// An unmasked token will be returned if a masked token is XOR'ed with the
-// one-time-pad used to mask it.
-func xorToken(a, b []byte) []byte {
- n := len(a)
- if len(b) < n {
- n = len(b)
- }
-
- res := make([]byte, n)
-
- for i := 0; i < n; i++ {
- res[i] = a[i] ^ b[i]
- }
-
- return res
-}
-
-// contains is a helper function to check if a string exists in a slice - e.g.
-// whether a HTTP method exists in a list of safe methods.
-func contains(vals []string, s string) bool {
- for _, v := range vals {
- if v == s {
- return true
- }
- }
-
- return false
-}
-
-// envError stores a CSRF error in the request context.
-func envError(r *http.Request, err error) *http.Request {
- return contextSave(r, errorKey, err)
-}
diff --git a/vendor/github.com/gorilla/csrf/options.go b/vendor/github.com/gorilla/csrf/options.go
deleted file mode 100644
index b50ebd4..0000000
--- a/vendor/github.com/gorilla/csrf/options.go
+++ /dev/null
@@ -1,130 +0,0 @@
-package csrf
-
-import "net/http"
-
-// Option describes a functional option for configuring the CSRF handler.
-type Option func(*csrf)
-
-// MaxAge sets the maximum age (in seconds) of a CSRF token's underlying cookie.
-// Defaults to 12 hours.
-func MaxAge(age int) Option {
- return func(cs *csrf) {
- cs.opts.MaxAge = age
- }
-}
-
-// Domain sets the cookie domain. Defaults to the current domain of the request
-// only (recommended).
-//
-// This should be a hostname and not a URL. If set, the domain is treated as
-// being prefixed with a '.' - e.g. "example.com" becomes ".example.com" and
-// matches "www.example.com" and "secure.example.com".
-func Domain(domain string) Option {
- return func(cs *csrf) {
- cs.opts.Domain = domain
- }
-}
-
-// Path sets the cookie path. Defaults to the path the cookie was issued from
-// (recommended).
-//
-// This instructs clients to only respond with cookie for that path and its
-// subpaths - i.e. a cookie issued from "/register" would be included in requests
-// to "/register/step2" and "/register/submit".
-func Path(p string) Option {
- return func(cs *csrf) {
- cs.opts.Path = p
- }
-}
-
-// Secure sets the 'Secure' flag on the cookie. Defaults to true (recommended).
-// Set this to 'false' in your development environment otherwise the cookie won't
-// be sent over an insecure channel. Setting this via the presence of a 'DEV'
-// environmental variable is a good way of making sure this won't make it to a
-// production environment.
-func Secure(s bool) Option {
- return func(cs *csrf) {
- cs.opts.Secure = s
- }
-}
-
-// HttpOnly sets the 'HttpOnly' flag on the cookie. Defaults to true (recommended).
-func HttpOnly(h bool) Option {
- return func(cs *csrf) {
- // Note that the function and field names match the case of the
- // related http.Cookie field instead of the "correct" HTTPOnly name
- // that golint suggests.
- cs.opts.HttpOnly = h
- }
-}
-
-// ErrorHandler allows you to change the handler called when CSRF request
-// processing encounters an invalid token or request. A typical use would be to
-// provide a handler that returns a static HTML file with a HTTP 403 status. By
-// default a HTTP 403 status and a plain text CSRF failure reason are served.
-//
-// Note that a custom error handler can also access the csrf.FailureReason(r)
-// function to retrieve the CSRF validation reason from the request context.
-func ErrorHandler(h http.Handler) Option {
- return func(cs *csrf) {
- cs.opts.ErrorHandler = h
- }
-}
-
-// RequestHeader allows you to change the request header the CSRF middleware
-// inspects. The default is X-CSRF-Token.
-func RequestHeader(header string) Option {
- return func(cs *csrf) {
- cs.opts.RequestHeader = header
- }
-}
-
-// FieldName allows you to change the name attribute of the hidden <input> field
-// inspected by this package. The default is 'gorilla.csrf.Token'.
-func FieldName(name string) Option {
- return func(cs *csrf) {
- cs.opts.FieldName = name
- }
-}
-
-// CookieName changes the name of the CSRF cookie issued to clients.
-//
-// Note that cookie names should not contain whitespace, commas, semicolons,
-// backslashes or control characters as per RFC6265.
-func CookieName(name string) Option {
- return func(cs *csrf) {
- cs.opts.CookieName = name
- }
-}
-
-// setStore sets the store used by the CSRF middleware.
-// Note: this is private (for now) to allow for internal API changes.
-func setStore(s store) Option {
- return func(cs *csrf) {
- cs.st = s
- }
-}
-
-// parseOptions parses the supplied options functions and returns a configured
-// csrf handler.
-func parseOptions(h http.Handler, opts ...Option) *csrf {
- // Set the handler to call after processing.
- cs := &csrf{
- h: h,
- }
-
- // Default to true. See Secure & HttpOnly function comments for rationale.
- // Set here to allow package users to override the default.
- cs.opts.Secure = true
- cs.opts.HttpOnly = true
-
- // Range over each options function and apply it
- // to our csrf type to configure it. Options functions are
- // applied in order, with any conflicting options overriding
- // earlier calls.
- for _, option := range opts {
- option(cs)
- }
-
- return cs
-}
diff --git a/vendor/github.com/gorilla/csrf/store.go b/vendor/github.com/gorilla/csrf/store.go
deleted file mode 100644
index 39f47ad..0000000
--- a/vendor/github.com/gorilla/csrf/store.go
+++ /dev/null
@@ -1,82 +0,0 @@
-package csrf
-
-import (
- "net/http"
- "time"
-
- "github.com/gorilla/securecookie"
-)
-
-// store represents the session storage used for CSRF tokens.
-type store interface {
- // Get returns the real CSRF token from the store.
- Get(*http.Request) ([]byte, error)
- // Save stores the real CSRF token in the store and writes a
- // cookie to the http.ResponseWriter.
- // For non-cookie stores, the cookie should contain a unique (256 bit) ID
- // or key that references the token in the backend store.
- // csrf.GenerateRandomBytes is a helper function for generating secure IDs.
- Save(token []byte, w http.ResponseWriter) error
-}
-
-// cookieStore is a signed cookie session store for CSRF tokens.
-type cookieStore struct {
- name string
- maxAge int
- secure bool
- httpOnly bool
- path string
- domain string
- sc *securecookie.SecureCookie
-}
-
-// Get retrieves a CSRF token from the session cookie. It returns an empty token
-// if decoding fails (e.g. HMAC validation fails or the named cookie doesn't exist).
-func (cs *cookieStore) Get(r *http.Request) ([]byte, error) {
- // Retrieve the cookie from the request
- cookie, err := r.Cookie(cs.name)
- if err != nil {
- return nil, err
- }
-
- token := make([]byte, tokenLength)
- // Decode the HMAC authenticated cookie.
- err = cs.sc.Decode(cs.name, cookie.Value, &token)
- if err != nil {
- return nil, err
- }
-
- return token, nil
-}
-
-// Save stores the CSRF token in the session cookie.
-func (cs *cookieStore) Save(token []byte, w http.ResponseWriter) error {
- // Generate an encoded cookie value with the CSRF token.
- encoded, err := cs.sc.Encode(cs.name, token)
- if err != nil {
- return err
- }
-
- cookie := &http.Cookie{
- Name: cs.name,
- Value: encoded,
- MaxAge: cs.maxAge,
- HttpOnly: cs.httpOnly,
- Secure: cs.secure,
- Path: cs.path,
- Domain: cs.domain,
- }
-
- // Set the Expires field on the cookie based on the MaxAge
- // If MaxAge <= 0, we don't set the Expires attribute, making the cookie
- // session-only.
- if cs.maxAge > 0 {
- cookie.Expires = time.Now().Add(
- time.Duration(cs.maxAge) * time.Second)
- }
-
- // Write the authenticated cookie to the response.
- http.SetCookie(w, cookie)
-
- return nil
-}
diff --git a/vendor/github.com/gorilla/handlers/LICENSE b/vendor/github.com/gorilla/handlers/LICENSE
deleted file mode 100644
index 66ea3c8..0000000
--- a/vendor/github.com/gorilla/handlers/LICENSE
+++ /dev/null
@@ -1,22 +0,0 @@
-Copyright (c) 2013 The Gorilla Handlers Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/gorilla/handlers/README.md b/vendor/github.com/gorilla/handlers/README.md
deleted file mode 100644
index 4a6895d..0000000
--- a/vendor/github.com/gorilla/handlers/README.md
+++ /dev/null
@@ -1,55 +0,0 @@
-gorilla/handlers
-================
-[![GoDoc](https://godoc.org/github.com/gorilla/handlers?status.svg)](https://godoc.org/github.com/gorilla/handlers) [![Build Status](https://travis-ci.org/gorilla/handlers.svg?branch=master)](https://travis-ci.org/gorilla/handlers)
-[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/handlers/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/handlers?badge)
-
-
-Package handlers is a collection of handlers (aka "HTTP middleware") for use
-with Go's `net/http` package (or any framework supporting `http.Handler`), including:
-
-* [**LoggingHandler**](https://godoc.org/github.com/gorilla/handlers#LoggingHandler) for logging HTTP requests in the Apache [Common Log
- Format](http://httpd.apache.org/docs/2.2/logs.html#common).
-* [**CombinedLoggingHandler**](https://godoc.org/github.com/gorilla/handlers#CombinedLoggingHandler) for logging HTTP requests in the Apache [Combined Log
- Format](http://httpd.apache.org/docs/2.2/logs.html#combined) commonly used by
- both Apache and nginx.
-* [**CompressHandler**](https://godoc.org/github.com/gorilla/handlers#CompressHandler) for gzipping responses.
-* [**ContentTypeHandler**](https://godoc.org/github.com/gorilla/handlers#ContentTypeHandler) for validating requests against a list of accepted
- content types.
-* [**MethodHandler**](https://godoc.org/github.com/gorilla/handlers#MethodHandler) for matching HTTP methods against handlers in a
- `map[string]http.Handler`
-* [**ProxyHeaders**](https://godoc.org/github.com/gorilla/handlers#ProxyHeaders) for populating `r.RemoteAddr` and `r.URL.Scheme` based on the
- `X-Forwarded-For`, `X-Real-IP`, `X-Forwarded-Proto` and RFC7239 `Forwarded`
- headers when running a Go server behind a HTTP reverse proxy.
-* [**CanonicalHost**](https://godoc.org/github.com/gorilla/handlers#CanonicalHost) for re-directing to the preferred host when handling multiple
- domains (i.e. multiple CNAME aliases).
-* [**RecoveryHandler**](https://godoc.org/github.com/gorilla/handlers#RecoveryHandler) for recovering from unexpected panics.
-
-Other handlers are documented [on the Gorilla
-website](http://www.gorillatoolkit.org/pkg/handlers).
-
-## Example
-
-A simple example using `handlers.LoggingHandler` and `handlers.CompressHandler`:
-
-```go
-import (
- "net/http"
- "github.com/gorilla/handlers"
-)
-
-func main() {
- r := http.NewServeMux()
-
- // Only log requests to our admin dashboard to stdout
- r.Handle("/admin", handlers.LoggingHandler(os.Stdout, http.HandlerFunc(ShowAdminDashboard)))
- r.HandleFunc("/", ShowIndex)
-
- // Wrap our server with our gzip handler to gzip compress all responses.
- http.ListenAndServe(":8000", handlers.CompressHandler(r))
-}
-```
-
-## License
-
-BSD licensed. See the included LICENSE file for details.
-
diff --git a/vendor/github.com/gorilla/handlers/canonical.go b/vendor/github.com/gorilla/handlers/canonical.go
deleted file mode 100644
index 8437fef..0000000
--- a/vendor/github.com/gorilla/handlers/canonical.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package handlers
-
-import (
- "net/http"
- "net/url"
- "strings"
-)
-
-type canonical struct {
- h http.Handler
- domain string
- code int
-}
-
-// CanonicalHost is HTTP middleware that re-directs requests to the canonical
-// domain. It accepts a domain and a status code (e.g. 301 or 302) and
-// re-directs clients to this domain. The existing request path is maintained.
-//
-// Note: If the provided domain is considered invalid by url.Parse or otherwise
-// returns an empty scheme or host, clients are not re-directed.
-//
-// Example:
-//
-// r := mux.NewRouter()
-// canonical := handlers.CanonicalHost("http://www.gorillatoolkit.org", 302)
-// r.HandleFunc("/route", YourHandler)
-//
-// log.Fatal(http.ListenAndServe(":7000", canonical(r)))
-//
-func CanonicalHost(domain string, code int) func(h http.Handler) http.Handler {
- fn := func(h http.Handler) http.Handler {
- return canonical{h, domain, code}
- }
-
- return fn
-}
-
-func (c canonical) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- dest, err := url.Parse(c.domain)
- if err != nil {
- // Call the next handler if the provided domain fails to parse.
- c.h.ServeHTTP(w, r)
- return
- }
-
- if dest.Scheme == "" || dest.Host == "" {
- // Call the next handler if the scheme or host are empty.
- // Note that url.Parse won't fail on in this case.
- c.h.ServeHTTP(w, r)
- return
- }
-
- if !strings.EqualFold(cleanHost(r.Host), dest.Host) {
- // Re-build the destination URL
- dest := dest.Scheme + "://" + dest.Host + r.URL.Path
- if r.URL.RawQuery != "" {
- dest += "?" + r.URL.RawQuery
- }
- http.Redirect(w, r, dest, c.code)
- return
- }
-
- c.h.ServeHTTP(w, r)
-}
-
-// cleanHost cleans invalid Host headers by stripping anything after '/' or ' '.
-// This is backported from Go 1.5 (in response to issue #11206) and attempts to
-// mitigate malformed Host headers that do not match the format in RFC7230.
-func cleanHost(in string) string {
- if i := strings.IndexAny(in, " /"); i != -1 {
- return in[:i]
- }
- return in
-}
diff --git a/vendor/github.com/gorilla/handlers/compress.go b/vendor/github.com/gorilla/handlers/compress.go
deleted file mode 100644
index e8345d7..0000000
--- a/vendor/github.com/gorilla/handlers/compress.go
+++ /dev/null
@@ -1,148 +0,0 @@
-// Copyright 2013 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package handlers
-
-import (
- "compress/flate"
- "compress/gzip"
- "io"
- "net/http"
- "strings"
-)
-
-type compressResponseWriter struct {
- io.Writer
- http.ResponseWriter
- http.Hijacker
- http.Flusher
- http.CloseNotifier
-}
-
-func (w *compressResponseWriter) WriteHeader(c int) {
- w.ResponseWriter.Header().Del("Content-Length")
- w.ResponseWriter.WriteHeader(c)
-}
-
-func (w *compressResponseWriter) Header() http.Header {
- return w.ResponseWriter.Header()
-}
-
-func (w *compressResponseWriter) Write(b []byte) (int, error) {
- h := w.ResponseWriter.Header()
- if h.Get("Content-Type") == "" {
- h.Set("Content-Type", http.DetectContentType(b))
- }
- h.Del("Content-Length")
-
- return w.Writer.Write(b)
-}
-
-type flusher interface {
- Flush() error
-}
-
-func (w *compressResponseWriter) Flush() {
- // Flush compressed data if compressor supports it.
- if f, ok := w.Writer.(flusher); ok {
- f.Flush()
- }
- // Flush HTTP response.
- if w.Flusher != nil {
- w.Flusher.Flush()
- }
-}
-
-// CompressHandler gzip compresses HTTP responses for clients that support it
-// via the 'Accept-Encoding' header.
-//
-// Compressing TLS traffic may leak the page contents to an attacker if the
-// page contains user input: http://security.stackexchange.com/a/102015/12208
-func CompressHandler(h http.Handler) http.Handler {
- return CompressHandlerLevel(h, gzip.DefaultCompression)
-}
-
-// CompressHandlerLevel gzip compresses HTTP responses with specified compression level
-// for clients that support it via the 'Accept-Encoding' header.
-//
-// The compression level should be gzip.DefaultCompression, gzip.NoCompression,
-// or any integer value between gzip.BestSpeed and gzip.BestCompression inclusive.
-// gzip.DefaultCompression is used in case of invalid compression level.
-func CompressHandlerLevel(h http.Handler, level int) http.Handler {
- if level < gzip.DefaultCompression || level > gzip.BestCompression {
- level = gzip.DefaultCompression
- }
-
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- L:
- for _, enc := range strings.Split(r.Header.Get("Accept-Encoding"), ",") {
- switch strings.TrimSpace(enc) {
- case "gzip":
- w.Header().Set("Content-Encoding", "gzip")
- w.Header().Add("Vary", "Accept-Encoding")
-
- gw, _ := gzip.NewWriterLevel(w, level)
- defer gw.Close()
-
- h, hok := w.(http.Hijacker)
- if !hok { /* w is not Hijacker... oh well... */
- h = nil
- }
-
- f, fok := w.(http.Flusher)
- if !fok {
- f = nil
- }
-
- cn, cnok := w.(http.CloseNotifier)
- if !cnok {
- cn = nil
- }
-
- w = &compressResponseWriter{
- Writer: gw,
- ResponseWriter: w,
- Hijacker: h,
- Flusher: f,
- CloseNotifier: cn,
- }
-
- break L
- case "deflate":
- w.Header().Set("Content-Encoding", "deflate")
- w.Header().Add("Vary", "Accept-Encoding")
-
- fw, _ := flate.NewWriter(w, level)
- defer fw.Close()
-
- h, hok := w.(http.Hijacker)
- if !hok { /* w is not Hijacker... oh well... */
- h = nil
- }
-
- f, fok := w.(http.Flusher)
- if !fok {
- f = nil
- }
-
- cn, cnok := w.(http.CloseNotifier)
- if !cnok {
- cn = nil
- }
-
- w = &compressResponseWriter{
- Writer: fw,
- ResponseWriter: w,
- Hijacker: h,
- Flusher: f,
- CloseNotifier: cn,
- }
-
- break L
- }
- }
-
- h.ServeHTTP(w, r)
- })
-}
diff --git a/vendor/github.com/gorilla/handlers/cors.go b/vendor/github.com/gorilla/handlers/cors.go
deleted file mode 100644
index 1acf80d..0000000
--- a/vendor/github.com/gorilla/handlers/cors.go
+++ /dev/null
@@ -1,338 +0,0 @@
-package handlers
-
-import (
- "net/http"
- "strconv"
- "strings"
-)
-
-// CORSOption represents a functional option for configuring the CORS middleware.
-type CORSOption func(*cors) error
-
-type cors struct {
- h http.Handler
- allowedHeaders []string
- allowedMethods []string
- allowedOrigins []string
- allowedOriginValidator OriginValidator
- exposedHeaders []string
- maxAge int
- ignoreOptions bool
- allowCredentials bool
-}
-
-// OriginValidator takes an origin string and returns whether or not that origin is allowed.
-type OriginValidator func(string) bool
-
-var (
- defaultCorsMethods = []string{"GET", "HEAD", "POST"}
- defaultCorsHeaders = []string{"Accept", "Accept-Language", "Content-Language", "Origin"}
- // (WebKit/Safari v9 sends the Origin header by default in AJAX requests)
-)
-
-const (
- corsOptionMethod string = "OPTIONS"
- corsAllowOriginHeader string = "Access-Control-Allow-Origin"
- corsExposeHeadersHeader string = "Access-Control-Expose-Headers"
- corsMaxAgeHeader string = "Access-Control-Max-Age"
- corsAllowMethodsHeader string = "Access-Control-Allow-Methods"
- corsAllowHeadersHeader string = "Access-Control-Allow-Headers"
- corsAllowCredentialsHeader string = "Access-Control-Allow-Credentials"
- corsRequestMethodHeader string = "Access-Control-Request-Method"
- corsRequestHeadersHeader string = "Access-Control-Request-Headers"
- corsOriginHeader string = "Origin"
- corsVaryHeader string = "Vary"
- corsOriginMatchAll string = "*"
-)
-
-func (ch *cors) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- origin := r.Header.Get(corsOriginHeader)
- if !ch.isOriginAllowed(origin) {
- if r.Method != corsOptionMethod || ch.ignoreOptions {
- ch.h.ServeHTTP(w, r)
- }
-
- return
- }
-
- if r.Method == corsOptionMethod {
- if ch.ignoreOptions {
- ch.h.ServeHTTP(w, r)
- return
- }
-
- if _, ok := r.Header[corsRequestMethodHeader]; !ok {
- w.WriteHeader(http.StatusBadRequest)
- return
- }
-
- method := r.Header.Get(corsRequestMethodHeader)
- if !ch.isMatch(method, ch.allowedMethods) {
- w.WriteHeader(http.StatusMethodNotAllowed)
- return
- }
-
- requestHeaders := strings.Split(r.Header.Get(corsRequestHeadersHeader), ",")
- allowedHeaders := []string{}
- for _, v := range requestHeaders {
- canonicalHeader := http.CanonicalHeaderKey(strings.TrimSpace(v))
- if canonicalHeader == "" || ch.isMatch(canonicalHeader, defaultCorsHeaders) {
- continue
- }
-
- if !ch.isMatch(canonicalHeader, ch.allowedHeaders) {
- w.WriteHeader(http.StatusForbidden)
- return
- }
-
- allowedHeaders = append(allowedHeaders, canonicalHeader)
- }
-
- if len(allowedHeaders) > 0 {
- w.Header().Set(corsAllowHeadersHeader, strings.Join(allowedHeaders, ","))
- }
-
- if ch.maxAge > 0 {
- w.Header().Set(corsMaxAgeHeader, strconv.Itoa(ch.maxAge))
- }
-
- if !ch.isMatch(method, defaultCorsMethods) {
- w.Header().Set(corsAllowMethodsHeader, method)
- }
- } else {
- if len(ch.exposedHeaders) > 0 {
- w.Header().Set(corsExposeHeadersHeader, strings.Join(ch.exposedHeaders, ","))
- }
- }
-
- if ch.allowCredentials {
- w.Header().Set(corsAllowCredentialsHeader, "true")
- }
-
- if len(ch.allowedOrigins) > 1 {
- w.Header().Set(corsVaryHeader, corsOriginHeader)
- }
-
- returnOrigin := origin
- if ch.allowedOriginValidator == nil && len(ch.allowedOrigins) == 0 {
- returnOrigin = "*"
- } else {
- for _, o := range ch.allowedOrigins {
- // A configuration of * is different than explicitly setting an allowed
- // origin. Returning arbitrary origin headers in an access control allow
- // origin header is unsafe and is not required by any use case.
- if o == corsOriginMatchAll {
- returnOrigin = "*"
- break
- }
- }
- }
- w.Header().Set(corsAllowOriginHeader, returnOrigin)
-
- if r.Method == corsOptionMethod {
- return
- }
- ch.h.ServeHTTP(w, r)
-}
-
-// CORS provides Cross-Origin Resource Sharing middleware.
-// Example:
-//
-// import (
-// "net/http"
-//
-// "github.com/gorilla/handlers"
-// "github.com/gorilla/mux"
-// )
-//
-// func main() {
-// r := mux.NewRouter()
-// r.HandleFunc("/users", UserEndpoint)
-// r.HandleFunc("/projects", ProjectEndpoint)
-//
-// // Apply the CORS middleware to our top-level router, with the defaults.
-// http.ListenAndServe(":8000", handlers.CORS()(r))
-// }
-//
-func CORS(opts ...CORSOption) func(http.Handler) http.Handler {
- return func(h http.Handler) http.Handler {
- ch := parseCORSOptions(opts...)
- ch.h = h
- return ch
- }
-}
-
-func parseCORSOptions(opts ...CORSOption) *cors {
- ch := &cors{
- allowedMethods: defaultCorsMethods,
- allowedHeaders: defaultCorsHeaders,
- allowedOrigins: []string{},
- }
-
- for _, option := range opts {
- option(ch)
- }
-
- return ch
-}
-
-//
-// Functional options for configuring CORS.
-//
-
-// AllowedHeaders adds the provided headers to the list of allowed headers in a
-// CORS request.
-// This is an append operation so the headers Accept, Accept-Language,
-// and Content-Language are always allowed.
-// Content-Type must be explicitly declared if accepting Content-Types other than
-// application/x-www-form-urlencoded, multipart/form-data, or text/plain.
-func AllowedHeaders(headers []string) CORSOption {
- return func(ch *cors) error {
- for _, v := range headers {
- normalizedHeader := http.CanonicalHeaderKey(strings.TrimSpace(v))
- if normalizedHeader == "" {
- continue
- }
-
- if !ch.isMatch(normalizedHeader, ch.allowedHeaders) {
- ch.allowedHeaders = append(ch.allowedHeaders, normalizedHeader)
- }
- }
-
- return nil
- }
-}
-
-// AllowedMethods can be used to explicitly allow methods in the
-// Access-Control-Allow-Methods header.
-// This is a replacement operation so you must also
-// pass GET, HEAD, and POST if you wish to support those methods.
-func AllowedMethods(methods []string) CORSOption {
- return func(ch *cors) error {
- ch.allowedMethods = []string{}
- for _, v := range methods {
- normalizedMethod := strings.ToUpper(strings.TrimSpace(v))
- if normalizedMethod == "" {
- continue
- }
-
- if !ch.isMatch(normalizedMethod, ch.allowedMethods) {
- ch.allowedMethods = append(ch.allowedMethods, normalizedMethod)
- }
- }
-
- return nil
- }
-}
-
-// AllowedOrigins sets the allowed origins for CORS requests, as used in the
-// 'Allow-Access-Control-Origin' HTTP header.
-// Note: Passing in a []string{"*"} will allow any domain.
-func AllowedOrigins(origins []string) CORSOption {
- return func(ch *cors) error {
- for _, v := range origins {
- if v == corsOriginMatchAll {
- ch.allowedOrigins = []string{corsOriginMatchAll}
- return nil
- }
- }
-
- ch.allowedOrigins = origins
- return nil
- }
-}
-
-// AllowedOriginValidator sets a function for evaluating allowed origins in CORS requests, represented by the
-// 'Allow-Access-Control-Origin' HTTP header.
-func AllowedOriginValidator(fn OriginValidator) CORSOption {
- return func(ch *cors) error {
- ch.allowedOriginValidator = fn
- return nil
- }
-}
-
-// ExposeHeaders can be used to specify headers that are available
-// and will not be stripped out by the user-agent.
-func ExposedHeaders(headers []string) CORSOption {
- return func(ch *cors) error {
- ch.exposedHeaders = []string{}
- for _, v := range headers {
- normalizedHeader := http.CanonicalHeaderKey(strings.TrimSpace(v))
- if normalizedHeader == "" {
- continue
- }
-
- if !ch.isMatch(normalizedHeader, ch.exposedHeaders) {
- ch.exposedHeaders = append(ch.exposedHeaders, normalizedHeader)
- }
- }
-
- return nil
- }
-}
-
-// MaxAge determines the maximum age (in seconds) between preflight requests. A
-// maximum of 10 minutes is allowed. An age above this value will default to 10
-// minutes.
-func MaxAge(age int) CORSOption {
- return func(ch *cors) error {
- // Maximum of 10 minutes.
- if age > 600 {
- age = 600
- }
-
- ch.maxAge = age
- return nil
- }
-}
-
-// IgnoreOptions causes the CORS middleware to ignore OPTIONS requests, instead
-// passing them through to the next handler. This is useful when your application
-// or framework has a pre-existing mechanism for responding to OPTIONS requests.
-func IgnoreOptions() CORSOption {
- return func(ch *cors) error {
- ch.ignoreOptions = true
- return nil
- }
-}
-
-// AllowCredentials can be used to specify that the user agent may pass
-// authentication details along with the request.
-func AllowCredentials() CORSOption {
- return func(ch *cors) error {
- ch.allowCredentials = true
- return nil
- }
-}
-
-func (ch *cors) isOriginAllowed(origin string) bool {
- if origin == "" {
- return false
- }
-
- if ch.allowedOriginValidator != nil {
- return ch.allowedOriginValidator(origin)
- }
-
- if len(ch.allowedOrigins) == 0 {
- return true
- }
-
- for _, allowedOrigin := range ch.allowedOrigins {
- if allowedOrigin == origin || allowedOrigin == corsOriginMatchAll {
- return true
- }
- }
-
- return false
-}
-
-func (ch *cors) isMatch(needle string, haystack []string) bool {
- for _, v := range haystack {
- if v == needle {
- return true
- }
- }
-
- return false
-}
diff --git a/vendor/github.com/gorilla/handlers/doc.go b/vendor/github.com/gorilla/handlers/doc.go
deleted file mode 100644
index 944e5a8..0000000
--- a/vendor/github.com/gorilla/handlers/doc.go
+++ /dev/null
@@ -1,9 +0,0 @@
-/*
-Package handlers is a collection of handlers (aka "HTTP middleware") for use
-with Go's net/http package (or any framework supporting http.Handler).
-
-The package includes handlers for logging in standardised formats, compressing
-HTTP responses, validating content types and other useful tools for manipulating
-requests and responses.
-*/
-package handlers
diff --git a/vendor/github.com/gorilla/handlers/handlers.go b/vendor/github.com/gorilla/handlers/handlers.go
deleted file mode 100644
index d03f2bf..0000000
--- a/vendor/github.com/gorilla/handlers/handlers.go
+++ /dev/null
@@ -1,174 +0,0 @@
-// Copyright 2013 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package handlers
-
-import (
- "bufio"
- "fmt"
- "net"
- "net/http"
- "sort"
- "strings"
-)
-
-// MethodHandler is an http.Handler that dispatches to a handler whose key in the
-// MethodHandler's map matches the name of the HTTP request's method, eg: GET
-//
-// If the request's method is OPTIONS and OPTIONS is not a key in the map then
-// the handler responds with a status of 200 and sets the Allow header to a
-// comma-separated list of available methods.
-//
-// If the request's method doesn't match any of its keys the handler responds
-// with a status of HTTP 405 "Method Not Allowed" and sets the Allow header to a
-// comma-separated list of available methods.
-type MethodHandler map[string]http.Handler
-
-func (h MethodHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
- if handler, ok := h[req.Method]; ok {
- handler.ServeHTTP(w, req)
- } else {
- allow := []string{}
- for k := range h {
- allow = append(allow, k)
- }
- sort.Strings(allow)
- w.Header().Set("Allow", strings.Join(allow, ", "))
- if req.Method == "OPTIONS" {
- w.WriteHeader(http.StatusOK)
- } else {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- }
- }
-}
-
-// responseLogger is wrapper of http.ResponseWriter that keeps track of its HTTP
-// status code and body size
-type responseLogger struct {
- w http.ResponseWriter
- status int
- size int
-}
-
-func (l *responseLogger) Header() http.Header {
- return l.w.Header()
-}
-
-func (l *responseLogger) Write(b []byte) (int, error) {
- size, err := l.w.Write(b)
- l.size += size
- return size, err
-}
-
-func (l *responseLogger) WriteHeader(s int) {
- l.w.WriteHeader(s)
- l.status = s
-}
-
-func (l *responseLogger) Status() int {
- return l.status
-}
-
-func (l *responseLogger) Size() int {
- return l.size
-}
-
-func (l *responseLogger) Flush() {
- f, ok := l.w.(http.Flusher)
- if ok {
- f.Flush()
- }
-}
-
-type hijackLogger struct {
- responseLogger
-}
-
-func (l *hijackLogger) Hijack() (net.Conn, *bufio.ReadWriter, error) {
- h := l.responseLogger.w.(http.Hijacker)
- conn, rw, err := h.Hijack()
- if err == nil && l.responseLogger.status == 0 {
- // The status will be StatusSwitchingProtocols if there was no error and
- // WriteHeader has not been called yet
- l.responseLogger.status = http.StatusSwitchingProtocols
- }
- return conn, rw, err
-}
-
-type closeNotifyWriter struct {
- loggingResponseWriter
- http.CloseNotifier
-}
-
-type hijackCloseNotifier struct {
- loggingResponseWriter
- http.Hijacker
- http.CloseNotifier
-}
-
-// isContentType validates the Content-Type header matches the supplied
-// contentType. That is, its type and subtype match.
-func isContentType(h http.Header, contentType string) bool {
- ct := h.Get("Content-Type")
- if i := strings.IndexRune(ct, ';'); i != -1 {
- ct = ct[0:i]
- }
- return ct == contentType
-}
-
-// ContentTypeHandler wraps and returns a http.Handler, validating the request
-// content type is compatible with the contentTypes list. It writes a HTTP 415
-// error if that fails.
-//
-// Only PUT, POST, and PATCH requests are considered.
-func ContentTypeHandler(h http.Handler, contentTypes ...string) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if !(r.Method == "PUT" || r.Method == "POST" || r.Method == "PATCH") {
- h.ServeHTTP(w, r)
- return
- }
-
- for _, ct := range contentTypes {
- if isContentType(r.Header, ct) {
- h.ServeHTTP(w, r)
- return
- }
- }
- http.Error(w, fmt.Sprintf("Unsupported content type %q; expected one of %q", r.Header.Get("Content-Type"), contentTypes), http.StatusUnsupportedMediaType)
- })
-}
-
-const (
- // HTTPMethodOverrideHeader is a commonly used
- // http header to override a request method.
- HTTPMethodOverrideHeader = "X-HTTP-Method-Override"
- // HTTPMethodOverrideFormKey is a commonly used
- // HTML form key to override a request method.
- HTTPMethodOverrideFormKey = "_method"
-)
-
-// HTTPMethodOverrideHandler wraps and returns a http.Handler which checks for
-// the X-HTTP-Method-Override header or the _method form key, and overrides (if
-// valid) request.Method with its value.
-//
-// This is especially useful for HTTP clients that don't support many http verbs.
-// It isn't secure to override e.g a GET to a POST, so only POST requests are
-// considered. Likewise, the override method can only be a "write" method: PUT,
-// PATCH or DELETE.
-//
-// Form method takes precedence over header method.
-func HTTPMethodOverrideHandler(h http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.Method == "POST" {
- om := r.FormValue(HTTPMethodOverrideFormKey)
- if om == "" {
- om = r.Header.Get(HTTPMethodOverrideHeader)
- }
- if om == "PUT" || om == "PATCH" || om == "DELETE" {
- r.Method = om
- }
- }
- h.ServeHTTP(w, r)
- })
-}
diff --git a/vendor/github.com/gorilla/handlers/handlers_go18.go b/vendor/github.com/gorilla/handlers/handlers_go18.go
deleted file mode 100644
index 35eb8d4..0000000
--- a/vendor/github.com/gorilla/handlers/handlers_go18.go
+++ /dev/null
@@ -1,21 +0,0 @@
-// +build go1.8
-
-package handlers
-
-import (
- "fmt"
- "net/http"
-)
-
-type loggingResponseWriter interface {
- commonLoggingResponseWriter
- http.Pusher
-}
-
-func (l *responseLogger) Push(target string, opts *http.PushOptions) error {
- p, ok := l.w.(http.Pusher)
- if !ok {
- return fmt.Errorf("responseLogger does not implement http.Pusher")
- }
- return p.Push(target, opts)
-}
diff --git a/vendor/github.com/gorilla/handlers/handlers_pre18.go b/vendor/github.com/gorilla/handlers/handlers_pre18.go
deleted file mode 100644
index 197836a..0000000
--- a/vendor/github.com/gorilla/handlers/handlers_pre18.go
+++ /dev/null
@@ -1,7 +0,0 @@
-// +build !go1.8
-
-package handlers
-
-type loggingResponseWriter interface {
- commonLoggingResponseWriter
-}
diff --git a/vendor/github.com/gorilla/handlers/logging.go b/vendor/github.com/gorilla/handlers/logging.go
deleted file mode 100644
index cbd182f..0000000
--- a/vendor/github.com/gorilla/handlers/logging.go
+++ /dev/null
@@ -1,252 +0,0 @@
-// Copyright 2013 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package handlers
-
-import (
- "io"
- "net"
- "net/http"
- "net/url"
- "strconv"
- "time"
- "unicode/utf8"
-)
-
-// Logging
-
-// FormatterParams is the structure any formatter will be handed when time to log comes
-type LogFormatterParams struct {
- Request *http.Request
- URL url.URL
- TimeStamp time.Time
- StatusCode int
- Size int
-}
-
-// LogFormatter gives the signature of the formatter function passed to CustomLoggingHandler
-type LogFormatter func(writer io.Writer, params LogFormatterParams)
-
-// loggingHandler is the http.Handler implementation for LoggingHandlerTo and its
-// friends
-
-type loggingHandler struct {
- writer io.Writer
- handler http.Handler
- formatter LogFormatter
-}
-
-func (h loggingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
- t := time.Now()
- logger := makeLogger(w)
- url := *req.URL
-
- h.handler.ServeHTTP(logger, req)
-
- params := LogFormatterParams{
- Request: req,
- URL: url,
- TimeStamp: t,
- StatusCode: logger.Status(),
- Size: logger.Size(),
- }
-
- h.formatter(h.writer, params)
-}
-
-func makeLogger(w http.ResponseWriter) loggingResponseWriter {
- var logger loggingResponseWriter = &responseLogger{w: w, status: http.StatusOK}
- if _, ok := w.(http.Hijacker); ok {
- logger = &hijackLogger{responseLogger{w: w, status: http.StatusOK}}
- }
- h, ok1 := logger.(http.Hijacker)
- c, ok2 := w.(http.CloseNotifier)
- if ok1 && ok2 {
- return hijackCloseNotifier{logger, h, c}
- }
- if ok2 {
- return &closeNotifyWriter{logger, c}
- }
- return logger
-}
-
-type commonLoggingResponseWriter interface {
- http.ResponseWriter
- http.Flusher
- Status() int
- Size() int
-}
-
-const lowerhex = "0123456789abcdef"
-
-func appendQuoted(buf []byte, s string) []byte {
- var runeTmp [utf8.UTFMax]byte
- for width := 0; len(s) > 0; s = s[width:] {
- r := rune(s[0])
- width = 1
- if r >= utf8.RuneSelf {
- r, width = utf8.DecodeRuneInString(s)
- }
- if width == 1 && r == utf8.RuneError {
- buf = append(buf, `\x`...)
- buf = append(buf, lowerhex[s[0]>>4])
- buf = append(buf, lowerhex[s[0]&0xF])
- continue
- }
- if r == rune('"') || r == '\\' { // always backslashed
- buf = append(buf, '\\')
- buf = append(buf, byte(r))
- continue
- }
- if strconv.IsPrint(r) {
- n := utf8.EncodeRune(runeTmp[:], r)
- buf = append(buf, runeTmp[:n]...)
- continue
- }
- switch r {
- case '\a':
- buf = append(buf, `\a`...)
- case '\b':
- buf = append(buf, `\b`...)
- case '\f':
- buf = append(buf, `\f`...)
- case '\n':
- buf = append(buf, `\n`...)
- case '\r':
- buf = append(buf, `\r`...)
- case '\t':
- buf = append(buf, `\t`...)
- case '\v':
- buf = append(buf, `\v`...)
- default:
- switch {
- case r < ' ':
- buf = append(buf, `\x`...)
- buf = append(buf, lowerhex[s[0]>>4])
- buf = append(buf, lowerhex[s[0]&0xF])
- case r > utf8.MaxRune:
- r = 0xFFFD
- fallthrough
- case r < 0x10000:
- buf = append(buf, `\u`...)
- for s := 12; s >= 0; s -= 4 {
- buf = append(buf, lowerhex[r>>uint(s)&0xF])
- }
- default:
- buf = append(buf, `\U`...)
- for s := 28; s >= 0; s -= 4 {
- buf = append(buf, lowerhex[r>>uint(s)&0xF])
- }
- }
- }
- }
- return buf
-
-}
-
-// buildCommonLogLine builds a log entry for req in Apache Common Log Format.
-// ts is the timestamp with which the entry should be logged.
-// status and size are used to provide the response HTTP status and size.
-func buildCommonLogLine(req *http.Request, url url.URL, ts time.Time, status int, size int) []byte {
- username := "-"
- if url.User != nil {
- if name := url.User.Username(); name != "" {
- username = name
- }
- }
-
- host, _, err := net.SplitHostPort(req.RemoteAddr)
-
- if err != nil {
- host = req.RemoteAddr
- }
-
- uri := req.RequestURI
-
- // Requests using the CONNECT method over HTTP/2.0 must use
- // the authority field (aka r.Host) to identify the target.
- // Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT
- if req.ProtoMajor == 2 && req.Method == "CONNECT" {
- uri = req.Host
- }
- if uri == "" {
- uri = url.RequestURI()
- }
-
- buf := make([]byte, 0, 3*(len(host)+len(username)+len(req.Method)+len(uri)+len(req.Proto)+50)/2)
- buf = append(buf, host...)
- buf = append(buf, " - "...)
- buf = append(buf, username...)
- buf = append(buf, " ["...)
- buf = append(buf, ts.Format("02/Jan/2006:15:04:05 -0700")...)
- buf = append(buf, `] "`...)
- buf = append(buf, req.Method...)
- buf = append(buf, " "...)
- buf = appendQuoted(buf, uri)
- buf = append(buf, " "...)
- buf = append(buf, req.Proto...)
- buf = append(buf, `" `...)
- buf = append(buf, strconv.Itoa(status)...)
- buf = append(buf, " "...)
- buf = append(buf, strconv.Itoa(size)...)
- return buf
-}
-
-// writeLog writes a log entry for req to w in Apache Common Log Format.
-// ts is the timestamp with which the entry should be logged.
-// status and size are used to provide the response HTTP status and size.
-func writeLog(writer io.Writer, params LogFormatterParams) {
- buf := buildCommonLogLine(params.Request, params.URL, params.TimeStamp, params.StatusCode, params.Size)
- buf = append(buf, '\n')
- writer.Write(buf)
-}
-
-// writeCombinedLog writes a log entry for req to w in Apache Combined Log Format.
-// ts is the timestamp with which the entry should be logged.
-// status and size are used to provide the response HTTP status and size.
-func writeCombinedLog(writer io.Writer, params LogFormatterParams) {
- buf := buildCommonLogLine(params.Request, params.URL, params.TimeStamp, params.StatusCode, params.Size)
- buf = append(buf, ` "`...)
- buf = appendQuoted(buf, params.Request.Referer())
- buf = append(buf, `" "`...)
- buf = appendQuoted(buf, params.Request.UserAgent())
- buf = append(buf, '"', '\n')
- writer.Write(buf)
-}
-
-// CombinedLoggingHandler return a http.Handler that wraps h and logs requests to out in
-// Apache Combined Log Format.
-//
-// See http://httpd.apache.org/docs/2.2/logs.html#combined for a description of this format.
-//
-// LoggingHandler always sets the ident field of the log to -
-func CombinedLoggingHandler(out io.Writer, h http.Handler) http.Handler {
- return loggingHandler{out, h, writeCombinedLog}
-}
-
-// LoggingHandler return a http.Handler that wraps h and logs requests to out in
-// Apache Common Log Format (CLF).
-//
-// See http://httpd.apache.org/docs/2.2/logs.html#common for a description of this format.
-//
-// LoggingHandler always sets the ident field of the log to -
-//
-// Example:
-//
-// r := mux.NewRouter()
-// r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
-// w.Write([]byte("This is a catch-all route"))
-// })
-// loggedRouter := handlers.LoggingHandler(os.Stdout, r)
-// http.ListenAndServe(":1123", loggedRouter)
-//
-func LoggingHandler(out io.Writer, h http.Handler) http.Handler {
- return loggingHandler{out, h, writeLog}
-}
-
-// CustomLoggingHandler provides a way to supply a custom log formatter
-// while taking advantage of the mechanisms in this package
-func CustomLoggingHandler(out io.Writer, h http.Handler, f LogFormatter) http.Handler {
- return loggingHandler{out, h, f}
-}
diff --git a/vendor/github.com/gorilla/handlers/proxy_headers.go b/vendor/github.com/gorilla/handlers/proxy_headers.go
deleted file mode 100644
index 0be750f..0000000
--- a/vendor/github.com/gorilla/handlers/proxy_headers.go
+++ /dev/null
@@ -1,120 +0,0 @@
-package handlers
-
-import (
- "net/http"
- "regexp"
- "strings"
-)
-
-var (
- // De-facto standard header keys.
- xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
- xForwardedHost = http.CanonicalHeaderKey("X-Forwarded-Host")
- xForwardedProto = http.CanonicalHeaderKey("X-Forwarded-Proto")
- xForwardedScheme = http.CanonicalHeaderKey("X-Forwarded-Scheme")
- xRealIP = http.CanonicalHeaderKey("X-Real-IP")
-)
-
-var (
- // RFC7239 defines a new "Forwarded: " header designed to replace the
- // existing use of X-Forwarded-* headers.
- // e.g. Forwarded: for=192.0.2.60;proto=https;by=203.0.113.43
- forwarded = http.CanonicalHeaderKey("Forwarded")
- // Allows for a sub-match of the first value after 'for=' to the next
- // comma, semi-colon or space. The match is case-insensitive.
- forRegex = regexp.MustCompile(`(?i)(?:for=)([^(;|,| )]+)`)
- // Allows for a sub-match for the first instance of scheme (http|https)
- // prefixed by 'proto='. The match is case-insensitive.
- protoRegex = regexp.MustCompile(`(?i)(?:proto=)(https|http)`)
-)
-
-// ProxyHeaders inspects common reverse proxy headers and sets the corresponding
-// fields in the HTTP request struct. These are X-Forwarded-For and X-Real-IP
-// for the remote (client) IP address, X-Forwarded-Proto or X-Forwarded-Scheme
-// for the scheme (http|https) and the RFC7239 Forwarded header, which may
-// include both client IPs and schemes.
-//
-// NOTE: This middleware should only be used when behind a reverse
-// proxy like nginx, HAProxy or Apache. Reverse proxies that don't (or are
-// configured not to) strip these headers from client requests, or where these
-// headers are accepted "as is" from a remote client (e.g. when Go is not behind
-// a proxy), can manifest as a vulnerability if your application uses these
-// headers for validating the 'trustworthiness' of a request.
-func ProxyHeaders(h http.Handler) http.Handler {
- fn := func(w http.ResponseWriter, r *http.Request) {
- // Set the remote IP with the value passed from the proxy.
- if fwd := getIP(r); fwd != "" {
- r.RemoteAddr = fwd
- }
-
- // Set the scheme (proto) with the value passed from the proxy.
- if scheme := getScheme(r); scheme != "" {
- r.URL.Scheme = scheme
- }
- // Set the host with the value passed by the proxy
- if r.Header.Get(xForwardedHost) != "" {
- r.Host = r.Header.Get(xForwardedHost)
- }
- // Call the next handler in the chain.
- h.ServeHTTP(w, r)
- }
-
- return http.HandlerFunc(fn)
-}
-
-// getIP retrieves the IP from the X-Forwarded-For, X-Real-IP and RFC7239
-// Forwarded headers (in that order).
-func getIP(r *http.Request) string {
- var addr string
-
- if fwd := r.Header.Get(xForwardedFor); fwd != "" {
- // Only grab the first (client) address. Note that '192.168.0.1,
- // 10.1.1.1' is a valid key for X-Forwarded-For where addresses after
- // the first may represent forwarding proxies earlier in the chain.
- s := strings.Index(fwd, ", ")
- if s == -1 {
- s = len(fwd)
- }
- addr = fwd[:s]
- } else if fwd := r.Header.Get(xRealIP); fwd != "" {
- // X-Real-IP should only contain one IP address (the client making the
- // request).
- addr = fwd
- } else if fwd := r.Header.Get(forwarded); fwd != "" {
- // match should contain at least two elements if the protocol was
- // specified in the Forwarded header. The first element will always be
- // the 'for=' capture, which we ignore. In the case of multiple IP
- // addresses (for=8.8.8.8, 8.8.4.4,172.16.1.20 is valid) we only
- // extract the first, which should be the client IP.
- if match := forRegex.FindStringSubmatch(fwd); len(match) > 1 {
- // IPv6 addresses in Forwarded headers are quoted-strings. We strip
- // these quotes.
- addr = strings.Trim(match[1], `"`)
- }
- }
-
- return addr
-}
-
-// getScheme retrieves the scheme from the X-Forwarded-Proto and RFC7239
-// Forwarded headers (in that order).
-func getScheme(r *http.Request) string {
- var scheme string
-
- // Retrieve the scheme from X-Forwarded-Proto.
- if proto := r.Header.Get(xForwardedProto); proto != "" {
- scheme = strings.ToLower(proto)
- } else if proto = r.Header.Get(xForwardedScheme); proto != "" {
- scheme = strings.ToLower(proto)
- } else if proto = r.Header.Get(forwarded); proto != "" {
- // match should contain at least two elements if the protocol was
- // specified in the Forwarded header. The first element will always be
- // the 'proto=' capture, which we ignore. In the case of multiple proto
- // parameters (invalid) we only extract the first.
- if match := protoRegex.FindStringSubmatch(proto); len(match) > 1 {
- scheme = strings.ToLower(match[1])
- }
- }
-
- return scheme
-}
diff --git a/vendor/github.com/gorilla/handlers/recovery.go b/vendor/github.com/gorilla/handlers/recovery.go
deleted file mode 100644
index b1be9dc..0000000
--- a/vendor/github.com/gorilla/handlers/recovery.go
+++ /dev/null
@@ -1,91 +0,0 @@
-package handlers
-
-import (
- "log"
- "net/http"
- "runtime/debug"
-)
-
-// RecoveryHandlerLogger is an interface used by the recovering handler to print logs.
-type RecoveryHandlerLogger interface {
- Println(...interface{})
-}
-
-type recoveryHandler struct {
- handler http.Handler
- logger RecoveryHandlerLogger
- printStack bool
-}
-
-// RecoveryOption provides a functional approach to define
-// configuration for a handler; such as setting the logging
-// whether or not to print strack traces on panic.
-type RecoveryOption func(http.Handler)
-
-func parseRecoveryOptions(h http.Handler, opts ...RecoveryOption) http.Handler {
- for _, option := range opts {
- option(h)
- }
-
- return h
-}
-
-// RecoveryHandler is HTTP middleware that recovers from a panic,
-// logs the panic, writes http.StatusInternalServerError, and
-// continues to the next handler.
-//
-// Example:
-//
-// r := mux.NewRouter()
-// r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
-// panic("Unexpected error!")
-// })
-//
-// http.ListenAndServe(":1123", handlers.RecoveryHandler()(r))
-func RecoveryHandler(opts ...RecoveryOption) func(h http.Handler) http.Handler {
- return func(h http.Handler) http.Handler {
- r := &recoveryHandler{handler: h}
- return parseRecoveryOptions(r, opts...)
- }
-}
-
-// RecoveryLogger is a functional option to override
-// the default logger
-func RecoveryLogger(logger RecoveryHandlerLogger) RecoveryOption {
- return func(h http.Handler) {
- r := h.(*recoveryHandler)
- r.logger = logger
- }
-}
-
-// PrintRecoveryStack is a functional option to enable
-// or disable printing stack traces on panic.
-func PrintRecoveryStack(print bool) RecoveryOption {
- return func(h http.Handler) {
- r := h.(*recoveryHandler)
- r.printStack = print
- }
-}
-
-func (h recoveryHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
- defer func() {
- if err := recover(); err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- h.log(err)
- }
- }()
-
- h.handler.ServeHTTP(w, req)
-}
-
-func (h recoveryHandler) log(v ...interface{}) {
- if h.logger != nil {
- h.logger.Println(v...)
- } else {
- log.Println(v...)
- }
-
- if h.printStack {
- debug.PrintStack()
- }
-}
diff --git a/vendor/github.com/gorilla/mux/AUTHORS b/vendor/github.com/gorilla/mux/AUTHORS
deleted file mode 100644
index b722392..0000000
--- a/vendor/github.com/gorilla/mux/AUTHORS
+++ /dev/null
@@ -1,8 +0,0 @@
-# This is the official list of gorilla/mux authors for copyright purposes.
-#
-# Please keep the list sorted.
-
-Google LLC (https://opensource.google.com/)
-Kamil Kisielk <kamil@kamilkisiel.net>
-Matt Silverlock <matt@eatsleeprepeat.net>
-Rodrigo Moraes (https://github.com/moraes)
diff --git a/vendor/github.com/gorilla/mux/ISSUE_TEMPLATE.md b/vendor/github.com/gorilla/mux/ISSUE_TEMPLATE.md
deleted file mode 100644
index 232be82..0000000
--- a/vendor/github.com/gorilla/mux/ISSUE_TEMPLATE.md
+++ /dev/null
@@ -1,11 +0,0 @@
-**What version of Go are you running?** (Paste the output of `go version`)
-
-
-**What version of gorilla/mux are you at?** (Paste the output of `git rev-parse HEAD` inside `$GOPATH/src/github.com/gorilla/mux`)
-
-
-**Describe your problem** (and what you have tried so far)
-
-
-**Paste a minimal, runnable, reproduction of your issue below** (use backticks to format it)
-
diff --git a/vendor/github.com/gorilla/mux/LICENSE b/vendor/github.com/gorilla/mux/LICENSE
deleted file mode 100644
index 6903df6..0000000
--- a/vendor/github.com/gorilla/mux/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2012-2018 The Gorilla Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/gorilla/mux/README.md b/vendor/github.com/gorilla/mux/README.md
deleted file mode 100644
index e424397..0000000
--- a/vendor/github.com/gorilla/mux/README.md
+++ /dev/null
@@ -1,649 +0,0 @@
-# gorilla/mux
-
-[![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux)
-[![Build Status](https://travis-ci.org/gorilla/mux.svg?branch=master)](https://travis-ci.org/gorilla/mux)
-[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/mux/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/mux?badge)
-
-![Gorilla Logo](http://www.gorillatoolkit.org/static/images/gorilla-icon-64.png)
-
-http://www.gorillatoolkit.org/pkg/mux
-
-Package `gorilla/mux` implements a request router and dispatcher for matching incoming requests to
-their respective handler.
-
-The name mux stands for "HTTP request multiplexer". Like the standard `http.ServeMux`, `mux.Router` matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are:
-
-* It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`.
-* Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers.
-* URL hosts, paths and query values can have variables with an optional regular expression.
-* Registered URLs can be built, or "reversed", which helps maintaining references to resources.
-* Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching.
-
----
-
-* [Install](#install)
-* [Examples](#examples)
-* [Matching Routes](#matching-routes)
-* [Static Files](#static-files)
-* [Registered URLs](#registered-urls)
-* [Walking Routes](#walking-routes)
-* [Graceful Shutdown](#graceful-shutdown)
-* [Middleware](#middleware)
-* [Testing Handlers](#testing-handlers)
-* [Full Example](#full-example)
-
----
-
-## Install
-
-With a [correctly configured](https://golang.org/doc/install#testing) Go toolchain:
-
-```sh
-go get -u github.com/gorilla/mux
-```
-
-## Examples
-
-Let's start registering a couple of URL paths and handlers:
-
-```go
-func main() {
- r := mux.NewRouter()
- r.HandleFunc("/", HomeHandler)
- r.HandleFunc("/products", ProductsHandler)
- r.HandleFunc("/articles", ArticlesHandler)
- http.Handle("/", r)
-}
-```
-
-Here we register three routes mapping URL paths to handlers. This is equivalent to how `http.HandleFunc()` works: if an incoming request URL matches one of the paths, the corresponding handler is called passing (`http.ResponseWriter`, `*http.Request`) as parameters.
-
-Paths can have variables. They are defined using the format `{name}` or `{name:pattern}`. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example:
-
-```go
-r := mux.NewRouter()
-r.HandleFunc("/products/{key}", ProductHandler)
-r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
-r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
-```
-
-The names are used to create a map of route variables which can be retrieved calling `mux.Vars()`:
-
-```go
-func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
- vars := mux.Vars(r)
- w.WriteHeader(http.StatusOK)
- fmt.Fprintf(w, "Category: %v\n", vars["category"])
-}
-```
-
-And this is all you need to know about the basic usage. More advanced options are explained below.
-
-### Matching Routes
-
-Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables:
-
-```go
-r := mux.NewRouter()
-// Only matches if domain is "www.example.com".
-r.Host("www.example.com")
-// Matches a dynamic subdomain.
-r.Host("{subdomain:[a-z]+}.domain.com")
-```
-
-There are several other matchers that can be added. To match path prefixes:
-
-```go
-r.PathPrefix("/products/")
-```
-
-...or HTTP methods:
-
-```go
-r.Methods("GET", "POST")
-```
-
-...or URL schemes:
-
-```go
-r.Schemes("https")
-```
-
-...or header values:
-
-```go
-r.Headers("X-Requested-With", "XMLHttpRequest")
-```
-
-...or query values:
-
-```go
-r.Queries("key", "value")
-```
-
-...or to use a custom matcher function:
-
-```go
-r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
- return r.ProtoMajor == 0
-})
-```
-
-...and finally, it is possible to combine several matchers in a single route:
-
-```go
-r.HandleFunc("/products", ProductsHandler).
- Host("www.example.com").
- Methods("GET").
- Schemes("http")
-```
-
-Routes are tested in the order they were added to the router. If two routes match, the first one wins:
-
-```go
-r := mux.NewRouter()
-r.HandleFunc("/specific", specificHandler)
-r.PathPrefix("/").Handler(catchAllHandler)
-```
-
-Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting".
-
-For example, let's say we have several URLs that should only match when the host is `www.example.com`. Create a route for that host and get a "subrouter" from it:
-
-```go
-r := mux.NewRouter()
-s := r.Host("www.example.com").Subrouter()
-```
-
-Then register routes in the subrouter:
-
-```go
-s.HandleFunc("/products/", ProductsHandler)
-s.HandleFunc("/products/{key}", ProductHandler)
-s.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
-```
-
-The three URL paths we registered above will only be tested if the domain is `www.example.com`, because the subrouter is tested first. This is not only convenient, but also optimizes request matching. You can create subrouters combining any attribute matchers accepted by a route.
-
-Subrouters can be used to create domain or path "namespaces": you define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter.
-
-There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths:
-
-```go
-r := mux.NewRouter()
-s := r.PathPrefix("/products").Subrouter()
-// "/products/"
-s.HandleFunc("/", ProductsHandler)
-// "/products/{key}/"
-s.HandleFunc("/{key}/", ProductHandler)
-// "/products/{key}/details"
-s.HandleFunc("/{key}/details", ProductDetailsHandler)
-```
-
-
-### Static Files
-
-Note that the path provided to `PathPrefix()` represents a "wildcard": calling
-`PathPrefix("/static/").Handler(...)` means that the handler will be passed any
-request that matches "/static/\*". This makes it easy to serve static files with mux:
-
-```go
-func main() {
- var dir string
-
- flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
- flag.Parse()
- r := mux.NewRouter()
-
- // This will serve files under http://localhost:8000/static/<filename>
- r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
-
- srv := &http.Server{
- Handler: r,
- Addr: "127.0.0.1:8000",
- // Good practice: enforce timeouts for servers you create!
- WriteTimeout: 15 * time.Second,
- ReadTimeout: 15 * time.Second,
- }
-
- log.Fatal(srv.ListenAndServe())
-}
-```
-
-### Registered URLs
-
-Now let's see how to build registered URLs.
-
-Routes can be named. All routes that define a name can have their URLs built, or "reversed". We define a name calling `Name()` on a route. For example:
-
-```go
-r := mux.NewRouter()
-r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
- Name("article")
-```
-
-To build a URL, get the route and call the `URL()` method, passing a sequence of key/value pairs for the route variables. For the previous route, we would do:
-
-```go
-url, err := r.Get("article").URL("category", "technology", "id", "42")
-```
-
-...and the result will be a `url.URL` with the following path:
-
-```
-"/articles/technology/42"
-```
-
-This also works for host and query value variables:
-
-```go
-r := mux.NewRouter()
-r.Host("{subdomain}.domain.com").
- Path("/articles/{category}/{id:[0-9]+}").
- Queries("filter", "{filter}").
- HandlerFunc(ArticleHandler).
- Name("article")
-
-// url.String() will be "http://news.domain.com/articles/technology/42?filter=gorilla"
-url, err := r.Get("article").URL("subdomain", "news",
- "category", "technology",
- "id", "42",
- "filter", "gorilla")
-```
-
-All variables defined in the route are required, and their values must conform to the corresponding patterns. These requirements guarantee that a generated URL will always match a registered route -- the only exception is for explicitly defined "build-only" routes which never match.
-
-Regex support also exists for matching Headers within a route. For example, we could do:
-
-```go
-r.HeadersRegexp("Content-Type", "application/(text|json)")
-```
-
-...and the route will match both requests with a Content-Type of `application/json` as well as `application/text`
-
-There's also a way to build only the URL host or path for a route: use the methods `URLHost()` or `URLPath()` instead. For the previous route, we would do:
-
-```go
-// "http://news.domain.com/"
-host, err := r.Get("article").URLHost("subdomain", "news")
-
-// "/articles/technology/42"
-path, err := r.Get("article").URLPath("category", "technology", "id", "42")
-```
-
-And if you use subrouters, host and path defined separately can be built as well:
-
-```go
-r := mux.NewRouter()
-s := r.Host("{subdomain}.domain.com").Subrouter()
-s.Path("/articles/{category}/{id:[0-9]+}").
- HandlerFunc(ArticleHandler).
- Name("article")
-
-// "http://news.domain.com/articles/technology/42"
-url, err := r.Get("article").URL("subdomain", "news",
- "category", "technology",
- "id", "42")
-```
-
-### Walking Routes
-
-The `Walk` function on `mux.Router` can be used to visit all of the routes that are registered on a router. For example,
-the following prints all of the registered routes:
-
-```go
-package main
-
-import (
- "fmt"
- "net/http"
- "strings"
-
- "github.com/gorilla/mux"
-)
-
-func handler(w http.ResponseWriter, r *http.Request) {
- return
-}
-
-func main() {
- r := mux.NewRouter()
- r.HandleFunc("/", handler)
- r.HandleFunc("/products", handler).Methods("POST")
- r.HandleFunc("/articles", handler).Methods("GET")
- r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT")
- r.HandleFunc("/authors", handler).Queries("surname", "{surname}")
- err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
- pathTemplate, err := route.GetPathTemplate()
- if err == nil {
- fmt.Println("ROUTE:", pathTemplate)
- }
- pathRegexp, err := route.GetPathRegexp()
- if err == nil {
- fmt.Println("Path regexp:", pathRegexp)
- }
- queriesTemplates, err := route.GetQueriesTemplates()
- if err == nil {
- fmt.Println("Queries templates:", strings.Join(queriesTemplates, ","))
- }
- queriesRegexps, err := route.GetQueriesRegexp()
- if err == nil {
- fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ","))
- }
- methods, err := route.GetMethods()
- if err == nil {
- fmt.Println("Methods:", strings.Join(methods, ","))
- }
- fmt.Println()
- return nil
- })
-
- if err != nil {
- fmt.Println(err)
- }
-
- http.Handle("/", r)
-}
-```
-
-### Graceful Shutdown
-
-Go 1.8 introduced the ability to [gracefully shutdown](https://golang.org/doc/go1.8#http_shutdown) a `*http.Server`. Here's how to do that alongside `mux`:
-
-```go
-package main
-
-import (
- "context"
- "flag"
- "log"
- "net/http"
- "os"
- "os/signal"
- "time"
-
- "github.com/gorilla/mux"
-)
-
-func main() {
- var wait time.Duration
- flag.DurationVar(&wait, "graceful-timeout", time.Second * 15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m")
- flag.Parse()
-
- r := mux.NewRouter()
- // Add your routes as needed
-
- srv := &http.Server{
- Addr: "0.0.0.0:8080",
- // Good practice to set timeouts to avoid Slowloris attacks.
- WriteTimeout: time.Second * 15,
- ReadTimeout: time.Second * 15,
- IdleTimeout: time.Second * 60,
- Handler: r, // Pass our instance of gorilla/mux in.
- }
-
- // Run our server in a goroutine so that it doesn't block.
- go func() {
- if err := srv.ListenAndServe(); err != nil {
- log.Println(err)
- }
- }()
-
- c := make(chan os.Signal, 1)
- // We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
- // SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
- signal.Notify(c, os.Interrupt)
-
- // Block until we receive our signal.
- <-c
-
- // Create a deadline to wait for.
- ctx, cancel := context.WithTimeout(context.Background(), wait)
- defer cancel()
- // Doesn't block if no connections, but will otherwise wait
- // until the timeout deadline.
- srv.Shutdown(ctx)
- // Optionally, you could run srv.Shutdown in a goroutine and block on
- // <-ctx.Done() if your application should wait for other services
- // to finalize based on context cancellation.
- log.Println("shutting down")
- os.Exit(0)
-}
-```
-
-### Middleware
-
-Mux supports the addition of middlewares to a [Router](https://godoc.org/github.com/gorilla/mux#Router), which are executed in the order they are added if a match is found, including its subrouters.
-Middlewares are (typically) small pieces of code which take one request, do something with it, and pass it down to another middleware or the final handler. Some common use cases for middleware are request logging, header manipulation, or `ResponseWriter` hijacking.
-
-Mux middlewares are defined using the de facto standard type:
-
-```go
-type MiddlewareFunc func(http.Handler) http.Handler
-```
-
-Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed to it, and then calls the handler passed as parameter to the MiddlewareFunc. This takes advantage of closures being able access variables from the context where they are created, while retaining the signature enforced by the receivers.
-
-A very basic middleware which logs the URI of the request being handled could be written as:
-
-```go
-func loggingMiddleware(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // Do stuff here
- log.Println(r.RequestURI)
- // Call the next handler, which can be another middleware in the chain, or the final handler.
- next.ServeHTTP(w, r)
- })
-}
-```
-
-Middlewares can be added to a router using `Router.Use()`:
-
-```go
-r := mux.NewRouter()
-r.HandleFunc("/", handler)
-r.Use(loggingMiddleware)
-```
-
-A more complex authentication middleware, which maps session token to users, could be written as:
-
-```go
-// Define our struct
-type authenticationMiddleware struct {
- tokenUsers map[string]string
-}
-
-// Initialize it somewhere
-func (amw *authenticationMiddleware) Populate() {
- amw.tokenUsers["00000000"] = "user0"
- amw.tokenUsers["aaaaaaaa"] = "userA"
- amw.tokenUsers["05f717e5"] = "randomUser"
- amw.tokenUsers["deadbeef"] = "user0"
-}
-
-// Middleware function, which will be called for each request
-func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- token := r.Header.Get("X-Session-Token")
-
- if user, found := amw.tokenUsers[token]; found {
- // We found the token in our map
- log.Printf("Authenticated user %s\n", user)
- // Pass down the request to the next middleware (or final handler)
- next.ServeHTTP(w, r)
- } else {
- // Write an error and stop the handler chain
- http.Error(w, "Forbidden", http.StatusForbidden)
- }
- })
-}
-```
-
-```go
-r := mux.NewRouter()
-r.HandleFunc("/", handler)
-
-amw := authenticationMiddleware{}
-amw.Populate()
-
-r.Use(amw.Middleware)
-```
-
-Note: The handler chain will be stopped if your middleware doesn't call `next.ServeHTTP()` with the corresponding parameters. This can be used to abort a request if the middleware writer wants to. Middlewares _should_ write to `ResponseWriter` if they _are_ going to terminate the request, and they _should not_ write to `ResponseWriter` if they _are not_ going to terminate it.
-
-### Testing Handlers
-
-Testing handlers in a Go web application is straightforward, and _mux_ doesn't complicate this any further. Given two files: `endpoints.go` and `endpoints_test.go`, here's how we'd test an application using _mux_.
-
-First, our simple HTTP handler:
-
-```go
-// endpoints.go
-package main
-
-func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
- // A very simple health check.
- w.WriteHeader(http.StatusOK)
- w.Header().Set("Content-Type", "application/json")
-
- // In the future we could report back on the status of our DB, or our cache
- // (e.g. Redis) by performing a simple PING, and include them in the response.
- io.WriteString(w, `{"alive": true}`)
-}
-
-func main() {
- r := mux.NewRouter()
- r.HandleFunc("/health", HealthCheckHandler)
-
- log.Fatal(http.ListenAndServe("localhost:8080", r))
-}
-```
-
-Our test code:
-
-```go
-// endpoints_test.go
-package main
-
-import (
- "net/http"
- "net/http/httptest"
- "testing"
-)
-
-func TestHealthCheckHandler(t *testing.T) {
- // Create a request to pass to our handler. We don't have any query parameters for now, so we'll
- // pass 'nil' as the third parameter.
- req, err := http.NewRequest("GET", "/health", nil)
- if err != nil {
- t.Fatal(err)
- }
-
- // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
- rr := httptest.NewRecorder()
- handler := http.HandlerFunc(HealthCheckHandler)
-
- // Our handlers satisfy http.Handler, so we can call their ServeHTTP method
- // directly and pass in our Request and ResponseRecorder.
- handler.ServeHTTP(rr, req)
-
- // Check the status code is what we expect.
- if status := rr.Code; status != http.StatusOK {
- t.Errorf("handler returned wrong status code: got %v want %v",
- status, http.StatusOK)
- }
-
- // Check the response body is what we expect.
- expected := `{"alive": true}`
- if rr.Body.String() != expected {
- t.Errorf("handler returned unexpected body: got %v want %v",
- rr.Body.String(), expected)
- }
-}
-```
-
-In the case that our routes have [variables](#examples), we can pass those in the request. We could write
-[table-driven tests](https://dave.cheney.net/2013/06/09/writing-table-driven-tests-in-go) to test multiple
-possible route variables as needed.
-
-```go
-// endpoints.go
-func main() {
- r := mux.NewRouter()
- // A route with a route variable:
- r.HandleFunc("/metrics/{type}", MetricsHandler)
-
- log.Fatal(http.ListenAndServe("localhost:8080", r))
-}
-```
-
-Our test file, with a table-driven test of `routeVariables`:
-
-```go
-// endpoints_test.go
-func TestMetricsHandler(t *testing.T) {
- tt := []struct{
- routeVariable string
- shouldPass bool
- }{
- {"goroutines", true},
- {"heap", true},
- {"counters", true},
- {"queries", true},
- {"adhadaeqm3k", false},
- }
-
- for _, tc := range tt {
- path := fmt.Sprintf("/metrics/%s", tc.routeVariable)
- req, err := http.NewRequest("GET", path, nil)
- if err != nil {
- t.Fatal(err)
- }
-
- rr := httptest.NewRecorder()
-
- // Need to create a router that we can pass the request through so that the vars will be added to the context
- router := mux.NewRouter()
- router.HandleFunc("/metrics/{type}", MetricsHandler)
- router.ServeHTTP(rr, req)
-
- // In this case, our MetricsHandler returns a non-200 response
- // for a route variable it doesn't know about.
- if rr.Code == http.StatusOK && !tc.shouldPass {
- t.Errorf("handler should have failed on routeVariable %s: got %v want %v",
- tc.routeVariable, rr.Code, http.StatusOK)
- }
- }
-}
-```
-
-## Full Example
-
-Here's a complete, runnable example of a small `mux` based server:
-
-```go
-package main
-
-import (
- "net/http"
- "log"
- "github.com/gorilla/mux"
-)
-
-func YourHandler(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("Gorilla!\n"))
-}
-
-func main() {
- r := mux.NewRouter()
- // Routes consist of a path and a handler function.
- r.HandleFunc("/", YourHandler)
-
- // Bind to a port and pass our router in
- log.Fatal(http.ListenAndServe(":8000", r))
-}
-```
-
-## License
-
-BSD licensed. See the LICENSE file for details.
diff --git a/vendor/github.com/gorilla/mux/context_gorilla.go b/vendor/github.com/gorilla/mux/context_gorilla.go
deleted file mode 100644
index d7adaa8..0000000
--- a/vendor/github.com/gorilla/mux/context_gorilla.go
+++ /dev/null
@@ -1,26 +0,0 @@
-// +build !go1.7
-
-package mux
-
-import (
- "net/http"
-
- "github.com/gorilla/context"
-)
-
-func contextGet(r *http.Request, key interface{}) interface{} {
- return context.Get(r, key)
-}
-
-func contextSet(r *http.Request, key, val interface{}) *http.Request {
- if val == nil {
- return r
- }
-
- context.Set(r, key, val)
- return r
-}
-
-func contextClear(r *http.Request) {
- context.Clear(r)
-}
diff --git a/vendor/github.com/gorilla/mux/context_native.go b/vendor/github.com/gorilla/mux/context_native.go
deleted file mode 100644
index 209cbea..0000000
--- a/vendor/github.com/gorilla/mux/context_native.go
+++ /dev/null
@@ -1,24 +0,0 @@
-// +build go1.7
-
-package mux
-
-import (
- "context"
- "net/http"
-)
-
-func contextGet(r *http.Request, key interface{}) interface{} {
- return r.Context().Value(key)
-}
-
-func contextSet(r *http.Request, key, val interface{}) *http.Request {
- if val == nil {
- return r
- }
-
- return r.WithContext(context.WithValue(r.Context(), key, val))
-}
-
-func contextClear(r *http.Request) {
- return
-}
diff --git a/vendor/github.com/gorilla/mux/doc.go b/vendor/github.com/gorilla/mux/doc.go
deleted file mode 100644
index 38957de..0000000
--- a/vendor/github.com/gorilla/mux/doc.go
+++ /dev/null
@@ -1,306 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-/*
-Package mux implements a request router and dispatcher.
-
-The name mux stands for "HTTP request multiplexer". Like the standard
-http.ServeMux, mux.Router matches incoming requests against a list of
-registered routes and calls a handler for the route that matches the URL
-or other conditions. The main features are:
-
- * Requests can be matched based on URL host, path, path prefix, schemes,
- header and query values, HTTP methods or using custom matchers.
- * URL hosts, paths and query values can have variables with an optional
- regular expression.
- * Registered URLs can be built, or "reversed", which helps maintaining
- references to resources.
- * Routes can be used as subrouters: nested routes are only tested if the
- parent route matches. This is useful to define groups of routes that
- share common conditions like a host, a path prefix or other repeated
- attributes. As a bonus, this optimizes request matching.
- * It implements the http.Handler interface so it is compatible with the
- standard http.ServeMux.
-
-Let's start registering a couple of URL paths and handlers:
-
- func main() {
- r := mux.NewRouter()
- r.HandleFunc("/", HomeHandler)
- r.HandleFunc("/products", ProductsHandler)
- r.HandleFunc("/articles", ArticlesHandler)
- http.Handle("/", r)
- }
-
-Here we register three routes mapping URL paths to handlers. This is
-equivalent to how http.HandleFunc() works: if an incoming request URL matches
-one of the paths, the corresponding handler is called passing
-(http.ResponseWriter, *http.Request) as parameters.
-
-Paths can have variables. They are defined using the format {name} or
-{name:pattern}. If a regular expression pattern is not defined, the matched
-variable will be anything until the next slash. For example:
-
- r := mux.NewRouter()
- r.HandleFunc("/products/{key}", ProductHandler)
- r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
- r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
-
-Groups can be used inside patterns, as long as they are non-capturing (?:re). For example:
-
- r.HandleFunc("/articles/{category}/{sort:(?:asc|desc|new)}", ArticlesCategoryHandler)
-
-The names are used to create a map of route variables which can be retrieved
-calling mux.Vars():
-
- vars := mux.Vars(request)
- category := vars["category"]
-
-Note that if any capturing groups are present, mux will panic() during parsing. To prevent
-this, convert any capturing groups to non-capturing, e.g. change "/{sort:(asc|desc)}" to
-"/{sort:(?:asc|desc)}". This is a change from prior versions which behaved unpredictably
-when capturing groups were present.
-
-And this is all you need to know about the basic usage. More advanced options
-are explained below.
-
-Routes can also be restricted to a domain or subdomain. Just define a host
-pattern to be matched. They can also have variables:
-
- r := mux.NewRouter()
- // Only matches if domain is "www.example.com".
- r.Host("www.example.com")
- // Matches a dynamic subdomain.
- r.Host("{subdomain:[a-z]+}.domain.com")
-
-There are several other matchers that can be added. To match path prefixes:
-
- r.PathPrefix("/products/")
-
-...or HTTP methods:
-
- r.Methods("GET", "POST")
-
-...or URL schemes:
-
- r.Schemes("https")
-
-...or header values:
-
- r.Headers("X-Requested-With", "XMLHttpRequest")
-
-...or query values:
-
- r.Queries("key", "value")
-
-...or to use a custom matcher function:
-
- r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
- return r.ProtoMajor == 0
- })
-
-...and finally, it is possible to combine several matchers in a single route:
-
- r.HandleFunc("/products", ProductsHandler).
- Host("www.example.com").
- Methods("GET").
- Schemes("http")
-
-Setting the same matching conditions again and again can be boring, so we have
-a way to group several routes that share the same requirements.
-We call it "subrouting".
-
-For example, let's say we have several URLs that should only match when the
-host is "www.example.com". Create a route for that host and get a "subrouter"
-from it:
-
- r := mux.NewRouter()
- s := r.Host("www.example.com").Subrouter()
-
-Then register routes in the subrouter:
-
- s.HandleFunc("/products/", ProductsHandler)
- s.HandleFunc("/products/{key}", ProductHandler)
- s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
-
-The three URL paths we registered above will only be tested if the domain is
-"www.example.com", because the subrouter is tested first. This is not
-only convenient, but also optimizes request matching. You can create
-subrouters combining any attribute matchers accepted by a route.
-
-Subrouters can be used to create domain or path "namespaces": you define
-subrouters in a central place and then parts of the app can register its
-paths relatively to a given subrouter.
-
-There's one more thing about subroutes. When a subrouter has a path prefix,
-the inner routes use it as base for their paths:
-
- r := mux.NewRouter()
- s := r.PathPrefix("/products").Subrouter()
- // "/products/"
- s.HandleFunc("/", ProductsHandler)
- // "/products/{key}/"
- s.HandleFunc("/{key}/", ProductHandler)
- // "/products/{key}/details"
- s.HandleFunc("/{key}/details", ProductDetailsHandler)
-
-Note that the path provided to PathPrefix() represents a "wildcard": calling
-PathPrefix("/static/").Handler(...) means that the handler will be passed any
-request that matches "/static/*". This makes it easy to serve static files with mux:
-
- func main() {
- var dir string
-
- flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
- flag.Parse()
- r := mux.NewRouter()
-
- // This will serve files under http://localhost:8000/static/<filename>
- r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
-
- srv := &http.Server{
- Handler: r,
- Addr: "127.0.0.1:8000",
- // Good practice: enforce timeouts for servers you create!
- WriteTimeout: 15 * time.Second,
- ReadTimeout: 15 * time.Second,
- }
-
- log.Fatal(srv.ListenAndServe())
- }
-
-Now let's see how to build registered URLs.
-
-Routes can be named. All routes that define a name can have their URLs built,
-or "reversed". We define a name calling Name() on a route. For example:
-
- r := mux.NewRouter()
- r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
- Name("article")
-
-To build a URL, get the route and call the URL() method, passing a sequence of
-key/value pairs for the route variables. For the previous route, we would do:
-
- url, err := r.Get("article").URL("category", "technology", "id", "42")
-
-...and the result will be a url.URL with the following path:
-
- "/articles/technology/42"
-
-This also works for host and query value variables:
-
- r := mux.NewRouter()
- r.Host("{subdomain}.domain.com").
- Path("/articles/{category}/{id:[0-9]+}").
- Queries("filter", "{filter}").
- HandlerFunc(ArticleHandler).
- Name("article")
-
- // url.String() will be "http://news.domain.com/articles/technology/42?filter=gorilla"
- url, err := r.Get("article").URL("subdomain", "news",
- "category", "technology",
- "id", "42",
- "filter", "gorilla")
-
-All variables defined in the route are required, and their values must
-conform to the corresponding patterns. These requirements guarantee that a
-generated URL will always match a registered route -- the only exception is
-for explicitly defined "build-only" routes which never match.
-
-Regex support also exists for matching Headers within a route. For example, we could do:
-
- r.HeadersRegexp("Content-Type", "application/(text|json)")
-
-...and the route will match both requests with a Content-Type of `application/json` as well as
-`application/text`
-
-There's also a way to build only the URL host or path for a route:
-use the methods URLHost() or URLPath() instead. For the previous route,
-we would do:
-
- // "http://news.domain.com/"
- host, err := r.Get("article").URLHost("subdomain", "news")
-
- // "/articles/technology/42"
- path, err := r.Get("article").URLPath("category", "technology", "id", "42")
-
-And if you use subrouters, host and path defined separately can be built
-as well:
-
- r := mux.NewRouter()
- s := r.Host("{subdomain}.domain.com").Subrouter()
- s.Path("/articles/{category}/{id:[0-9]+}").
- HandlerFunc(ArticleHandler).
- Name("article")
-
- // "http://news.domain.com/articles/technology/42"
- url, err := r.Get("article").URL("subdomain", "news",
- "category", "technology",
- "id", "42")
-
-Mux supports the addition of middlewares to a Router, which are executed in the order they are added if a match is found, including its subrouters. Middlewares are (typically) small pieces of code which take one request, do something with it, and pass it down to another middleware or the final handler. Some common use cases for middleware are request logging, header manipulation, or ResponseWriter hijacking.
-
- type MiddlewareFunc func(http.Handler) http.Handler
-
-Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed to it, and then calls the handler passed as parameter to the MiddlewareFunc (closures can access variables from the context where they are created).
-
-A very basic middleware which logs the URI of the request being handled could be written as:
-
- func simpleMw(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- // Do stuff here
- log.Println(r.RequestURI)
- // Call the next handler, which can be another middleware in the chain, or the final handler.
- next.ServeHTTP(w, r)
- })
- }
-
-Middlewares can be added to a router using `Router.Use()`:
-
- r := mux.NewRouter()
- r.HandleFunc("/", handler)
- r.Use(simpleMw)
-
-A more complex authentication middleware, which maps session token to users, could be written as:
-
- // Define our struct
- type authenticationMiddleware struct {
- tokenUsers map[string]string
- }
-
- // Initialize it somewhere
- func (amw *authenticationMiddleware) Populate() {
- amw.tokenUsers["00000000"] = "user0"
- amw.tokenUsers["aaaaaaaa"] = "userA"
- amw.tokenUsers["05f717e5"] = "randomUser"
- amw.tokenUsers["deadbeef"] = "user0"
- }
-
- // Middleware function, which will be called for each request
- func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- token := r.Header.Get("X-Session-Token")
-
- if user, found := amw.tokenUsers[token]; found {
- // We found the token in our map
- log.Printf("Authenticated user %s\n", user)
- next.ServeHTTP(w, r)
- } else {
- http.Error(w, "Forbidden", http.StatusForbidden)
- }
- })
- }
-
- r := mux.NewRouter()
- r.HandleFunc("/", handler)
-
- amw := authenticationMiddleware{}
- amw.Populate()
-
- r.Use(amw.Middleware)
-
-Note: The handler chain will be stopped if your middleware doesn't call `next.ServeHTTP()` with the corresponding parameters. This can be used to abort a request if the middleware writer wants to.
-
-*/
-package mux
diff --git a/vendor/github.com/gorilla/mux/go.mod b/vendor/github.com/gorilla/mux/go.mod
deleted file mode 100644
index cfc8ede..0000000
--- a/vendor/github.com/gorilla/mux/go.mod
+++ /dev/null
@@ -1 +0,0 @@
-module github.com/gorilla/mux
diff --git a/vendor/github.com/gorilla/mux/middleware.go b/vendor/github.com/gorilla/mux/middleware.go
deleted file mode 100644
index ceb812c..0000000
--- a/vendor/github.com/gorilla/mux/middleware.go
+++ /dev/null
@@ -1,72 +0,0 @@
-package mux
-
-import (
- "net/http"
- "strings"
-)
-
-// MiddlewareFunc is a function which receives an http.Handler and returns another http.Handler.
-// Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed
-// to it, and then calls the handler passed as parameter to the MiddlewareFunc.
-type MiddlewareFunc func(http.Handler) http.Handler
-
-// middleware interface is anything which implements a MiddlewareFunc named Middleware.
-type middleware interface {
- Middleware(handler http.Handler) http.Handler
-}
-
-// Middleware allows MiddlewareFunc to implement the middleware interface.
-func (mw MiddlewareFunc) Middleware(handler http.Handler) http.Handler {
- return mw(handler)
-}
-
-// Use appends a MiddlewareFunc to the chain. Middleware can be used to intercept or otherwise modify requests and/or responses, and are executed in the order that they are applied to the Router.
-func (r *Router) Use(mwf ...MiddlewareFunc) {
- for _, fn := range mwf {
- r.middlewares = append(r.middlewares, fn)
- }
-}
-
-// useInterface appends a middleware to the chain. Middleware can be used to intercept or otherwise modify requests and/or responses, and are executed in the order that they are applied to the Router.
-func (r *Router) useInterface(mw middleware) {
- r.middlewares = append(r.middlewares, mw)
-}
-
-// CORSMethodMiddleware sets the Access-Control-Allow-Methods response header
-// on a request, by matching routes based only on paths. It also handles
-// OPTIONS requests, by settings Access-Control-Allow-Methods, and then
-// returning without calling the next http handler.
-func CORSMethodMiddleware(r *Router) MiddlewareFunc {
- return func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
- var allMethods []string
-
- err := r.Walk(func(route *Route, _ *Router, _ []*Route) error {
- for _, m := range route.matchers {
- if _, ok := m.(*routeRegexp); ok {
- if m.Match(req, &RouteMatch{}) {
- methods, err := route.GetMethods()
- if err != nil {
- return err
- }
-
- allMethods = append(allMethods, methods...)
- }
- break
- }
- }
- return nil
- })
-
- if err == nil {
- w.Header().Set("Access-Control-Allow-Methods", strings.Join(append(allMethods, "OPTIONS"), ","))
-
- if req.Method == "OPTIONS" {
- return
- }
- }
-
- next.ServeHTTP(w, req)
- })
- }
-}
diff --git a/vendor/github.com/gorilla/mux/mux.go b/vendor/github.com/gorilla/mux/mux.go
deleted file mode 100644
index 4bbafa5..0000000
--- a/vendor/github.com/gorilla/mux/mux.go
+++ /dev/null
@@ -1,588 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package mux
-
-import (
- "errors"
- "fmt"
- "net/http"
- "path"
- "regexp"
-)
-
-var (
- // ErrMethodMismatch is returned when the method in the request does not match
- // the method defined against the route.
- ErrMethodMismatch = errors.New("method is not allowed")
- // ErrNotFound is returned when no route match is found.
- ErrNotFound = errors.New("no matching route was found")
-)
-
-// NewRouter returns a new router instance.
-func NewRouter() *Router {
- return &Router{namedRoutes: make(map[string]*Route), KeepContext: false}
-}
-
-// Router registers routes to be matched and dispatches a handler.
-//
-// It implements the http.Handler interface, so it can be registered to serve
-// requests:
-//
-// var router = mux.NewRouter()
-//
-// func main() {
-// http.Handle("/", router)
-// }
-//
-// Or, for Google App Engine, register it in a init() function:
-//
-// func init() {
-// http.Handle("/", router)
-// }
-//
-// This will send all incoming requests to the router.
-type Router struct {
- // Configurable Handler to be used when no route matches.
- NotFoundHandler http.Handler
-
- // Configurable Handler to be used when the request method does not match the route.
- MethodNotAllowedHandler http.Handler
-
- // Parent route, if this is a subrouter.
- parent parentRoute
- // Routes to be matched, in order.
- routes []*Route
- // Routes by name for URL building.
- namedRoutes map[string]*Route
- // See Router.StrictSlash(). This defines the flag for new routes.
- strictSlash bool
- // See Router.SkipClean(). This defines the flag for new routes.
- skipClean bool
- // If true, do not clear the request context after handling the request.
- // This has no effect when go1.7+ is used, since the context is stored
- // on the request itself.
- KeepContext bool
- // see Router.UseEncodedPath(). This defines a flag for all routes.
- useEncodedPath bool
- // Slice of middlewares to be called after a match is found
- middlewares []middleware
-}
-
-// Match attempts to match the given request against the router's registered routes.
-//
-// If the request matches a route of this router or one of its subrouters the Route,
-// Handler, and Vars fields of the the match argument are filled and this function
-// returns true.
-//
-// If the request does not match any of this router's or its subrouters' routes
-// then this function returns false. If available, a reason for the match failure
-// will be filled in the match argument's MatchErr field. If the match failure type
-// (eg: not found) has a registered handler, the handler is assigned to the Handler
-// field of the match argument.
-func (r *Router) Match(req *http.Request, match *RouteMatch) bool {
- for _, route := range r.routes {
- if route.Match(req, match) {
- // Build middleware chain if no error was found
- if match.MatchErr == nil {
- for i := len(r.middlewares) - 1; i >= 0; i-- {
- match.Handler = r.middlewares[i].Middleware(match.Handler)
- }
- }
- return true
- }
- }
-
- if match.MatchErr == ErrMethodMismatch {
- if r.MethodNotAllowedHandler != nil {
- match.Handler = r.MethodNotAllowedHandler
- return true
- }
-
- return false
- }
-
- // Closest match for a router (includes sub-routers)
- if r.NotFoundHandler != nil {
- match.Handler = r.NotFoundHandler
- match.MatchErr = ErrNotFound
- return true
- }
-
- match.MatchErr = ErrNotFound
- return false
-}
-
-// ServeHTTP dispatches the handler registered in the matched route.
-//
-// When there is a match, the route variables can be retrieved calling
-// mux.Vars(request).
-func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
- if !r.skipClean {
- path := req.URL.Path
- if r.useEncodedPath {
- path = req.URL.EscapedPath()
- }
- // Clean path to canonical form and redirect.
- if p := cleanPath(path); p != path {
-
- // Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query.
- // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue:
- // http://code.google.com/p/go/issues/detail?id=5252
- url := *req.URL
- url.Path = p
- p = url.String()
-
- w.Header().Set("Location", p)
- w.WriteHeader(http.StatusMovedPermanently)
- return
- }
- }
- var match RouteMatch
- var handler http.Handler
- if r.Match(req, &match) {
- handler = match.Handler
- req = setVars(req, match.Vars)
- req = setCurrentRoute(req, match.Route)
- }
-
- if handler == nil && match.MatchErr == ErrMethodMismatch {
- handler = methodNotAllowedHandler()
- }
-
- if handler == nil {
- handler = http.NotFoundHandler()
- }
-
- if !r.KeepContext {
- defer contextClear(req)
- }
-
- handler.ServeHTTP(w, req)
-}
-
-// Get returns a route registered with the given name.
-func (r *Router) Get(name string) *Route {
- return r.getNamedRoutes()[name]
-}
-
-// GetRoute returns a route registered with the given name. This method
-// was renamed to Get() and remains here for backwards compatibility.
-func (r *Router) GetRoute(name string) *Route {
- return r.getNamedRoutes()[name]
-}
-
-// StrictSlash defines the trailing slash behavior for new routes. The initial
-// value is false.
-//
-// When true, if the route path is "/path/", accessing "/path" will perform a redirect
-// to the former and vice versa. In other words, your application will always
-// see the path as specified in the route.
-//
-// When false, if the route path is "/path", accessing "/path/" will not match
-// this route and vice versa.
-//
-// The re-direct is a HTTP 301 (Moved Permanently). Note that when this is set for
-// routes with a non-idempotent method (e.g. POST, PUT), the subsequent re-directed
-// request will be made as a GET by most clients. Use middleware or client settings
-// to modify this behaviour as needed.
-//
-// Special case: when a route sets a path prefix using the PathPrefix() method,
-// strict slash is ignored for that route because the redirect behavior can't
-// be determined from a prefix alone. However, any subrouters created from that
-// route inherit the original StrictSlash setting.
-func (r *Router) StrictSlash(value bool) *Router {
- r.strictSlash = value
- return r
-}
-
-// SkipClean defines the path cleaning behaviour for new routes. The initial
-// value is false. Users should be careful about which routes are not cleaned
-//
-// When true, if the route path is "/path//to", it will remain with the double
-// slash. This is helpful if you have a route like: /fetch/http://xkcd.com/534/
-//
-// When false, the path will be cleaned, so /fetch/http://xkcd.com/534/ will
-// become /fetch/http/xkcd.com/534
-func (r *Router) SkipClean(value bool) *Router {
- r.skipClean = value
- return r
-}
-
-// UseEncodedPath tells the router to match the encoded original path
-// to the routes.
-// For eg. "/path/foo%2Fbar/to" will match the path "/path/{var}/to".
-//
-// If not called, the router will match the unencoded path to the routes.
-// For eg. "/path/foo%2Fbar/to" will match the path "/path/foo/bar/to"
-func (r *Router) UseEncodedPath() *Router {
- r.useEncodedPath = true
- return r
-}
-
-// ----------------------------------------------------------------------------
-// parentRoute
-// ----------------------------------------------------------------------------
-
-func (r *Router) getBuildScheme() string {
- if r.parent != nil {
- return r.parent.getBuildScheme()
- }
- return ""
-}
-
-// getNamedRoutes returns the map where named routes are registered.
-func (r *Router) getNamedRoutes() map[string]*Route {
- if r.namedRoutes == nil {
- if r.parent != nil {
- r.namedRoutes = r.parent.getNamedRoutes()
- } else {
- r.namedRoutes = make(map[string]*Route)
- }
- }
- return r.namedRoutes
-}
-
-// getRegexpGroup returns regexp definitions from the parent route, if any.
-func (r *Router) getRegexpGroup() *routeRegexpGroup {
- if r.parent != nil {
- return r.parent.getRegexpGroup()
- }
- return nil
-}
-
-func (r *Router) buildVars(m map[string]string) map[string]string {
- if r.parent != nil {
- m = r.parent.buildVars(m)
- }
- return m
-}
-
-// ----------------------------------------------------------------------------
-// Route factories
-// ----------------------------------------------------------------------------
-
-// NewRoute registers an empty route.
-func (r *Router) NewRoute() *Route {
- route := &Route{parent: r, strictSlash: r.strictSlash, skipClean: r.skipClean, useEncodedPath: r.useEncodedPath}
- r.routes = append(r.routes, route)
- return route
-}
-
-// Handle registers a new route with a matcher for the URL path.
-// See Route.Path() and Route.Handler().
-func (r *Router) Handle(path string, handler http.Handler) *Route {
- return r.NewRoute().Path(path).Handler(handler)
-}
-
-// HandleFunc registers a new route with a matcher for the URL path.
-// See Route.Path() and Route.HandlerFunc().
-func (r *Router) HandleFunc(path string, f func(http.ResponseWriter,
- *http.Request)) *Route {
- return r.NewRoute().Path(path).HandlerFunc(f)
-}
-
-// Headers registers a new route with a matcher for request header values.
-// See Route.Headers().
-func (r *Router) Headers(pairs ...string) *Route {
- return r.NewRoute().Headers(pairs...)
-}
-
-// Host registers a new route with a matcher for the URL host.
-// See Route.Host().
-func (r *Router) Host(tpl string) *Route {
- return r.NewRoute().Host(tpl)
-}
-
-// MatcherFunc registers a new route with a custom matcher function.
-// See Route.MatcherFunc().
-func (r *Router) MatcherFunc(f MatcherFunc) *Route {
- return r.NewRoute().MatcherFunc(f)
-}
-
-// Methods registers a new route with a matcher for HTTP methods.
-// See Route.Methods().
-func (r *Router) Methods(methods ...string) *Route {
- return r.NewRoute().Methods(methods...)
-}
-
-// Path registers a new route with a matcher for the URL path.
-// See Route.Path().
-func (r *Router) Path(tpl string) *Route {
- return r.NewRoute().Path(tpl)
-}
-
-// PathPrefix registers a new route with a matcher for the URL path prefix.
-// See Route.PathPrefix().
-func (r *Router) PathPrefix(tpl string) *Route {
- return r.NewRoute().PathPrefix(tpl)
-}
-
-// Queries registers a new route with a matcher for URL query values.
-// See Route.Queries().
-func (r *Router) Queries(pairs ...string) *Route {
- return r.NewRoute().Queries(pairs...)
-}
-
-// Schemes registers a new route with a matcher for URL schemes.
-// See Route.Schemes().
-func (r *Router) Schemes(schemes ...string) *Route {
- return r.NewRoute().Schemes(schemes...)
-}
-
-// BuildVarsFunc registers a new route with a custom function for modifying
-// route variables before building a URL.
-func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route {
- return r.NewRoute().BuildVarsFunc(f)
-}
-
-// Walk walks the router and all its sub-routers, calling walkFn for each route
-// in the tree. The routes are walked in the order they were added. Sub-routers
-// are explored depth-first.
-func (r *Router) Walk(walkFn WalkFunc) error {
- return r.walk(walkFn, []*Route{})
-}
-
-// SkipRouter is used as a return value from WalkFuncs to indicate that the
-// router that walk is about to descend down to should be skipped.
-var SkipRouter = errors.New("skip this router")
-
-// WalkFunc is the type of the function called for each route visited by Walk.
-// At every invocation, it is given the current route, and the current router,
-// and a list of ancestor routes that lead to the current route.
-type WalkFunc func(route *Route, router *Router, ancestors []*Route) error
-
-func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
- for _, t := range r.routes {
- err := walkFn(t, r, ancestors)
- if err == SkipRouter {
- continue
- }
- if err != nil {
- return err
- }
- for _, sr := range t.matchers {
- if h, ok := sr.(*Router); ok {
- ancestors = append(ancestors, t)
- err := h.walk(walkFn, ancestors)
- if err != nil {
- return err
- }
- ancestors = ancestors[:len(ancestors)-1]
- }
- }
- if h, ok := t.handler.(*Router); ok {
- ancestors = append(ancestors, t)
- err := h.walk(walkFn, ancestors)
- if err != nil {
- return err
- }
- ancestors = ancestors[:len(ancestors)-1]
- }
- }
- return nil
-}
-
-// ----------------------------------------------------------------------------
-// Context
-// ----------------------------------------------------------------------------
-
-// RouteMatch stores information about a matched route.
-type RouteMatch struct {
- Route *Route
- Handler http.Handler
- Vars map[string]string
-
- // MatchErr is set to appropriate matching error
- // It is set to ErrMethodMismatch if there is a mismatch in
- // the request method and route method
- MatchErr error
-}
-
-type contextKey int
-
-const (
- varsKey contextKey = iota
- routeKey
-)
-
-// Vars returns the route variables for the current request, if any.
-func Vars(r *http.Request) map[string]string {
- if rv := contextGet(r, varsKey); rv != nil {
- return rv.(map[string]string)
- }
- return nil
-}
-
-// CurrentRoute returns the matched route for the current request, if any.
-// This only works when called inside the handler of the matched route
-// because the matched route is stored in the request context which is cleared
-// after the handler returns, unless the KeepContext option is set on the
-// Router.
-func CurrentRoute(r *http.Request) *Route {
- if rv := contextGet(r, routeKey); rv != nil {
- return rv.(*Route)
- }
- return nil
-}
-
-func setVars(r *http.Request, val interface{}) *http.Request {
- return contextSet(r, varsKey, val)
-}
-
-func setCurrentRoute(r *http.Request, val interface{}) *http.Request {
- return contextSet(r, routeKey, val)
-}
-
-// ----------------------------------------------------------------------------
-// Helpers
-// ----------------------------------------------------------------------------
-
-// cleanPath returns the canonical path for p, eliminating . and .. elements.
-// Borrowed from the net/http package.
-func cleanPath(p string) string {
- if p == "" {
- return "/"
- }
- if p[0] != '/' {
- p = "/" + p
- }
- np := path.Clean(p)
- // path.Clean removes trailing slash except for root;
- // put the trailing slash back if necessary.
- if p[len(p)-1] == '/' && np != "/" {
- np += "/"
- }
-
- return np
-}
-
-// uniqueVars returns an error if two slices contain duplicated strings.
-func uniqueVars(s1, s2 []string) error {
- for _, v1 := range s1 {
- for _, v2 := range s2 {
- if v1 == v2 {
- return fmt.Errorf("mux: duplicated route variable %q", v2)
- }
- }
- }
- return nil
-}
-
-// checkPairs returns the count of strings passed in, and an error if
-// the count is not an even number.
-func checkPairs(pairs ...string) (int, error) {
- length := len(pairs)
- if length%2 != 0 {
- return length, fmt.Errorf(
- "mux: number of parameters must be multiple of 2, got %v", pairs)
- }
- return length, nil
-}
-
-// mapFromPairsToString converts variadic string parameters to a
-// string to string map.
-func mapFromPairsToString(pairs ...string) (map[string]string, error) {
- length, err := checkPairs(pairs...)
- if err != nil {
- return nil, err
- }
- m := make(map[string]string, length/2)
- for i := 0; i < length; i += 2 {
- m[pairs[i]] = pairs[i+1]
- }
- return m, nil
-}
-
-// mapFromPairsToRegex converts variadic string parameters to a
-// string to regex map.
-func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) {
- length, err := checkPairs(pairs...)
- if err != nil {
- return nil, err
- }
- m := make(map[string]*regexp.Regexp, length/2)
- for i := 0; i < length; i += 2 {
- regex, err := regexp.Compile(pairs[i+1])
- if err != nil {
- return nil, err
- }
- m[pairs[i]] = regex
- }
- return m, nil
-}
-
-// matchInArray returns true if the given string value is in the array.
-func matchInArray(arr []string, value string) bool {
- for _, v := range arr {
- if v == value {
- return true
- }
- }
- return false
-}
-
-// matchMapWithString returns true if the given key/value pairs exist in a given map.
-func matchMapWithString(toCheck map[string]string, toMatch map[string][]string, canonicalKey bool) bool {
- for k, v := range toCheck {
- // Check if key exists.
- if canonicalKey {
- k = http.CanonicalHeaderKey(k)
- }
- if values := toMatch[k]; values == nil {
- return false
- } else if v != "" {
- // If value was defined as an empty string we only check that the
- // key exists. Otherwise we also check for equality.
- valueExists := false
- for _, value := range values {
- if v == value {
- valueExists = true
- break
- }
- }
- if !valueExists {
- return false
- }
- }
- }
- return true
-}
-
-// matchMapWithRegex returns true if the given key/value pairs exist in a given map compiled against
-// the given regex
-func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]string, canonicalKey bool) bool {
- for k, v := range toCheck {
- // Check if key exists.
- if canonicalKey {
- k = http.CanonicalHeaderKey(k)
- }
- if values := toMatch[k]; values == nil {
- return false
- } else if v != nil {
- // If value was defined as an empty string we only check that the
- // key exists. Otherwise we also check for equality.
- valueExists := false
- for _, value := range values {
- if v.MatchString(value) {
- valueExists = true
- break
- }
- }
- if !valueExists {
- return false
- }
- }
- }
- return true
-}
-
-// methodNotAllowed replies to the request with an HTTP status code 405.
-func methodNotAllowed(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(http.StatusMethodNotAllowed)
-}
-
-// methodNotAllowedHandler returns a simple request handler
-// that replies to each request with a status code 405.
-func methodNotAllowedHandler() http.Handler { return http.HandlerFunc(methodNotAllowed) }
diff --git a/vendor/github.com/gorilla/mux/regexp.go b/vendor/github.com/gorilla/mux/regexp.go
deleted file mode 100644
index 2b57e56..0000000
--- a/vendor/github.com/gorilla/mux/regexp.go
+++ /dev/null
@@ -1,332 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package mux
-
-import (
- "bytes"
- "fmt"
- "net/http"
- "net/url"
- "regexp"
- "strconv"
- "strings"
-)
-
-type routeRegexpOptions struct {
- strictSlash bool
- useEncodedPath bool
-}
-
-type regexpType int
-
-const (
- regexpTypePath regexpType = 0
- regexpTypeHost regexpType = 1
- regexpTypePrefix regexpType = 2
- regexpTypeQuery regexpType = 3
-)
-
-// newRouteRegexp parses a route template and returns a routeRegexp,
-// used to match a host, a path or a query string.
-//
-// It will extract named variables, assemble a regexp to be matched, create
-// a "reverse" template to build URLs and compile regexps to validate variable
-// values used in URL building.
-//
-// Previously we accepted only Python-like identifiers for variable
-// names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that
-// name and pattern can't be empty, and names can't contain a colon.
-func newRouteRegexp(tpl string, typ regexpType, options routeRegexpOptions) (*routeRegexp, error) {
- // Check if it is well-formed.
- idxs, errBraces := braceIndices(tpl)
- if errBraces != nil {
- return nil, errBraces
- }
- // Backup the original.
- template := tpl
- // Now let's parse it.
- defaultPattern := "[^/]+"
- if typ == regexpTypeQuery {
- defaultPattern = ".*"
- } else if typ == regexpTypeHost {
- defaultPattern = "[^.]+"
- }
- // Only match strict slash if not matching
- if typ != regexpTypePath {
- options.strictSlash = false
- }
- // Set a flag for strictSlash.
- endSlash := false
- if options.strictSlash && strings.HasSuffix(tpl, "/") {
- tpl = tpl[:len(tpl)-1]
- endSlash = true
- }
- varsN := make([]string, len(idxs)/2)
- varsR := make([]*regexp.Regexp, len(idxs)/2)
- pattern := bytes.NewBufferString("")
- pattern.WriteByte('^')
- reverse := bytes.NewBufferString("")
- var end int
- var err error
- for i := 0; i < len(idxs); i += 2 {
- // Set all values we are interested in.
- raw := tpl[end:idxs[i]]
- end = idxs[i+1]
- parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2)
- name := parts[0]
- patt := defaultPattern
- if len(parts) == 2 {
- patt = parts[1]
- }
- // Name or pattern can't be empty.
- if name == "" || patt == "" {
- return nil, fmt.Errorf("mux: missing name or pattern in %q",
- tpl[idxs[i]:end])
- }
- // Build the regexp pattern.
- fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(i/2), patt)
-
- // Build the reverse template.
- fmt.Fprintf(reverse, "%s%%s", raw)
-
- // Append variable name and compiled pattern.
- varsN[i/2] = name
- varsR[i/2], err = regexp.Compile(fmt.Sprintf("^%s$", patt))
- if err != nil {
- return nil, err
- }
- }
- // Add the remaining.
- raw := tpl[end:]
- pattern.WriteString(regexp.QuoteMeta(raw))
- if options.strictSlash {
- pattern.WriteString("[/]?")
- }
- if typ == regexpTypeQuery {
- // Add the default pattern if the query value is empty
- if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" {
- pattern.WriteString(defaultPattern)
- }
- }
- if typ != regexpTypePrefix {
- pattern.WriteByte('$')
- }
- reverse.WriteString(raw)
- if endSlash {
- reverse.WriteByte('/')
- }
- // Compile full regexp.
- reg, errCompile := regexp.Compile(pattern.String())
- if errCompile != nil {
- return nil, errCompile
- }
-
- // Check for capturing groups which used to work in older versions
- if reg.NumSubexp() != len(idxs)/2 {
- panic(fmt.Sprintf("route %s contains capture groups in its regexp. ", template) +
- "Only non-capturing groups are accepted: e.g. (?:pattern) instead of (pattern)")
- }
-
- // Done!
- return &routeRegexp{
- template: template,
- regexpType: typ,
- options: options,
- regexp: reg,
- reverse: reverse.String(),
- varsN: varsN,
- varsR: varsR,
- }, nil
-}
-
-// routeRegexp stores a regexp to match a host or path and information to
-// collect and validate route variables.
-type routeRegexp struct {
- // The unmodified template.
- template string
- // The type of match
- regexpType regexpType
- // Options for matching
- options routeRegexpOptions
- // Expanded regexp.
- regexp *regexp.Regexp
- // Reverse template.
- reverse string
- // Variable names.
- varsN []string
- // Variable regexps (validators).
- varsR []*regexp.Regexp
-}
-
-// Match matches the regexp against the URL host or path.
-func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {
- if r.regexpType != regexpTypeHost {
- if r.regexpType == regexpTypeQuery {
- return r.matchQueryString(req)
- }
- path := req.URL.Path
- if r.options.useEncodedPath {
- path = req.URL.EscapedPath()
- }
- return r.regexp.MatchString(path)
- }
-
- return r.regexp.MatchString(getHost(req))
-}
-
-// url builds a URL part using the given values.
-func (r *routeRegexp) url(values map[string]string) (string, error) {
- urlValues := make([]interface{}, len(r.varsN))
- for k, v := range r.varsN {
- value, ok := values[v]
- if !ok {
- return "", fmt.Errorf("mux: missing route variable %q", v)
- }
- if r.regexpType == regexpTypeQuery {
- value = url.QueryEscape(value)
- }
- urlValues[k] = value
- }
- rv := fmt.Sprintf(r.reverse, urlValues...)
- if !r.regexp.MatchString(rv) {
- // The URL is checked against the full regexp, instead of checking
- // individual variables. This is faster but to provide a good error
- // message, we check individual regexps if the URL doesn't match.
- for k, v := range r.varsN {
- if !r.varsR[k].MatchString(values[v]) {
- return "", fmt.Errorf(
- "mux: variable %q doesn't match, expected %q", values[v],
- r.varsR[k].String())
- }
- }
- }
- return rv, nil
-}
-
-// getURLQuery returns a single query parameter from a request URL.
-// For a URL with foo=bar&baz=ding, we return only the relevant key
-// value pair for the routeRegexp.
-func (r *routeRegexp) getURLQuery(req *http.Request) string {
- if r.regexpType != regexpTypeQuery {
- return ""
- }
- templateKey := strings.SplitN(r.template, "=", 2)[0]
- for key, vals := range req.URL.Query() {
- if key == templateKey && len(vals) > 0 {
- return key + "=" + vals[0]
- }
- }
- return ""
-}
-
-func (r *routeRegexp) matchQueryString(req *http.Request) bool {
- return r.regexp.MatchString(r.getURLQuery(req))
-}
-
-// braceIndices returns the first level curly brace indices from a string.
-// It returns an error in case of unbalanced braces.
-func braceIndices(s string) ([]int, error) {
- var level, idx int
- var idxs []int
- for i := 0; i < len(s); i++ {
- switch s[i] {
- case '{':
- if level++; level == 1 {
- idx = i
- }
- case '}':
- if level--; level == 0 {
- idxs = append(idxs, idx, i+1)
- } else if level < 0 {
- return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
- }
- }
- }
- if level != 0 {
- return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
- }
- return idxs, nil
-}
-
-// varGroupName builds a capturing group name for the indexed variable.
-func varGroupName(idx int) string {
- return "v" + strconv.Itoa(idx)
-}
-
-// ----------------------------------------------------------------------------
-// routeRegexpGroup
-// ----------------------------------------------------------------------------
-
-// routeRegexpGroup groups the route matchers that carry variables.
-type routeRegexpGroup struct {
- host *routeRegexp
- path *routeRegexp
- queries []*routeRegexp
-}
-
-// setMatch extracts the variables from the URL once a route matches.
-func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) {
- // Store host variables.
- if v.host != nil {
- host := getHost(req)
- matches := v.host.regexp.FindStringSubmatchIndex(host)
- if len(matches) > 0 {
- extractVars(host, matches, v.host.varsN, m.Vars)
- }
- }
- path := req.URL.Path
- if r.useEncodedPath {
- path = req.URL.EscapedPath()
- }
- // Store path variables.
- if v.path != nil {
- matches := v.path.regexp.FindStringSubmatchIndex(path)
- if len(matches) > 0 {
- extractVars(path, matches, v.path.varsN, m.Vars)
- // Check if we should redirect.
- if v.path.options.strictSlash {
- p1 := strings.HasSuffix(path, "/")
- p2 := strings.HasSuffix(v.path.template, "/")
- if p1 != p2 {
- u, _ := url.Parse(req.URL.String())
- if p1 {
- u.Path = u.Path[:len(u.Path)-1]
- } else {
- u.Path += "/"
- }
- m.Handler = http.RedirectHandler(u.String(), 301)
- }
- }
- }
- }
- // Store query string variables.
- for _, q := range v.queries {
- queryURL := q.getURLQuery(req)
- matches := q.regexp.FindStringSubmatchIndex(queryURL)
- if len(matches) > 0 {
- extractVars(queryURL, matches, q.varsN, m.Vars)
- }
- }
-}
-
-// getHost tries its best to return the request host.
-func getHost(r *http.Request) string {
- if r.URL.IsAbs() {
- return r.URL.Host
- }
- host := r.Host
- // Slice off any port information.
- if i := strings.Index(host, ":"); i != -1 {
- host = host[:i]
- }
- return host
-
-}
-
-func extractVars(input string, matches []int, names []string, output map[string]string) {
- for i, name := range names {
- output[name] = input[matches[2*i+2]:matches[2*i+3]]
- }
-}
diff --git a/vendor/github.com/gorilla/mux/route.go b/vendor/github.com/gorilla/mux/route.go
deleted file mode 100644
index c8bb5c7..0000000
--- a/vendor/github.com/gorilla/mux/route.go
+++ /dev/null
@@ -1,763 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package mux
-
-import (
- "errors"
- "fmt"
- "net/http"
- "net/url"
- "regexp"
- "strings"
-)
-
-// Route stores information to match a request and build URLs.
-type Route struct {
- // Parent where the route was registered (a Router).
- parent parentRoute
- // Request handler for the route.
- handler http.Handler
- // List of matchers.
- matchers []matcher
- // Manager for the variables from host and path.
- regexp *routeRegexpGroup
- // If true, when the path pattern is "/path/", accessing "/path" will
- // redirect to the former and vice versa.
- strictSlash bool
- // If true, when the path pattern is "/path//to", accessing "/path//to"
- // will not redirect
- skipClean bool
- // If true, "/path/foo%2Fbar/to" will match the path "/path/{var}/to"
- useEncodedPath bool
- // The scheme used when building URLs.
- buildScheme string
- // If true, this route never matches: it is only used to build URLs.
- buildOnly bool
- // The name used to build URLs.
- name string
- // Error resulted from building a route.
- err error
-
- buildVarsFunc BuildVarsFunc
-}
-
-// SkipClean reports whether path cleaning is enabled for this route via
-// Router.SkipClean.
-func (r *Route) SkipClean() bool {
- return r.skipClean
-}
-
-// Match matches the route against the request.
-func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
- if r.buildOnly || r.err != nil {
- return false
- }
-
- var matchErr error
-
- // Match everything.
- for _, m := range r.matchers {
- if matched := m.Match(req, match); !matched {
- if _, ok := m.(methodMatcher); ok {
- matchErr = ErrMethodMismatch
- continue
- }
- matchErr = nil
- return false
- }
- }
-
- if matchErr != nil {
- match.MatchErr = matchErr
- return false
- }
-
- if match.MatchErr == ErrMethodMismatch {
- // We found a route which matches request method, clear MatchErr
- match.MatchErr = nil
- // Then override the mis-matched handler
- match.Handler = r.handler
- }
-
- // Yay, we have a match. Let's collect some info about it.
- if match.Route == nil {
- match.Route = r
- }
- if match.Handler == nil {
- match.Handler = r.handler
- }
- if match.Vars == nil {
- match.Vars = make(map[string]string)
- }
-
- // Set variables.
- if r.regexp != nil {
- r.regexp.setMatch(req, match, r)
- }
- return true
-}
-
-// ----------------------------------------------------------------------------
-// Route attributes
-// ----------------------------------------------------------------------------
-
-// GetError returns an error resulted from building the route, if any.
-func (r *Route) GetError() error {
- return r.err
-}
-
-// BuildOnly sets the route to never match: it is only used to build URLs.
-func (r *Route) BuildOnly() *Route {
- r.buildOnly = true
- return r
-}
-
-// Handler --------------------------------------------------------------------
-
-// Handler sets a handler for the route.
-func (r *Route) Handler(handler http.Handler) *Route {
- if r.err == nil {
- r.handler = handler
- }
- return r
-}
-
-// HandlerFunc sets a handler function for the route.
-func (r *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route {
- return r.Handler(http.HandlerFunc(f))
-}
-
-// GetHandler returns the handler for the route, if any.
-func (r *Route) GetHandler() http.Handler {
- return r.handler
-}
-
-// Name -----------------------------------------------------------------------
-
-// Name sets the name for the route, used to build URLs.
-// It is an error to call Name more than once on a route.
-func (r *Route) Name(name string) *Route {
- if r.name != "" {
- r.err = fmt.Errorf("mux: route already has name %q, can't set %q",
- r.name, name)
- }
- if r.err == nil {
- r.name = name
- r.getNamedRoutes()[name] = r
- }
- return r
-}
-
-// GetName returns the name for the route, if any.
-func (r *Route) GetName() string {
- return r.name
-}
-
-// ----------------------------------------------------------------------------
-// Matchers
-// ----------------------------------------------------------------------------
-
-// matcher types try to match a request.
-type matcher interface {
- Match(*http.Request, *RouteMatch) bool
-}
-
-// addMatcher adds a matcher to the route.
-func (r *Route) addMatcher(m matcher) *Route {
- if r.err == nil {
- r.matchers = append(r.matchers, m)
- }
- return r
-}
-
-// addRegexpMatcher adds a host or path matcher and builder to a route.
-func (r *Route) addRegexpMatcher(tpl string, typ regexpType) error {
- if r.err != nil {
- return r.err
- }
- r.regexp = r.getRegexpGroup()
- if typ == regexpTypePath || typ == regexpTypePrefix {
- if len(tpl) > 0 && tpl[0] != '/' {
- return fmt.Errorf("mux: path must start with a slash, got %q", tpl)
- }
- if r.regexp.path != nil {
- tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl
- }
- }
- rr, err := newRouteRegexp(tpl, typ, routeRegexpOptions{
- strictSlash: r.strictSlash,
- useEncodedPath: r.useEncodedPath,
- })
- if err != nil {
- return err
- }
- for _, q := range r.regexp.queries {
- if err = uniqueVars(rr.varsN, q.varsN); err != nil {
- return err
- }
- }
- if typ == regexpTypeHost {
- if r.regexp.path != nil {
- if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil {
- return err
- }
- }
- r.regexp.host = rr
- } else {
- if r.regexp.host != nil {
- if err = uniqueVars(rr.varsN, r.regexp.host.varsN); err != nil {
- return err
- }
- }
- if typ == regexpTypeQuery {
- r.regexp.queries = append(r.regexp.queries, rr)
- } else {
- r.regexp.path = rr
- }
- }
- r.addMatcher(rr)
- return nil
-}
-
-// Headers --------------------------------------------------------------------
-
-// headerMatcher matches the request against header values.
-type headerMatcher map[string]string
-
-func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool {
- return matchMapWithString(m, r.Header, true)
-}
-
-// Headers adds a matcher for request header values.
-// It accepts a sequence of key/value pairs to be matched. For example:
-//
-// r := mux.NewRouter()
-// r.Headers("Content-Type", "application/json",
-// "X-Requested-With", "XMLHttpRequest")
-//
-// The above route will only match if both request header values match.
-// If the value is an empty string, it will match any value if the key is set.
-func (r *Route) Headers(pairs ...string) *Route {
- if r.err == nil {
- var headers map[string]string
- headers, r.err = mapFromPairsToString(pairs...)
- return r.addMatcher(headerMatcher(headers))
- }
- return r
-}
-
-// headerRegexMatcher matches the request against the route given a regex for the header
-type headerRegexMatcher map[string]*regexp.Regexp
-
-func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool {
- return matchMapWithRegex(m, r.Header, true)
-}
-
-// HeadersRegexp accepts a sequence of key/value pairs, where the value has regex
-// support. For example:
-//
-// r := mux.NewRouter()
-// r.HeadersRegexp("Content-Type", "application/(text|json)",
-// "X-Requested-With", "XMLHttpRequest")
-//
-// The above route will only match if both the request header matches both regular expressions.
-// If the value is an empty string, it will match any value if the key is set.
-// Use the start and end of string anchors (^ and $) to match an exact value.
-func (r *Route) HeadersRegexp(pairs ...string) *Route {
- if r.err == nil {
- var headers map[string]*regexp.Regexp
- headers, r.err = mapFromPairsToRegex(pairs...)
- return r.addMatcher(headerRegexMatcher(headers))
- }
- return r
-}
-
-// Host -----------------------------------------------------------------------
-
-// Host adds a matcher for the URL host.
-// It accepts a template with zero or more URL variables enclosed by {}.
-// Variables can define an optional regexp pattern to be matched:
-//
-// - {name} matches anything until the next dot.
-//
-// - {name:pattern} matches the given regexp pattern.
-//
-// For example:
-//
-// r := mux.NewRouter()
-// r.Host("www.example.com")
-// r.Host("{subdomain}.domain.com")
-// r.Host("{subdomain:[a-z]+}.domain.com")
-//
-// Variable names must be unique in a given route. They can be retrieved
-// calling mux.Vars(request).
-func (r *Route) Host(tpl string) *Route {
- r.err = r.addRegexpMatcher(tpl, regexpTypeHost)
- return r
-}
-
-// MatcherFunc ----------------------------------------------------------------
-
-// MatcherFunc is the function signature used by custom matchers.
-type MatcherFunc func(*http.Request, *RouteMatch) bool
-
-// Match returns the match for a given request.
-func (m MatcherFunc) Match(r *http.Request, match *RouteMatch) bool {
- return m(r, match)
-}
-
-// MatcherFunc adds a custom function to be used as request matcher.
-func (r *Route) MatcherFunc(f MatcherFunc) *Route {
- return r.addMatcher(f)
-}
-
-// Methods --------------------------------------------------------------------
-
-// methodMatcher matches the request against HTTP methods.
-type methodMatcher []string
-
-func (m methodMatcher) Match(r *http.Request, match *RouteMatch) bool {
- return matchInArray(m, r.Method)
-}
-
-// Methods adds a matcher for HTTP methods.
-// It accepts a sequence of one or more methods to be matched, e.g.:
-// "GET", "POST", "PUT".
-func (r *Route) Methods(methods ...string) *Route {
- for k, v := range methods {
- methods[k] = strings.ToUpper(v)
- }
- return r.addMatcher(methodMatcher(methods))
-}
-
-// Path -----------------------------------------------------------------------
-
-// Path adds a matcher for the URL path.
-// It accepts a template with zero or more URL variables enclosed by {}. The
-// template must start with a "/".
-// Variables can define an optional regexp pattern to be matched:
-//
-// - {name} matches anything until the next slash.
-//
-// - {name:pattern} matches the given regexp pattern.
-//
-// For example:
-//
-// r := mux.NewRouter()
-// r.Path("/products/").Handler(ProductsHandler)
-// r.Path("/products/{key}").Handler(ProductsHandler)
-// r.Path("/articles/{category}/{id:[0-9]+}").
-// Handler(ArticleHandler)
-//
-// Variable names must be unique in a given route. They can be retrieved
-// calling mux.Vars(request).
-func (r *Route) Path(tpl string) *Route {
- r.err = r.addRegexpMatcher(tpl, regexpTypePath)
- return r
-}
-
-// PathPrefix -----------------------------------------------------------------
-
-// PathPrefix adds a matcher for the URL path prefix. This matches if the given
-// template is a prefix of the full URL path. See Route.Path() for details on
-// the tpl argument.
-//
-// Note that it does not treat slashes specially ("/foobar/" will be matched by
-// the prefix "/foo") so you may want to use a trailing slash here.
-//
-// Also note that the setting of Router.StrictSlash() has no effect on routes
-// with a PathPrefix matcher.
-func (r *Route) PathPrefix(tpl string) *Route {
- r.err = r.addRegexpMatcher(tpl, regexpTypePrefix)
- return r
-}
-
-// Query ----------------------------------------------------------------------
-
-// Queries adds a matcher for URL query values.
-// It accepts a sequence of key/value pairs. Values may define variables.
-// For example:
-//
-// r := mux.NewRouter()
-// r.Queries("foo", "bar", "id", "{id:[0-9]+}")
-//
-// The above route will only match if the URL contains the defined queries
-// values, e.g.: ?foo=bar&id=42.
-//
-// It the value is an empty string, it will match any value if the key is set.
-//
-// Variables can define an optional regexp pattern to be matched:
-//
-// - {name} matches anything until the next slash.
-//
-// - {name:pattern} matches the given regexp pattern.
-func (r *Route) Queries(pairs ...string) *Route {
- length := len(pairs)
- if length%2 != 0 {
- r.err = fmt.Errorf(
- "mux: number of parameters must be multiple of 2, got %v", pairs)
- return nil
- }
- for i := 0; i < length; i += 2 {
- if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], regexpTypeQuery); r.err != nil {
- return r
- }
- }
-
- return r
-}
-
-// Schemes --------------------------------------------------------------------
-
-// schemeMatcher matches the request against URL schemes.
-type schemeMatcher []string
-
-func (m schemeMatcher) Match(r *http.Request, match *RouteMatch) bool {
- return matchInArray(m, r.URL.Scheme)
-}
-
-// Schemes adds a matcher for URL schemes.
-// It accepts a sequence of schemes to be matched, e.g.: "http", "https".
-func (r *Route) Schemes(schemes ...string) *Route {
- for k, v := range schemes {
- schemes[k] = strings.ToLower(v)
- }
- if r.buildScheme == "" && len(schemes) > 0 {
- r.buildScheme = schemes[0]
- }
- return r.addMatcher(schemeMatcher(schemes))
-}
-
-// BuildVarsFunc --------------------------------------------------------------
-
-// BuildVarsFunc is the function signature used by custom build variable
-// functions (which can modify route variables before a route's URL is built).
-type BuildVarsFunc func(map[string]string) map[string]string
-
-// BuildVarsFunc adds a custom function to be used to modify build variables
-// before a route's URL is built.
-func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route {
- r.buildVarsFunc = f
- return r
-}
-
-// Subrouter ------------------------------------------------------------------
-
-// Subrouter creates a subrouter for the route.
-//
-// It will test the inner routes only if the parent route matched. For example:
-//
-// r := mux.NewRouter()
-// s := r.Host("www.example.com").Subrouter()
-// s.HandleFunc("/products/", ProductsHandler)
-// s.HandleFunc("/products/{key}", ProductHandler)
-// s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
-//
-// Here, the routes registered in the subrouter won't be tested if the host
-// doesn't match.
-func (r *Route) Subrouter() *Router {
- router := &Router{parent: r, strictSlash: r.strictSlash}
- r.addMatcher(router)
- return router
-}
-
-// ----------------------------------------------------------------------------
-// URL building
-// ----------------------------------------------------------------------------
-
-// URL builds a URL for the route.
-//
-// It accepts a sequence of key/value pairs for the route variables. For
-// example, given this route:
-//
-// r := mux.NewRouter()
-// r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
-// Name("article")
-//
-// ...a URL for it can be built using:
-//
-// url, err := r.Get("article").URL("category", "technology", "id", "42")
-//
-// ...which will return an url.URL with the following path:
-//
-// "/articles/technology/42"
-//
-// This also works for host variables:
-//
-// r := mux.NewRouter()
-// r.Host("{subdomain}.domain.com").
-// HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
-// Name("article")
-//
-// // url.String() will be "http://news.domain.com/articles/technology/42"
-// url, err := r.Get("article").URL("subdomain", "news",
-// "category", "technology",
-// "id", "42")
-//
-// All variables defined in the route are required, and their values must
-// conform to the corresponding patterns.
-func (r *Route) URL(pairs ...string) (*url.URL, error) {
- if r.err != nil {
- return nil, r.err
- }
- if r.regexp == nil {
- return nil, errors.New("mux: route doesn't have a host or path")
- }
- values, err := r.prepareVars(pairs...)
- if err != nil {
- return nil, err
- }
- var scheme, host, path string
- queries := make([]string, 0, len(r.regexp.queries))
- if r.regexp.host != nil {
- if host, err = r.regexp.host.url(values); err != nil {
- return nil, err
- }
- scheme = "http"
- if s := r.getBuildScheme(); s != "" {
- scheme = s
- }
- }
- if r.regexp.path != nil {
- if path, err = r.regexp.path.url(values); err != nil {
- return nil, err
- }
- }
- for _, q := range r.regexp.queries {
- var query string
- if query, err = q.url(values); err != nil {
- return nil, err
- }
- queries = append(queries, query)
- }
- return &url.URL{
- Scheme: scheme,
- Host: host,
- Path: path,
- RawQuery: strings.Join(queries, "&"),
- }, nil
-}
-
-// URLHost builds the host part of the URL for a route. See Route.URL().
-//
-// The route must have a host defined.
-func (r *Route) URLHost(pairs ...string) (*url.URL, error) {
- if r.err != nil {
- return nil, r.err
- }
- if r.regexp == nil || r.regexp.host == nil {
- return nil, errors.New("mux: route doesn't have a host")
- }
- values, err := r.prepareVars(pairs...)
- if err != nil {
- return nil, err
- }
- host, err := r.regexp.host.url(values)
- if err != nil {
- return nil, err
- }
- u := &url.URL{
- Scheme: "http",
- Host: host,
- }
- if s := r.getBuildScheme(); s != "" {
- u.Scheme = s
- }
- return u, nil
-}
-
-// URLPath builds the path part of the URL for a route. See Route.URL().
-//
-// The route must have a path defined.
-func (r *Route) URLPath(pairs ...string) (*url.URL, error) {
- if r.err != nil {
- return nil, r.err
- }
- if r.regexp == nil || r.regexp.path == nil {
- return nil, errors.New("mux: route doesn't have a path")
- }
- values, err := r.prepareVars(pairs...)
- if err != nil {
- return nil, err
- }
- path, err := r.regexp.path.url(values)
- if err != nil {
- return nil, err
- }
- return &url.URL{
- Path: path,
- }, nil
-}
-
-// GetPathTemplate returns the template used to build the
-// route match.
-// This is useful for building simple REST API documentation and for instrumentation
-// against third-party services.
-// An error will be returned if the route does not define a path.
-func (r *Route) GetPathTemplate() (string, error) {
- if r.err != nil {
- return "", r.err
- }
- if r.regexp == nil || r.regexp.path == nil {
- return "", errors.New("mux: route doesn't have a path")
- }
- return r.regexp.path.template, nil
-}
-
-// GetPathRegexp returns the expanded regular expression used to match route path.
-// This is useful for building simple REST API documentation and for instrumentation
-// against third-party services.
-// An error will be returned if the route does not define a path.
-func (r *Route) GetPathRegexp() (string, error) {
- if r.err != nil {
- return "", r.err
- }
- if r.regexp == nil || r.regexp.path == nil {
- return "", errors.New("mux: route does not have a path")
- }
- return r.regexp.path.regexp.String(), nil
-}
-
-// GetQueriesRegexp returns the expanded regular expressions used to match the
-// route queries.
-// This is useful for building simple REST API documentation and for instrumentation
-// against third-party services.
-// An error will be returned if the route does not have queries.
-func (r *Route) GetQueriesRegexp() ([]string, error) {
- if r.err != nil {
- return nil, r.err
- }
- if r.regexp == nil || r.regexp.queries == nil {
- return nil, errors.New("mux: route doesn't have queries")
- }
- var queries []string
- for _, query := range r.regexp.queries {
- queries = append(queries, query.regexp.String())
- }
- return queries, nil
-}
-
-// GetQueriesTemplates returns the templates used to build the
-// query matching.
-// This is useful for building simple REST API documentation and for instrumentation
-// against third-party services.
-// An error will be returned if the route does not define queries.
-func (r *Route) GetQueriesTemplates() ([]string, error) {
- if r.err != nil {
- return nil, r.err
- }
- if r.regexp == nil || r.regexp.queries == nil {
- return nil, errors.New("mux: route doesn't have queries")
- }
- var queries []string
- for _, query := range r.regexp.queries {
- queries = append(queries, query.template)
- }
- return queries, nil
-}
-
-// GetMethods returns the methods the route matches against
-// This is useful for building simple REST API documentation and for instrumentation
-// against third-party services.
-// An error will be returned if route does not have methods.
-func (r *Route) GetMethods() ([]string, error) {
- if r.err != nil {
- return nil, r.err
- }
- for _, m := range r.matchers {
- if methods, ok := m.(methodMatcher); ok {
- return []string(methods), nil
- }
- }
- return nil, errors.New("mux: route doesn't have methods")
-}
-
-// GetHostTemplate returns the template used to build the
-// route match.
-// This is useful for building simple REST API documentation and for instrumentation
-// against third-party services.
-// An error will be returned if the route does not define a host.
-func (r *Route) GetHostTemplate() (string, error) {
- if r.err != nil {
- return "", r.err
- }
- if r.regexp == nil || r.regexp.host == nil {
- return "", errors.New("mux: route doesn't have a host")
- }
- return r.regexp.host.template, nil
-}
-
-// prepareVars converts the route variable pairs into a map. If the route has a
-// BuildVarsFunc, it is invoked.
-func (r *Route) prepareVars(pairs ...string) (map[string]string, error) {
- m, err := mapFromPairsToString(pairs...)
- if err != nil {
- return nil, err
- }
- return r.buildVars(m), nil
-}
-
-func (r *Route) buildVars(m map[string]string) map[string]string {
- if r.parent != nil {
- m = r.parent.buildVars(m)
- }
- if r.buildVarsFunc != nil {
- m = r.buildVarsFunc(m)
- }
- return m
-}
-
-// ----------------------------------------------------------------------------
-// parentRoute
-// ----------------------------------------------------------------------------
-
-// parentRoute allows routes to know about parent host and path definitions.
-type parentRoute interface {
- getBuildScheme() string
- getNamedRoutes() map[string]*Route
- getRegexpGroup() *routeRegexpGroup
- buildVars(map[string]string) map[string]string
-}
-
-func (r *Route) getBuildScheme() string {
- if r.buildScheme != "" {
- return r.buildScheme
- }
- if r.parent != nil {
- return r.parent.getBuildScheme()
- }
- return ""
-}
-
-// getNamedRoutes returns the map where named routes are registered.
-func (r *Route) getNamedRoutes() map[string]*Route {
- if r.parent == nil {
- // During tests router is not always set.
- r.parent = NewRouter()
- }
- return r.parent.getNamedRoutes()
-}
-
-// getRegexpGroup returns regexp definitions from this route.
-func (r *Route) getRegexpGroup() *routeRegexpGroup {
- if r.regexp == nil {
- if r.parent == nil {
- // During tests router is not always set.
- r.parent = NewRouter()
- }
- regexp := r.parent.getRegexpGroup()
- if regexp == nil {
- r.regexp = new(routeRegexpGroup)
- } else {
- // Copy.
- r.regexp = &routeRegexpGroup{
- host: regexp.host,
- path: regexp.path,
- queries: regexp.queries,
- }
- }
- }
- return r.regexp
-}
diff --git a/vendor/github.com/gorilla/mux/test_helpers.go b/vendor/github.com/gorilla/mux/test_helpers.go
deleted file mode 100644
index 32ecffd..0000000
--- a/vendor/github.com/gorilla/mux/test_helpers.go
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package mux
-
-import "net/http"
-
-// SetURLVars sets the URL variables for the given request, to be accessed via
-// mux.Vars for testing route behaviour. Arguments are not modified, a shallow
-// copy is returned.
-//
-// This API should only be used for testing purposes; it provides a way to
-// inject variables into the request context. Alternatively, URL variables
-// can be set by making a route that captures the required variables,
-// starting a server and sending the request to that server.
-func SetURLVars(r *http.Request, val map[string]string) *http.Request {
- return setVars(r, val)
-}
diff --git a/vendor/github.com/gorilla/securecookie/AUTHORS b/vendor/github.com/gorilla/securecookie/AUTHORS
deleted file mode 100644
index a4d447d..0000000
--- a/vendor/github.com/gorilla/securecookie/AUTHORS
+++ /dev/null
@@ -1,19 +0,0 @@
-# This is the official list of gorilla/securecookie authors for copyright purposes.
-# Please keep the list sorted.
-
-0x434D53 <christoph.seufert@gmail.com>
-Abdülhamit Yilmaz <mr.yilmaz@gmx.de>
-Annonomus-Penguin <Annonomus-Penguin@users.noreply.github.com>
-Craig Peterson <cpeterson@stackoverflow.com>
-Cyril David <cyx@cyx.is>
-Dmitry Chestnykh <dmitry@codingrobots.com>
-Dominik Honnef <dominikh@fork-bomb.org>
-Google LLC (https://opensource.google.com/)
-John Downey <john@jtdowney.com>
-Kamil Kisiel <kamil@kamilkisiel.net>
-Keunwoo Lee <keunwoo@flux.io>
-Mahmud Ridwan <m@hjr265.me>
-Matt Silverlock <matt@eatsleeprepeat.net>
-rodrigo moraes <rodrigo.moraes@gmail.com>
-s7v7nislands <s7v7nislands@gmail.com>
-Wesley Bitter <github@wessie.info>
diff --git a/vendor/github.com/gorilla/securecookie/LICENSE b/vendor/github.com/gorilla/securecookie/LICENSE
deleted file mode 100644
index 6903df6..0000000
--- a/vendor/github.com/gorilla/securecookie/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2012-2018 The Gorilla Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/gorilla/securecookie/README.md b/vendor/github.com/gorilla/securecookie/README.md
deleted file mode 100644
index aa7bd1a..0000000
--- a/vendor/github.com/gorilla/securecookie/README.md
+++ /dev/null
@@ -1,80 +0,0 @@
-securecookie
-============
-[![GoDoc](https://godoc.org/github.com/gorilla/securecookie?status.svg)](https://godoc.org/github.com/gorilla/securecookie) [![Build Status](https://travis-ci.org/gorilla/securecookie.png?branch=master)](https://travis-ci.org/gorilla/securecookie)
-[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/securecookie/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/securecookie?badge)
-
-
-securecookie encodes and decodes authenticated and optionally encrypted
-cookie values.
-
-Secure cookies can't be forged, because their values are validated using HMAC.
-When encrypted, the content is also inaccessible to malicious eyes. It is still
-recommended that sensitive data not be stored in cookies, and that HTTPS be used
-to prevent cookie [replay attacks](https://en.wikipedia.org/wiki/Replay_attack).
-
-## Examples
-
-To use it, first create a new SecureCookie instance:
-
-```go
-// Hash keys should be at least 32 bytes long
-var hashKey = []byte("very-secret")
-// Block keys should be 16 bytes (AES-128) or 32 bytes (AES-256) long.
-// Shorter keys may weaken the encryption used.
-var blockKey = []byte("a-lot-secret")
-var s = securecookie.New(hashKey, blockKey)
-```
-
-The hashKey is required, used to authenticate the cookie value using HMAC.
-It is recommended to use a key with 32 or 64 bytes.
-
-The blockKey is optional, used to encrypt the cookie value -- set it to nil
-to not use encryption. If set, the length must correspond to the block size
-of the encryption algorithm. For AES, used by default, valid lengths are
-16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
-
-Strong keys can be created using the convenience function GenerateRandomKey().
-
-Once a SecureCookie instance is set, use it to encode a cookie value:
-
-```go
-func SetCookieHandler(w http.ResponseWriter, r *http.Request) {
- value := map[string]string{
- "foo": "bar",
- }
- if encoded, err := s.Encode("cookie-name", value); err == nil {
- cookie := &http.Cookie{
- Name: "cookie-name",
- Value: encoded,
- Path: "/",
- Secure: true,
- HttpOnly: true,
- }
- http.SetCookie(w, cookie)
- }
-}
-```
-
-Later, use the same SecureCookie instance to decode and validate a cookie
-value:
-
-```go
-func ReadCookieHandler(w http.ResponseWriter, r *http.Request) {
- if cookie, err := r.Cookie("cookie-name"); err == nil {
- value := make(map[string]string)
- if err = s2.Decode("cookie-name", cookie.Value, &value); err == nil {
- fmt.Fprintf(w, "The value of foo is %q", value["foo"])
- }
- }
-}
-```
-
-We stored a map[string]string, but secure cookies can hold any value that
-can be encoded using `encoding/gob`. To store custom types, they must be
-registered first using gob.Register(). For basic types this is not needed;
-it works out of the box. An optional JSON encoder that uses `encoding/json` is
-available for types compatible with JSON.
-
-## License
-
-BSD licensed. See the LICENSE file for details.
diff --git a/vendor/github.com/gorilla/securecookie/doc.go b/vendor/github.com/gorilla/securecookie/doc.go
deleted file mode 100644
index ae89408..0000000
--- a/vendor/github.com/gorilla/securecookie/doc.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-/*
-Package securecookie encodes and decodes authenticated and optionally
-encrypted cookie values.
-
-Secure cookies can't be forged, because their values are validated using HMAC.
-When encrypted, the content is also inaccessible to malicious eyes.
-
-To use it, first create a new SecureCookie instance:
-
- var hashKey = []byte("very-secret")
- var blockKey = []byte("a-lot-secret")
- var s = securecookie.New(hashKey, blockKey)
-
-The hashKey is required, used to authenticate the cookie value using HMAC.
-It is recommended to use a key with 32 or 64 bytes.
-
-The blockKey is optional, used to encrypt the cookie value -- set it to nil
-to not use encryption. If set, the length must correspond to the block size
-of the encryption algorithm. For AES, used by default, valid lengths are
-16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
-
-Strong keys can be created using the convenience function GenerateRandomKey().
-
-Once a SecureCookie instance is set, use it to encode a cookie value:
-
- func SetCookieHandler(w http.ResponseWriter, r *http.Request) {
- value := map[string]string{
- "foo": "bar",
- }
- if encoded, err := s.Encode("cookie-name", value); err == nil {
- cookie := &http.Cookie{
- Name: "cookie-name",
- Value: encoded,
- Path: "/",
- }
- http.SetCookie(w, cookie)
- }
- }
-
-Later, use the same SecureCookie instance to decode and validate a cookie
-value:
-
- func ReadCookieHandler(w http.ResponseWriter, r *http.Request) {
- if cookie, err := r.Cookie("cookie-name"); err == nil {
- value := make(map[string]string)
- if err = s2.Decode("cookie-name", cookie.Value, &value); err == nil {
- fmt.Fprintf(w, "The value of foo is %q", value["foo"])
- }
- }
- }
-
-We stored a map[string]string, but secure cookies can hold any value that
-can be encoded using encoding/gob. To store custom types, they must be
-registered first using gob.Register(). For basic types this is not needed;
-it works out of the box.
-*/
-package securecookie
diff --git a/vendor/github.com/gorilla/securecookie/fuzz.go b/vendor/github.com/gorilla/securecookie/fuzz.go
deleted file mode 100644
index e4d0534..0000000
--- a/vendor/github.com/gorilla/securecookie/fuzz.go
+++ /dev/null
@@ -1,25 +0,0 @@
-// +build gofuzz
-
-package securecookie
-
-var hashKey = []byte("very-secret12345")
-var blockKey = []byte("a-lot-secret1234")
-var s = New(hashKey, blockKey)
-
-type Cookie struct {
- B bool
- I int
- S string
-}
-
-func Fuzz(data []byte) int {
- datas := string(data)
- var c Cookie
- if err := s.Decode("fuzz", datas, &c); err != nil {
- return 0
- }
- if _, err := s.Encode("fuzz", c); err != nil {
- panic(err)
- }
- return 1
-}
diff --git a/vendor/github.com/gorilla/securecookie/securecookie.go b/vendor/github.com/gorilla/securecookie/securecookie.go
deleted file mode 100644
index 61af390..0000000
--- a/vendor/github.com/gorilla/securecookie/securecookie.go
+++ /dev/null
@@ -1,646 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package securecookie
-
-import (
- "bytes"
- "crypto/aes"
- "crypto/cipher"
- "crypto/hmac"
- "crypto/rand"
- "crypto/sha256"
- "crypto/subtle"
- "encoding/base64"
- "encoding/gob"
- "encoding/json"
- "fmt"
- "hash"
- "io"
- "strconv"
- "strings"
- "time"
-)
-
-// Error is the interface of all errors returned by functions in this library.
-type Error interface {
- error
-
- // IsUsage returns true for errors indicating the client code probably
- // uses this library incorrectly. For example, the client may have
- // failed to provide a valid hash key, or may have failed to configure
- // the Serializer adequately for encoding value.
- IsUsage() bool
-
- // IsDecode returns true for errors indicating that a cookie could not
- // be decoded and validated. Since cookies are usually untrusted
- // user-provided input, errors of this type should be expected.
- // Usually, the proper action is simply to reject the request.
- IsDecode() bool
-
- // IsInternal returns true for unexpected errors occurring in the
- // securecookie implementation.
- IsInternal() bool
-
- // Cause, if it returns a non-nil value, indicates that this error was
- // propagated from some underlying library. If this method returns nil,
- // this error was raised directly by this library.
- //
- // Cause is provided principally for debugging/logging purposes; it is
- // rare that application logic should perform meaningfully different
- // logic based on Cause. See, for example, the caveats described on
- // (MultiError).Cause().
- Cause() error
-}
-
-// errorType is a bitmask giving the error type(s) of an cookieError value.
-type errorType int
-
-const (
- usageError = errorType(1 << iota)
- decodeError
- internalError
-)
-
-type cookieError struct {
- typ errorType
- msg string
- cause error
-}
-
-func (e cookieError) IsUsage() bool { return (e.typ & usageError) != 0 }
-func (e cookieError) IsDecode() bool { return (e.typ & decodeError) != 0 }
-func (e cookieError) IsInternal() bool { return (e.typ & internalError) != 0 }
-
-func (e cookieError) Cause() error { return e.cause }
-
-func (e cookieError) Error() string {
- parts := []string{"securecookie: "}
- if e.msg == "" {
- parts = append(parts, "error")
- } else {
- parts = append(parts, e.msg)
- }
- if c := e.Cause(); c != nil {
- parts = append(parts, " - caused by: ", c.Error())
- }
- return strings.Join(parts, "")
-}
-
-var (
- errGeneratingIV = cookieError{typ: internalError, msg: "failed to generate random iv"}
-
- errNoCodecs = cookieError{typ: usageError, msg: "no codecs provided"}
- errHashKeyNotSet = cookieError{typ: usageError, msg: "hash key is not set"}
- errBlockKeyNotSet = cookieError{typ: usageError, msg: "block key is not set"}
- errEncodedValueTooLong = cookieError{typ: usageError, msg: "the value is too long"}
-
- errValueToDecodeTooLong = cookieError{typ: decodeError, msg: "the value is too long"}
- errTimestampInvalid = cookieError{typ: decodeError, msg: "invalid timestamp"}
- errTimestampTooNew = cookieError{typ: decodeError, msg: "timestamp is too new"}
- errTimestampExpired = cookieError{typ: decodeError, msg: "expired timestamp"}
- errDecryptionFailed = cookieError{typ: decodeError, msg: "the value could not be decrypted"}
- errValueNotByte = cookieError{typ: decodeError, msg: "value not a []byte."}
- errValueNotBytePtr = cookieError{typ: decodeError, msg: "value not a pointer to []byte."}
-
- // ErrMacInvalid indicates that cookie decoding failed because the HMAC
- // could not be extracted and verified. Direct use of this error
- // variable is deprecated; it is public only for legacy compatibility,
- // and may be privatized in the future, as it is rarely useful to
- // distinguish between this error and other Error implementations.
- ErrMacInvalid = cookieError{typ: decodeError, msg: "the value is not valid"}
-)
-
-// Codec defines an interface to encode and decode cookie values.
-type Codec interface {
- Encode(name string, value interface{}) (string, error)
- Decode(name, value string, dst interface{}) error
-}
-
-// New returns a new SecureCookie.
-//
-// hashKey is required, used to authenticate values using HMAC. Create it using
-// GenerateRandomKey(). It is recommended to use a key with 32 or 64 bytes.
-//
-// blockKey is optional, used to encrypt values. Create it using
-// GenerateRandomKey(). The key length must correspond to the block size
-// of the encryption algorithm. For AES, used by default, valid lengths are
-// 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
-// The default encoder used for cookie serialization is encoding/gob.
-//
-// Note that keys created using GenerateRandomKey() are not automatically
-// persisted. New keys will be created when the application is restarted, and
-// previously issued cookies will not be able to be decoded.
-func New(hashKey, blockKey []byte) *SecureCookie {
- s := &SecureCookie{
- hashKey: hashKey,
- blockKey: blockKey,
- hashFunc: sha256.New,
- maxAge: 86400 * 30,
- maxLength: 4096,
- sz: GobEncoder{},
- }
- if len(hashKey) == 0 {
- s.err = errHashKeyNotSet
- }
- if blockKey != nil {
- s.BlockFunc(aes.NewCipher)
- }
- return s
-}
-
-// SecureCookie encodes and decodes authenticated and optionally encrypted
-// cookie values.
-type SecureCookie struct {
- hashKey []byte
- hashFunc func() hash.Hash
- blockKey []byte
- block cipher.Block
- maxLength int
- maxAge int64
- minAge int64
- err error
- sz Serializer
- // For testing purposes, the function that returns the current timestamp.
- // If not set, it will use time.Now().UTC().Unix().
- timeFunc func() int64
-}
-
-// Serializer provides an interface for providing custom serializers for cookie
-// values.
-type Serializer interface {
- Serialize(src interface{}) ([]byte, error)
- Deserialize(src []byte, dst interface{}) error
-}
-
-// GobEncoder encodes cookie values using encoding/gob. This is the simplest
-// encoder and can handle complex types via gob.Register.
-type GobEncoder struct{}
-
-// JSONEncoder encodes cookie values using encoding/json. Users who wish to
-// encode complex types need to satisfy the json.Marshaller and
-// json.Unmarshaller interfaces.
-type JSONEncoder struct{}
-
-// NopEncoder does not encode cookie values, and instead simply accepts a []byte
-// (as an interface{}) and returns a []byte. This is particularly useful when
-// you encoding an object upstream and do not wish to re-encode it.
-type NopEncoder struct{}
-
-// MaxLength restricts the maximum length, in bytes, for the cookie value.
-//
-// Default is 4096, which is the maximum value accepted by Internet Explorer.
-func (s *SecureCookie) MaxLength(value int) *SecureCookie {
- s.maxLength = value
- return s
-}
-
-// MaxAge restricts the maximum age, in seconds, for the cookie value.
-//
-// Default is 86400 * 30. Set it to 0 for no restriction.
-func (s *SecureCookie) MaxAge(value int) *SecureCookie {
- s.maxAge = int64(value)
- return s
-}
-
-// MinAge restricts the minimum age, in seconds, for the cookie value.
-//
-// Default is 0 (no restriction).
-func (s *SecureCookie) MinAge(value int) *SecureCookie {
- s.minAge = int64(value)
- return s
-}
-
-// HashFunc sets the hash function used to create HMAC.
-//
-// Default is crypto/sha256.New.
-func (s *SecureCookie) HashFunc(f func() hash.Hash) *SecureCookie {
- s.hashFunc = f
- return s
-}
-
-// BlockFunc sets the encryption function used to create a cipher.Block.
-//
-// Default is crypto/aes.New.
-func (s *SecureCookie) BlockFunc(f func([]byte) (cipher.Block, error)) *SecureCookie {
- if s.blockKey == nil {
- s.err = errBlockKeyNotSet
- } else if block, err := f(s.blockKey); err == nil {
- s.block = block
- } else {
- s.err = cookieError{cause: err, typ: usageError}
- }
- return s
-}
-
-// Encoding sets the encoding/serialization method for cookies.
-//
-// Default is encoding/gob. To encode special structures using encoding/gob,
-// they must be registered first using gob.Register().
-func (s *SecureCookie) SetSerializer(sz Serializer) *SecureCookie {
- s.sz = sz
-
- return s
-}
-
-// Encode encodes a cookie value.
-//
-// It serializes, optionally encrypts, signs with a message authentication code,
-// and finally encodes the value.
-//
-// The name argument is the cookie name. It is stored with the encoded value.
-// The value argument is the value to be encoded. It can be any value that can
-// be encoded using the currently selected serializer; see SetSerializer().
-//
-// It is the client's responsibility to ensure that value, when encoded using
-// the current serialization/encryption settings on s and then base64-encoded,
-// is shorter than the maximum permissible length.
-func (s *SecureCookie) Encode(name string, value interface{}) (string, error) {
- if s.err != nil {
- return "", s.err
- }
- if s.hashKey == nil {
- s.err = errHashKeyNotSet
- return "", s.err
- }
- var err error
- var b []byte
- // 1. Serialize.
- if b, err = s.sz.Serialize(value); err != nil {
- return "", cookieError{cause: err, typ: usageError}
- }
- // 2. Encrypt (optional).
- if s.block != nil {
- if b, err = encrypt(s.block, b); err != nil {
- return "", cookieError{cause: err, typ: usageError}
- }
- }
- b = encode(b)
- // 3. Create MAC for "name|date|value". Extra pipe to be used later.
- b = []byte(fmt.Sprintf("%s|%d|%s|", name, s.timestamp(), b))
- mac := createMac(hmac.New(s.hashFunc, s.hashKey), b[:len(b)-1])
- // Append mac, remove name.
- b = append(b, mac...)[len(name)+1:]
- // 4. Encode to base64.
- b = encode(b)
- // 5. Check length.
- if s.maxLength != 0 && len(b) > s.maxLength {
- return "", errEncodedValueTooLong
- }
- // Done.
- return string(b), nil
-}
-
-// Decode decodes a cookie value.
-//
-// It decodes, verifies a message authentication code, optionally decrypts and
-// finally deserializes the value.
-//
-// The name argument is the cookie name. It must be the same name used when
-// it was stored. The value argument is the encoded cookie value. The dst
-// argument is where the cookie will be decoded. It must be a pointer.
-func (s *SecureCookie) Decode(name, value string, dst interface{}) error {
- if s.err != nil {
- return s.err
- }
- if s.hashKey == nil {
- s.err = errHashKeyNotSet
- return s.err
- }
- // 1. Check length.
- if s.maxLength != 0 && len(value) > s.maxLength {
- return errValueToDecodeTooLong
- }
- // 2. Decode from base64.
- b, err := decode([]byte(value))
- if err != nil {
- return err
- }
- // 3. Verify MAC. Value is "date|value|mac".
- parts := bytes.SplitN(b, []byte("|"), 3)
- if len(parts) != 3 {
- return ErrMacInvalid
- }
- h := hmac.New(s.hashFunc, s.hashKey)
- b = append([]byte(name+"|"), b[:len(b)-len(parts[2])-1]...)
- if err = verifyMac(h, b, parts[2]); err != nil {
- return err
- }
- // 4. Verify date ranges.
- var t1 int64
- if t1, err = strconv.ParseInt(string(parts[0]), 10, 64); err != nil {
- return errTimestampInvalid
- }
- t2 := s.timestamp()
- if s.minAge != 0 && t1 > t2-s.minAge {
- return errTimestampTooNew
- }
- if s.maxAge != 0 && t1 < t2-s.maxAge {
- return errTimestampExpired
- }
- // 5. Decrypt (optional).
- b, err = decode(parts[1])
- if err != nil {
- return err
- }
- if s.block != nil {
- if b, err = decrypt(s.block, b); err != nil {
- return err
- }
- }
- // 6. Deserialize.
- if err = s.sz.Deserialize(b, dst); err != nil {
- return cookieError{cause: err, typ: decodeError}
- }
- // Done.
- return nil
-}
-
-// timestamp returns the current timestamp, in seconds.
-//
-// For testing purposes, the function that generates the timestamp can be
-// overridden. If not set, it will return time.Now().UTC().Unix().
-func (s *SecureCookie) timestamp() int64 {
- if s.timeFunc == nil {
- return time.Now().UTC().Unix()
- }
- return s.timeFunc()
-}
-
-// Authentication -------------------------------------------------------------
-
-// createMac creates a message authentication code (MAC).
-func createMac(h hash.Hash, value []byte) []byte {
- h.Write(value)
- return h.Sum(nil)
-}
-
-// verifyMac verifies that a message authentication code (MAC) is valid.
-func verifyMac(h hash.Hash, value []byte, mac []byte) error {
- mac2 := createMac(h, value)
- // Check that both MACs are of equal length, as subtle.ConstantTimeCompare
- // does not do this prior to Go 1.4.
- if len(mac) == len(mac2) && subtle.ConstantTimeCompare(mac, mac2) == 1 {
- return nil
- }
- return ErrMacInvalid
-}
-
-// Encryption -----------------------------------------------------------------
-
-// encrypt encrypts a value using the given block in counter mode.
-//
-// A random initialization vector (http://goo.gl/zF67k) with the length of the
-// block size is prepended to the resulting ciphertext.
-func encrypt(block cipher.Block, value []byte) ([]byte, error) {
- iv := GenerateRandomKey(block.BlockSize())
- if iv == nil {
- return nil, errGeneratingIV
- }
- // Encrypt it.
- stream := cipher.NewCTR(block, iv)
- stream.XORKeyStream(value, value)
- // Return iv + ciphertext.
- return append(iv, value...), nil
-}
-
-// decrypt decrypts a value using the given block in counter mode.
-//
-// The value to be decrypted must be prepended by a initialization vector
-// (http://goo.gl/zF67k) with the length of the block size.
-func decrypt(block cipher.Block, value []byte) ([]byte, error) {
- size := block.BlockSize()
- if len(value) > size {
- // Extract iv.
- iv := value[:size]
- // Extract ciphertext.
- value = value[size:]
- // Decrypt it.
- stream := cipher.NewCTR(block, iv)
- stream.XORKeyStream(value, value)
- return value, nil
- }
- return nil, errDecryptionFailed
-}
-
-// Serialization --------------------------------------------------------------
-
-// Serialize encodes a value using gob.
-func (e GobEncoder) Serialize(src interface{}) ([]byte, error) {
- buf := new(bytes.Buffer)
- enc := gob.NewEncoder(buf)
- if err := enc.Encode(src); err != nil {
- return nil, cookieError{cause: err, typ: usageError}
- }
- return buf.Bytes(), nil
-}
-
-// Deserialize decodes a value using gob.
-func (e GobEncoder) Deserialize(src []byte, dst interface{}) error {
- dec := gob.NewDecoder(bytes.NewBuffer(src))
- if err := dec.Decode(dst); err != nil {
- return cookieError{cause: err, typ: decodeError}
- }
- return nil
-}
-
-// Serialize encodes a value using encoding/json.
-func (e JSONEncoder) Serialize(src interface{}) ([]byte, error) {
- buf := new(bytes.Buffer)
- enc := json.NewEncoder(buf)
- if err := enc.Encode(src); err != nil {
- return nil, cookieError{cause: err, typ: usageError}
- }
- return buf.Bytes(), nil
-}
-
-// Deserialize decodes a value using encoding/json.
-func (e JSONEncoder) Deserialize(src []byte, dst interface{}) error {
- dec := json.NewDecoder(bytes.NewReader(src))
- if err := dec.Decode(dst); err != nil {
- return cookieError{cause: err, typ: decodeError}
- }
- return nil
-}
-
-// Serialize passes a []byte through as-is.
-func (e NopEncoder) Serialize(src interface{}) ([]byte, error) {
- if b, ok := src.([]byte); ok {
- return b, nil
- }
-
- return nil, errValueNotByte
-}
-
-// Deserialize passes a []byte through as-is.
-func (e NopEncoder) Deserialize(src []byte, dst interface{}) error {
- if dat, ok := dst.(*[]byte); ok {
- *dat = src
- return nil
- }
- return errValueNotBytePtr
-}
-
-// Encoding -------------------------------------------------------------------
-
-// encode encodes a value using base64.
-func encode(value []byte) []byte {
- encoded := make([]byte, base64.URLEncoding.EncodedLen(len(value)))
- base64.URLEncoding.Encode(encoded, value)
- return encoded
-}
-
-// decode decodes a cookie using base64.
-func decode(value []byte) ([]byte, error) {
- decoded := make([]byte, base64.URLEncoding.DecodedLen(len(value)))
- b, err := base64.URLEncoding.Decode(decoded, value)
- if err != nil {
- return nil, cookieError{cause: err, typ: decodeError, msg: "base64 decode failed"}
- }
- return decoded[:b], nil
-}
-
-// Helpers --------------------------------------------------------------------
-
-// GenerateRandomKey creates a random key with the given length in bytes.
-// On failure, returns nil.
-//
-// Callers should explicitly check for the possibility of a nil return, treat
-// it as a failure of the system random number generator, and not continue.
-func GenerateRandomKey(length int) []byte {
- k := make([]byte, length)
- if _, err := io.ReadFull(rand.Reader, k); err != nil {
- return nil
- }
- return k
-}
-
-// CodecsFromPairs returns a slice of SecureCookie instances.
-//
-// It is a convenience function to create a list of codecs for key rotation. Note
-// that the generated Codecs will have the default options applied: callers
-// should iterate over each Codec and type-assert the underlying *SecureCookie to
-// change these.
-//
-// Example:
-//
-// codecs := securecookie.CodecsFromPairs(
-// []byte("new-hash-key"),
-// []byte("new-block-key"),
-// []byte("old-hash-key"),
-// []byte("old-block-key"),
-// )
-//
-// // Modify each instance.
-// for _, s := range codecs {
-// if cookie, ok := s.(*securecookie.SecureCookie); ok {
-// cookie.MaxAge(86400 * 7)
-// cookie.SetSerializer(securecookie.JSONEncoder{})
-// cookie.HashFunc(sha512.New512_256)
-// }
-// }
-//
-func CodecsFromPairs(keyPairs ...[]byte) []Codec {
- codecs := make([]Codec, len(keyPairs)/2+len(keyPairs)%2)
- for i := 0; i < len(keyPairs); i += 2 {
- var blockKey []byte
- if i+1 < len(keyPairs) {
- blockKey = keyPairs[i+1]
- }
- codecs[i/2] = New(keyPairs[i], blockKey)
- }
- return codecs
-}
-
-// EncodeMulti encodes a cookie value using a group of codecs.
-//
-// The codecs are tried in order. Multiple codecs are accepted to allow
-// key rotation.
-//
-// On error, may return a MultiError.
-func EncodeMulti(name string, value interface{}, codecs ...Codec) (string, error) {
- if len(codecs) == 0 {
- return "", errNoCodecs
- }
-
- var errors MultiError
- for _, codec := range codecs {
- encoded, err := codec.Encode(name, value)
- if err == nil {
- return encoded, nil
- }
- errors = append(errors, err)
- }
- return "", errors
-}
-
-// DecodeMulti decodes a cookie value using a group of codecs.
-//
-// The codecs are tried in order. Multiple codecs are accepted to allow
-// key rotation.
-//
-// On error, may return a MultiError.
-func DecodeMulti(name string, value string, dst interface{}, codecs ...Codec) error {
- if len(codecs) == 0 {
- return errNoCodecs
- }
-
- var errors MultiError
- for _, codec := range codecs {
- err := codec.Decode(name, value, dst)
- if err == nil {
- return nil
- }
- errors = append(errors, err)
- }
- return errors
-}
-
-// MultiError groups multiple errors.
-type MultiError []error
-
-func (m MultiError) IsUsage() bool { return m.any(func(e Error) bool { return e.IsUsage() }) }
-func (m MultiError) IsDecode() bool { return m.any(func(e Error) bool { return e.IsDecode() }) }
-func (m MultiError) IsInternal() bool { return m.any(func(e Error) bool { return e.IsInternal() }) }
-
-// Cause returns nil for MultiError; there is no unique underlying cause in the
-// general case.
-//
-// Note: we could conceivably return a non-nil Cause only when there is exactly
-// one child error with a Cause. However, it would be brittle for client code
-// to rely on the arity of causes inside a MultiError, so we have opted not to
-// provide this functionality. Clients which really wish to access the Causes
-// of the underlying errors are free to iterate through the errors themselves.
-func (m MultiError) Cause() error { return nil }
-
-func (m MultiError) Error() string {
- s, n := "", 0
- for _, e := range m {
- if e != nil {
- if n == 0 {
- s = e.Error()
- }
- n++
- }
- }
- switch n {
- case 0:
- return "(0 errors)"
- case 1:
- return s
- case 2:
- return s + " (and 1 other error)"
- }
- return fmt.Sprintf("%s (and %d other errors)", s, n-1)
-}
-
-// any returns true if any element of m is an Error for which pred returns true.
-func (m MultiError) any(pred func(Error) bool) bool {
- for _, e := range m {
- if ourErr, ok := e.(Error); ok && pred(ourErr) {
- return true
- }
- }
- return false
-}
diff --git a/vendor/github.com/gorilla/sessions/AUTHORS b/vendor/github.com/gorilla/sessions/AUTHORS
deleted file mode 100644
index 1e3e7ac..0000000
--- a/vendor/github.com/gorilla/sessions/AUTHORS
+++ /dev/null
@@ -1,43 +0,0 @@
-# This is the official list of gorilla/sessions authors for copyright purposes.
-#
-# Please keep the list sorted.
-
-Ahmadreza Zibaei <ahmadrezazibaei@hotmail.com>
-Anton Lindström <lindztr@gmail.com>
-Brian Jones <mojobojo@gmail.com>
-Collin Stedman <kronion@users.noreply.github.com>
-Deniz Eren <dee.116@gmail.com>
-Dmitry Chestnykh <dmitry@codingrobots.com>
-Dustin Oprea <myselfasunder@gmail.com>
-Egon Elbre <egonelbre@gmail.com>
-enumappstore <appstore@enumapps.com>
-Geofrey Ernest <geofreyernest@live.com>
-Google LLC (https://opensource.google.com/)
-Jerry Saravia <SaraviaJ@gmail.com>
-Jonathan Gillham <jonathan.gillham@gamil.com>
-Justin Clift <justin@postgresql.org>
-Justin Hellings <justin.hellings@gmail.com>
-Kamil Kisiel <kamil@kamilkisiel.net>
-Keiji Yoshida <yoshida.keiji.84@gmail.com>
-kliron <kliron@gmail.com>
-Kshitij Saraogi <KshitijSaraogi@gmail.com>
-Lauris BH <lauris@nix.lv>
-Lukas Rist <glaslos@gmail.com>
-Mark Dain <ancarda@users.noreply.github.com>
-Matt Ho <matt.ho@gmail.com>
-Matt Silverlock <matt@eatsleeprepeat.net>
-Mattias Wadman <mattias.wadman@gmail.com>
-Michael Schuett <michaeljs1990@gmail.com>
-Michael Stapelberg <stapelberg@users.noreply.github.com>
-Mirco Zeiss <mirco.zeiss@gmail.com>
-moraes <rodrigo.moraes@gmail.com>
-nvcnvn <nguyen@open-vn.org>
-pappz <zoltan.pmail@gmail.com>
-Pontus Leitzler <leitzler@users.noreply.github.com>
-QuaSoft <info@quasoft.net>
-rcadena <robert.cadena@gmail.com>
-rodrigo moraes <rodrigo.moraes@gmail.com>
-Shawn Smith <shawnpsmith@gmail.com>
-Taylor Hurt <taylor.a.hurt@gmail.com>
-Tortuoise <sanyasinp@gmail.com>
-Vitor De Mario <vitordemario@gmail.com>
diff --git a/vendor/github.com/gorilla/sessions/LICENSE b/vendor/github.com/gorilla/sessions/LICENSE
deleted file mode 100644
index 6903df6..0000000
--- a/vendor/github.com/gorilla/sessions/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2012-2018 The Gorilla Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/gorilla/sessions/README.md b/vendor/github.com/gorilla/sessions/README.md
deleted file mode 100644
index c9e0e92..0000000
--- a/vendor/github.com/gorilla/sessions/README.md
+++ /dev/null
@@ -1,92 +0,0 @@
-sessions
-========
-[![GoDoc](https://godoc.org/github.com/gorilla/sessions?status.svg)](https://godoc.org/github.com/gorilla/sessions) [![Build Status](https://travis-ci.org/gorilla/sessions.svg?branch=master)](https://travis-ci.org/gorilla/sessions)
-[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/sessions/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/sessions?badge)
-
-
-gorilla/sessions provides cookie and filesystem sessions and infrastructure for
-custom session backends.
-
-The key features are:
-
-* Simple API: use it as an easy way to set signed (and optionally
- encrypted) cookies.
-* Built-in backends to store sessions in cookies or the filesystem.
-* Flash messages: session values that last until read.
-* Convenient way to switch session persistency (aka "remember me") and set
- other attributes.
-* Mechanism to rotate authentication and encryption keys.
-* Multiple sessions per request, even using different backends.
-* Interfaces and infrastructure for custom session backends: sessions from
- different stores can be retrieved and batch-saved using a common API.
-
-Let's start with an example that shows the sessions API in a nutshell:
-
-```go
- import (
- "net/http"
- "github.com/gorilla/sessions"
- )
-
- var store = sessions.NewCookieStore([]byte("something-very-secret"))
-
- func MyHandler(w http.ResponseWriter, r *http.Request) {
- // Get a session. We're ignoring the error resulted from decoding an
- // existing session: Get() always returns a session, even if empty.
- session, _ := store.Get(r, "session-name")
- // Set some session values.
- session.Values["foo"] = "bar"
- session.Values[42] = 43
- // Save it before we write to the response/return from the handler.
- session.Save(r, w)
- }
-```
-
-First we initialize a session store calling `NewCookieStore()` and passing a
-secret key used to authenticate the session. Inside the handler, we call
-`store.Get()` to retrieve an existing session or create a new one. Then we set
-some session values in session.Values, which is a `map[interface{}]interface{}`.
-And finally we call `session.Save()` to save the session in the response.
-
-Important Note: If you aren't using gorilla/mux, you need to wrap your handlers
-with
-[`context.ClearHandler`](http://www.gorillatoolkit.org/pkg/context#ClearHandler)
-or else you will leak memory! An easy way to do this is to wrap the top-level
-mux when calling http.ListenAndServe:
-
-```go
- http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux))
-```
-
-The ClearHandler function is provided by the gorilla/context package.
-
-More examples are available [on the Gorilla
-website](http://www.gorillatoolkit.org/pkg/sessions).
-
-## Store Implementations
-
-Other implementations of the `sessions.Store` interface:
-
-* [github.com/starJammer/gorilla-sessions-arangodb](https://github.com/starJammer/gorilla-sessions-arangodb) - ArangoDB
-* [github.com/yosssi/boltstore](https://github.com/yosssi/boltstore) - Bolt
-* [github.com/srinathgs/couchbasestore](https://github.com/srinathgs/couchbasestore) - Couchbase
-* [github.com/denizeren/dynamostore](https://github.com/denizeren/dynamostore) - Dynamodb on AWS
-* [github.com/savaki/dynastore](https://github.com/savaki/dynastore) - DynamoDB on AWS (Official AWS library)
-* [github.com/bradleypeabody/gorilla-sessions-memcache](https://github.com/bradleypeabody/gorilla-sessions-memcache) - Memcache
-* [github.com/dsoprea/go-appengine-sessioncascade](https://github.com/dsoprea/go-appengine-sessioncascade) - Memcache/Datastore/Context in AppEngine
-* [github.com/kidstuff/mongostore](https://github.com/kidstuff/mongostore) - MongoDB
-* [github.com/srinathgs/mysqlstore](https://github.com/srinathgs/mysqlstore) - MySQL
-* [github.com/EnumApps/clustersqlstore](https://github.com/EnumApps/clustersqlstore) - MySQL Cluster
-* [github.com/antonlindstrom/pgstore](https://github.com/antonlindstrom/pgstore) - PostgreSQL
-* [github.com/boj/redistore](https://github.com/boj/redistore) - Redis
-* [github.com/boj/rethinkstore](https://github.com/boj/rethinkstore) - RethinkDB
-* [github.com/boj/riakstore](https://github.com/boj/riakstore) - Riak
-* [github.com/michaeljs1990/sqlitestore](https://github.com/michaeljs1990/sqlitestore) - SQLite
-* [github.com/wader/gormstore](https://github.com/wader/gormstore) - GORM (MySQL, PostgreSQL, SQLite)
-* [github.com/gernest/qlstore](https://github.com/gernest/qlstore) - ql
-* [github.com/quasoft/memstore](https://github.com/quasoft/memstore) - In-memory implementation for use in unit tests
-* [github.com/lafriks/xormstore](https://github.com/lafriks/xormstore) - XORM (MySQL, PostgreSQL, SQLite, Microsoft SQL Server, TiDB)
-
-## License
-
-BSD licensed. See the LICENSE file for details.
diff --git a/vendor/github.com/gorilla/sessions/doc.go b/vendor/github.com/gorilla/sessions/doc.go
deleted file mode 100644
index 57a5291..0000000
--- a/vendor/github.com/gorilla/sessions/doc.go
+++ /dev/null
@@ -1,198 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-/*
-Package sessions provides cookie and filesystem sessions and
-infrastructure for custom session backends.
-
-The key features are:
-
- * Simple API: use it as an easy way to set signed (and optionally
- encrypted) cookies.
- * Built-in backends to store sessions in cookies or the filesystem.
- * Flash messages: session values that last until read.
- * Convenient way to switch session persistency (aka "remember me") and set
- other attributes.
- * Mechanism to rotate authentication and encryption keys.
- * Multiple sessions per request, even using different backends.
- * Interfaces and infrastructure for custom session backends: sessions from
- different stores can be retrieved and batch-saved using a common API.
-
-Let's start with an example that shows the sessions API in a nutshell:
-
- import (
- "net/http"
- "github.com/gorilla/sessions"
- )
-
- var store = sessions.NewCookieStore([]byte("something-very-secret"))
-
- func MyHandler(w http.ResponseWriter, r *http.Request) {
- // Get a session. Get() always returns a session, even if empty.
- session, err := store.Get(r, "session-name")
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
-
- // Set some session values.
- session.Values["foo"] = "bar"
- session.Values[42] = 43
- // Save it before we write to the response/return from the handler.
- session.Save(r, w)
- }
-
-First we initialize a session store calling NewCookieStore() and passing a
-secret key used to authenticate the session. Inside the handler, we call
-store.Get() to retrieve an existing session or a new one. Then we set some
-session values in session.Values, which is a map[interface{}]interface{}.
-And finally we call session.Save() to save the session in the response.
-
-Note that in production code, we should check for errors when calling
-session.Save(r, w), and either display an error message or otherwise handle it.
-
-Save must be called before writing to the response, otherwise the session
-cookie will not be sent to the client.
-
-Important Note: If you aren't using gorilla/mux, you need to wrap your handlers
-with context.ClearHandler as or else you will leak memory! An easy way to do this
-is to wrap the top-level mux when calling http.ListenAndServe:
-
- http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux))
-
-The ClearHandler function is provided by the gorilla/context package.
-
-That's all you need to know for the basic usage. Let's take a look at other
-options, starting with flash messages.
-
-Flash messages are session values that last until read. The term appeared with
-Ruby On Rails a few years back. When we request a flash message, it is removed
-from the session. To add a flash, call session.AddFlash(), and to get all
-flashes, call session.Flashes(). Here is an example:
-
- func MyHandler(w http.ResponseWriter, r *http.Request) {
- // Get a session.
- session, err := store.Get(r, "session-name")
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
-
- // Get the previous flashes, if any.
- if flashes := session.Flashes(); len(flashes) > 0 {
- // Use the flash values.
- } else {
- // Set a new flash.
- session.AddFlash("Hello, flash messages world!")
- }
- session.Save(r, w)
- }
-
-Flash messages are useful to set information to be read after a redirection,
-like after form submissions.
-
-There may also be cases where you want to store a complex datatype within a
-session, such as a struct. Sessions are serialised using the encoding/gob package,
-so it is easy to register new datatypes for storage in sessions:
-
- import(
- "encoding/gob"
- "github.com/gorilla/sessions"
- )
-
- type Person struct {
- FirstName string
- LastName string
- Email string
- Age int
- }
-
- type M map[string]interface{}
-
- func init() {
-
- gob.Register(&Person{})
- gob.Register(&M{})
- }
-
-As it's not possible to pass a raw type as a parameter to a function, gob.Register()
-relies on us passing it a value of the desired type. In the example above we've passed
-it a pointer to a struct and a pointer to a custom type representing a
-map[string]interface. (We could have passed non-pointer values if we wished.) This will
-then allow us to serialise/deserialise values of those types to and from our sessions.
-
-Note that because session values are stored in a map[string]interface{}, there's
-a need to type-assert data when retrieving it. We'll use the Person struct we registered above:
-
- func MyHandler(w http.ResponseWriter, r *http.Request) {
- session, err := store.Get(r, "session-name")
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
-
- // Retrieve our struct and type-assert it
- val := session.Values["person"]
- var person = &Person{}
- if person, ok := val.(*Person); !ok {
- // Handle the case that it's not an expected type
- }
-
- // Now we can use our person object
- }
-
-By default, session cookies last for a month. This is probably too long for
-some cases, but it is easy to change this and other attributes during
-runtime. Sessions can be configured individually or the store can be
-configured and then all sessions saved using it will use that configuration.
-We access session.Options or store.Options to set a new configuration. The
-fields are basically a subset of http.Cookie fields. Let's change the
-maximum age of a session to one week:
-
- session.Options = &sessions.Options{
- Path: "/",
- MaxAge: 86400 * 7,
- HttpOnly: true,
- }
-
-Sometimes we may want to change authentication and/or encryption keys without
-breaking existing sessions. The CookieStore supports key rotation, and to use
-it you just need to set multiple authentication and encryption keys, in pairs,
-to be tested in order:
-
- var store = sessions.NewCookieStore(
- []byte("new-authentication-key"),
- []byte("new-encryption-key"),
- []byte("old-authentication-key"),
- []byte("old-encryption-key"),
- )
-
-New sessions will be saved using the first pair. Old sessions can still be
-read because the first pair will fail, and the second will be tested. This
-makes it easy to "rotate" secret keys and still be able to validate existing
-sessions. Note: for all pairs the encryption key is optional; set it to nil
-or omit it and and encryption won't be used.
-
-Multiple sessions can be used in the same request, even with different
-session backends. When this happens, calling Save() on each session
-individually would be cumbersome, so we have a way to save all sessions
-at once: it's sessions.Save(). Here's an example:
-
- var store = sessions.NewCookieStore([]byte("something-very-secret"))
-
- func MyHandler(w http.ResponseWriter, r *http.Request) {
- // Get a session and set a value.
- session1, _ := store.Get(r, "session-one")
- session1.Values["foo"] = "bar"
- // Get another session and set another value.
- session2, _ := store.Get(r, "session-two")
- session2.Values[42] = 43
- // Save all sessions.
- sessions.Save(r, w)
- }
-
-This is possible because when we call Get() from a session store, it adds the
-session to a common registry. Save() uses it to save all registered sessions.
-*/
-package sessions
diff --git a/vendor/github.com/gorilla/sessions/go.mod b/vendor/github.com/gorilla/sessions/go.mod
deleted file mode 100644
index 44befd4..0000000
--- a/vendor/github.com/gorilla/sessions/go.mod
+++ /dev/null
@@ -1,6 +0,0 @@
-module "github.com/gorilla/sessions"
-
-require (
- "github.com/gorilla/context" v1.1.1
- "github.com/gorilla/securecookie" v1.1.1
-)
diff --git a/vendor/github.com/gorilla/sessions/lex.go b/vendor/github.com/gorilla/sessions/lex.go
deleted file mode 100644
index 4bbbe10..0000000
--- a/vendor/github.com/gorilla/sessions/lex.go
+++ /dev/null
@@ -1,102 +0,0 @@
-// This file contains code adapted from the Go standard library
-// https://github.com/golang/go/blob/39ad0fd0789872f9469167be7fe9578625ff246e/src/net/http/lex.go
-
-package sessions
-
-import "strings"
-
-var isTokenTable = [127]bool{
- '!': true,
- '#': true,
- '$': true,
- '%': true,
- '&': true,
- '\'': true,
- '*': true,
- '+': true,
- '-': true,
- '.': true,
- '0': true,
- '1': true,
- '2': true,
- '3': true,
- '4': true,
- '5': true,
- '6': true,
- '7': true,
- '8': true,
- '9': true,
- 'A': true,
- 'B': true,
- 'C': true,
- 'D': true,
- 'E': true,
- 'F': true,
- 'G': true,
- 'H': true,
- 'I': true,
- 'J': true,
- 'K': true,
- 'L': true,
- 'M': true,
- 'N': true,
- 'O': true,
- 'P': true,
- 'Q': true,
- 'R': true,
- 'S': true,
- 'T': true,
- 'U': true,
- 'W': true,
- 'V': true,
- 'X': true,
- 'Y': true,
- 'Z': true,
- '^': true,
- '_': true,
- '`': true,
- 'a': true,
- 'b': true,
- 'c': true,
- 'd': true,
- 'e': true,
- 'f': true,
- 'g': true,
- 'h': true,
- 'i': true,
- 'j': true,
- 'k': true,
- 'l': true,
- 'm': true,
- 'n': true,
- 'o': true,
- 'p': true,
- 'q': true,
- 'r': true,
- 's': true,
- 't': true,
- 'u': true,
- 'v': true,
- 'w': true,
- 'x': true,
- 'y': true,
- 'z': true,
- '|': true,
- '~': true,
-}
-
-func isToken(r rune) bool {
- i := int(r)
- return i < len(isTokenTable) && isTokenTable[i]
-}
-
-func isNotToken(r rune) bool {
- return !isToken(r)
-}
-
-func isCookieNameValid(raw string) bool {
- if raw == "" {
- return false
- }
- return strings.IndexFunc(raw, isNotToken) < 0
-}
diff --git a/vendor/github.com/gorilla/sessions/sessions.go b/vendor/github.com/gorilla/sessions/sessions.go
deleted file mode 100644
index 9870e31..0000000
--- a/vendor/github.com/gorilla/sessions/sessions.go
+++ /dev/null
@@ -1,243 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package sessions
-
-import (
- "encoding/gob"
- "fmt"
- "net/http"
- "time"
-
- "github.com/gorilla/context"
-)
-
-// Default flashes key.
-const flashesKey = "_flash"
-
-// Options --------------------------------------------------------------------
-
-// Options stores configuration for a session or session store.
-//
-// Fields are a subset of http.Cookie fields.
-type Options struct {
- Path string
- Domain string
- // MaxAge=0 means no Max-Age attribute specified and the cookie will be
- // deleted after the browser session ends.
- // MaxAge<0 means delete cookie immediately.
- // MaxAge>0 means Max-Age attribute present and given in seconds.
- MaxAge int
- Secure bool
- HttpOnly bool
-}
-
-// Session --------------------------------------------------------------------
-
-// NewSession is called by session stores to create a new session instance.
-func NewSession(store Store, name string) *Session {
- return &Session{
- Values: make(map[interface{}]interface{}),
- store: store,
- name: name,
- Options: new(Options),
- }
-}
-
-// Session stores the values and optional configuration for a session.
-type Session struct {
- // The ID of the session, generated by stores. It should not be used for
- // user data.
- ID string
- // Values contains the user-data for the session.
- Values map[interface{}]interface{}
- Options *Options
- IsNew bool
- store Store
- name string
-}
-
-// Flashes returns a slice of flash messages from the session.
-//
-// A single variadic argument is accepted, and it is optional: it defines
-// the flash key. If not defined "_flash" is used by default.
-func (s *Session) Flashes(vars ...string) []interface{} {
- var flashes []interface{}
- key := flashesKey
- if len(vars) > 0 {
- key = vars[0]
- }
- if v, ok := s.Values[key]; ok {
- // Drop the flashes and return it.
- delete(s.Values, key)
- flashes = v.([]interface{})
- }
- return flashes
-}
-
-// AddFlash adds a flash message to the session.
-//
-// A single variadic argument is accepted, and it is optional: it defines
-// the flash key. If not defined "_flash" is used by default.
-func (s *Session) AddFlash(value interface{}, vars ...string) {
- key := flashesKey
- if len(vars) > 0 {
- key = vars[0]
- }
- var flashes []interface{}
- if v, ok := s.Values[key]; ok {
- flashes = v.([]interface{})
- }
- s.Values[key] = append(flashes, value)
-}
-
-// Save is a convenience method to save this session. It is the same as calling
-// store.Save(request, response, session). You should call Save before writing to
-// the response or returning from the handler.
-func (s *Session) Save(r *http.Request, w http.ResponseWriter) error {
- return s.store.Save(r, w, s)
-}
-
-// Name returns the name used to register the session.
-func (s *Session) Name() string {
- return s.name
-}
-
-// Store returns the session store used to register the session.
-func (s *Session) Store() Store {
- return s.store
-}
-
-// Registry -------------------------------------------------------------------
-
-// sessionInfo stores a session tracked by the registry.
-type sessionInfo struct {
- s *Session
- e error
-}
-
-// contextKey is the type used to store the registry in the context.
-type contextKey int
-
-// registryKey is the key used to store the registry in the context.
-const registryKey contextKey = 0
-
-// GetRegistry returns a registry instance for the current request.
-func GetRegistry(r *http.Request) *Registry {
- registry := context.Get(r, registryKey)
- if registry != nil {
- return registry.(*Registry)
- }
- newRegistry := &Registry{
- request: r,
- sessions: make(map[string]sessionInfo),
- }
- context.Set(r, registryKey, newRegistry)
- return newRegistry
-}
-
-// Registry stores sessions used during a request.
-type Registry struct {
- request *http.Request
- sessions map[string]sessionInfo
-}
-
-// Get registers and returns a session for the given name and session store.
-//
-// It returns a new session if there are no sessions registered for the name.
-func (s *Registry) Get(store Store, name string) (session *Session, err error) {
- if !isCookieNameValid(name) {
- return nil, fmt.Errorf("sessions: invalid character in cookie name: %s", name)
- }
- if info, ok := s.sessions[name]; ok {
- session, err = info.s, info.e
- } else {
- session, err = store.New(s.request, name)
- session.name = name
- s.sessions[name] = sessionInfo{s: session, e: err}
- }
- session.store = store
- return
-}
-
-// Save saves all sessions registered for the current request.
-func (s *Registry) Save(w http.ResponseWriter) error {
- var errMulti MultiError
- for name, info := range s.sessions {
- session := info.s
- if session.store == nil {
- errMulti = append(errMulti, fmt.Errorf(
- "sessions: missing store for session %q", name))
- } else if err := session.store.Save(s.request, w, session); err != nil {
- errMulti = append(errMulti, fmt.Errorf(
- "sessions: error saving session %q -- %v", name, err))
- }
- }
- if errMulti != nil {
- return errMulti
- }
- return nil
-}
-
-// Helpers --------------------------------------------------------------------
-
-func init() {
- gob.Register([]interface{}{})
-}
-
-// Save saves all sessions used during the current request.
-func Save(r *http.Request, w http.ResponseWriter) error {
- return GetRegistry(r).Save(w)
-}
-
-// NewCookie returns an http.Cookie with the options set. It also sets
-// the Expires field calculated based on the MaxAge value, for Internet
-// Explorer compatibility.
-func NewCookie(name, value string, options *Options) *http.Cookie {
- cookie := &http.Cookie{
- Name: name,
- Value: value,
- Path: options.Path,
- Domain: options.Domain,
- MaxAge: options.MaxAge,
- Secure: options.Secure,
- HttpOnly: options.HttpOnly,
- }
- if options.MaxAge > 0 {
- d := time.Duration(options.MaxAge) * time.Second
- cookie.Expires = time.Now().Add(d)
- } else if options.MaxAge < 0 {
- // Set it to the past to expire now.
- cookie.Expires = time.Unix(1, 0)
- }
- return cookie
-}
-
-// Error ----------------------------------------------------------------------
-
-// MultiError stores multiple errors.
-//
-// Borrowed from the App Engine SDK.
-type MultiError []error
-
-func (m MultiError) Error() string {
- s, n := "", 0
- for _, e := range m {
- if e != nil {
- if n == 0 {
- s = e.Error()
- }
- n++
- }
- }
- switch n {
- case 0:
- return "(0 errors)"
- case 1:
- return s
- case 2:
- return s + " (and 1 other error)"
- }
- return fmt.Sprintf("%s (and %d other errors)", s, n-1)
-}
diff --git a/vendor/github.com/gorilla/sessions/store.go b/vendor/github.com/gorilla/sessions/store.go
deleted file mode 100644
index 4ff6b6c..0000000
--- a/vendor/github.com/gorilla/sessions/store.go
+++ /dev/null
@@ -1,295 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package sessions
-
-import (
- "encoding/base32"
- "io/ioutil"
- "net/http"
- "os"
- "path/filepath"
- "strings"
- "sync"
-
- "github.com/gorilla/securecookie"
-)
-
-// Store is an interface for custom session stores.
-//
-// See CookieStore and FilesystemStore for examples.
-type Store interface {
- // Get should return a cached session.
- Get(r *http.Request, name string) (*Session, error)
-
- // New should create and return a new session.
- //
- // Note that New should never return a nil session, even in the case of
- // an error if using the Registry infrastructure to cache the session.
- New(r *http.Request, name string) (*Session, error)
-
- // Save should persist session to the underlying store implementation.
- Save(r *http.Request, w http.ResponseWriter, s *Session) error
-}
-
-// CookieStore ----------------------------------------------------------------
-
-// NewCookieStore returns a new CookieStore.
-//
-// Keys are defined in pairs to allow key rotation, but the common case is
-// to set a single authentication key and optionally an encryption key.
-//
-// The first key in a pair is used for authentication and the second for
-// encryption. The encryption key can be set to nil or omitted in the last
-// pair, but the authentication key is required in all pairs.
-//
-// It is recommended to use an authentication key with 32 or 64 bytes.
-// The encryption key, if set, must be either 16, 24, or 32 bytes to select
-// AES-128, AES-192, or AES-256 modes.
-//
-// Use the convenience function securecookie.GenerateRandomKey() to create
-// strong keys.
-func NewCookieStore(keyPairs ...[]byte) *CookieStore {
- cs := &CookieStore{
- Codecs: securecookie.CodecsFromPairs(keyPairs...),
- Options: &Options{
- Path: "/",
- MaxAge: 86400 * 30,
- },
- }
-
- cs.MaxAge(cs.Options.MaxAge)
- return cs
-}
-
-// CookieStore stores sessions using secure cookies.
-type CookieStore struct {
- Codecs []securecookie.Codec
- Options *Options // default configuration
-}
-
-// Get returns a session for the given name after adding it to the registry.
-//
-// It returns a new session if the sessions doesn't exist. Access IsNew on
-// the session to check if it is an existing session or a new one.
-//
-// It returns a new session and an error if the session exists but could
-// not be decoded.
-func (s *CookieStore) Get(r *http.Request, name string) (*Session, error) {
- return GetRegistry(r).Get(s, name)
-}
-
-// New returns a session for the given name without adding it to the registry.
-//
-// The difference between New() and Get() is that calling New() twice will
-// decode the session data twice, while Get() registers and reuses the same
-// decoded session after the first call.
-func (s *CookieStore) New(r *http.Request, name string) (*Session, error) {
- session := NewSession(s, name)
- opts := *s.Options
- session.Options = &opts
- session.IsNew = true
- var err error
- if c, errCookie := r.Cookie(name); errCookie == nil {
- err = securecookie.DecodeMulti(name, c.Value, &session.Values,
- s.Codecs...)
- if err == nil {
- session.IsNew = false
- }
- }
- return session, err
-}
-
-// Save adds a single session to the response.
-func (s *CookieStore) Save(r *http.Request, w http.ResponseWriter,
- session *Session) error {
- encoded, err := securecookie.EncodeMulti(session.Name(), session.Values,
- s.Codecs...)
- if err != nil {
- return err
- }
- http.SetCookie(w, NewCookie(session.Name(), encoded, session.Options))
- return nil
-}
-
-// MaxAge sets the maximum age for the store and the underlying cookie
-// implementation. Individual sessions can be deleted by setting Options.MaxAge
-// = -1 for that session.
-func (s *CookieStore) MaxAge(age int) {
- s.Options.MaxAge = age
-
- // Set the maxAge for each securecookie instance.
- for _, codec := range s.Codecs {
- if sc, ok := codec.(*securecookie.SecureCookie); ok {
- sc.MaxAge(age)
- }
- }
-}
-
-// FilesystemStore ------------------------------------------------------------
-
-var fileMutex sync.RWMutex
-
-// NewFilesystemStore returns a new FilesystemStore.
-//
-// The path argument is the directory where sessions will be saved. If empty
-// it will use os.TempDir().
-//
-// See NewCookieStore() for a description of the other parameters.
-func NewFilesystemStore(path string, keyPairs ...[]byte) *FilesystemStore {
- if path == "" {
- path = os.TempDir()
- }
- fs := &FilesystemStore{
- Codecs: securecookie.CodecsFromPairs(keyPairs...),
- Options: &Options{
- Path: "/",
- MaxAge: 86400 * 30,
- },
- path: path,
- }
-
- fs.MaxAge(fs.Options.MaxAge)
- return fs
-}
-
-// FilesystemStore stores sessions in the filesystem.
-//
-// It also serves as a reference for custom stores.
-//
-// This store is still experimental and not well tested. Feedback is welcome.
-type FilesystemStore struct {
- Codecs []securecookie.Codec
- Options *Options // default configuration
- path string
-}
-
-// MaxLength restricts the maximum length of new sessions to l.
-// If l is 0 there is no limit to the size of a session, use with caution.
-// The default for a new FilesystemStore is 4096.
-func (s *FilesystemStore) MaxLength(l int) {
- for _, c := range s.Codecs {
- if codec, ok := c.(*securecookie.SecureCookie); ok {
- codec.MaxLength(l)
- }
- }
-}
-
-// Get returns a session for the given name after adding it to the registry.
-//
-// See CookieStore.Get().
-func (s *FilesystemStore) Get(r *http.Request, name string) (*Session, error) {
- return GetRegistry(r).Get(s, name)
-}
-
-// New returns a session for the given name without adding it to the registry.
-//
-// See CookieStore.New().
-func (s *FilesystemStore) New(r *http.Request, name string) (*Session, error) {
- session := NewSession(s, name)
- opts := *s.Options
- session.Options = &opts
- session.IsNew = true
- var err error
- if c, errCookie := r.Cookie(name); errCookie == nil {
- err = securecookie.DecodeMulti(name, c.Value, &session.ID, s.Codecs...)
- if err == nil {
- err = s.load(session)
- if err == nil {
- session.IsNew = false
- }
- }
- }
- return session, err
-}
-
-// Save adds a single session to the response.
-//
-// If the Options.MaxAge of the session is <= 0 then the session file will be
-// deleted from the store path. With this process it enforces the properly
-// session cookie handling so no need to trust in the cookie management in the
-// web browser.
-func (s *FilesystemStore) Save(r *http.Request, w http.ResponseWriter,
- session *Session) error {
- // Delete if max-age is <= 0
- if session.Options.MaxAge <= 0 {
- if err := s.erase(session); err != nil {
- return err
- }
- http.SetCookie(w, NewCookie(session.Name(), "", session.Options))
- return nil
- }
-
- if session.ID == "" {
- // Because the ID is used in the filename, encode it to
- // use alphanumeric characters only.
- session.ID = strings.TrimRight(
- base32.StdEncoding.EncodeToString(
- securecookie.GenerateRandomKey(32)), "=")
- }
- if err := s.save(session); err != nil {
- return err
- }
- encoded, err := securecookie.EncodeMulti(session.Name(), session.ID,
- s.Codecs...)
- if err != nil {
- return err
- }
- http.SetCookie(w, NewCookie(session.Name(), encoded, session.Options))
- return nil
-}
-
-// MaxAge sets the maximum age for the store and the underlying cookie
-// implementation. Individual sessions can be deleted by setting Options.MaxAge
-// = -1 for that session.
-func (s *FilesystemStore) MaxAge(age int) {
- s.Options.MaxAge = age
-
- // Set the maxAge for each securecookie instance.
- for _, codec := range s.Codecs {
- if sc, ok := codec.(*securecookie.SecureCookie); ok {
- sc.MaxAge(age)
- }
- }
-}
-
-// save writes encoded session.Values to a file.
-func (s *FilesystemStore) save(session *Session) error {
- encoded, err := securecookie.EncodeMulti(session.Name(), session.Values,
- s.Codecs...)
- if err != nil {
- return err
- }
- filename := filepath.Join(s.path, "session_"+session.ID)
- fileMutex.Lock()
- defer fileMutex.Unlock()
- return ioutil.WriteFile(filename, []byte(encoded), 0600)
-}
-
-// load reads a file and decodes its content into session.Values.
-func (s *FilesystemStore) load(session *Session) error {
- filename := filepath.Join(s.path, "session_"+session.ID)
- fileMutex.RLock()
- defer fileMutex.RUnlock()
- fdata, err := ioutil.ReadFile(filename)
- if err != nil {
- return err
- }
- if err = securecookie.DecodeMulti(session.Name(), string(fdata),
- &session.Values, s.Codecs...); err != nil {
- return err
- }
- return nil
-}
-
-// delete session file
-func (s *FilesystemStore) erase(session *Session) error {
- filename := filepath.Join(s.path, "session_"+session.ID)
-
- fileMutex.RLock()
- defer fileMutex.RUnlock()
-
- err := os.Remove(filename)
- return err
-}