diff options
Diffstat (limited to 'vendor/github.com/labstack/echo/middleware')
9 files changed, 192 insertions, 47 deletions
diff --git a/vendor/github.com/labstack/echo/middleware/basic_auth.go b/vendor/github.com/labstack/echo/middleware/basic_auth.go index c1f34c8f..ae80da95 100644 --- a/vendor/github.com/labstack/echo/middleware/basic_auth.go +++ b/vendor/github.com/labstack/echo/middleware/basic_auth.go @@ -3,6 +3,7 @@ package middleware import ( "encoding/base64" "strconv" + "strings" "github.com/labstack/echo" ) @@ -27,7 +28,7 @@ type ( ) const ( - basic = "Basic" + basic = "basic" defaultRealm = "Restricted" ) @@ -54,7 +55,7 @@ func BasicAuth(fn BasicAuthValidator) echo.MiddlewareFunc { func BasicAuthWithConfig(config BasicAuthConfig) echo.MiddlewareFunc { // Defaults if config.Validator == nil { - panic("basic-auth middleware requires a validator function") + panic("echo: basic-auth middleware requires a validator function") } if config.Skipper == nil { config.Skipper = DefaultBasicAuthConfig.Skipper @@ -72,7 +73,7 @@ func BasicAuthWithConfig(config BasicAuthConfig) echo.MiddlewareFunc { auth := c.Request().Header.Get(echo.HeaderAuthorization) l := len(basic) - if len(auth) > l+1 && auth[:l] == basic { + if len(auth) > l+1 && strings.ToLower(auth[:l]) == basic { b, err := base64.StdEncoding.DecodeString(auth[l+1:]) if err != nil { return err diff --git a/vendor/github.com/labstack/echo/middleware/body_dump.go b/vendor/github.com/labstack/echo/middleware/body_dump.go new file mode 100644 index 00000000..88b75ee1 --- /dev/null +++ b/vendor/github.com/labstack/echo/middleware/body_dump.go @@ -0,0 +1,112 @@ +package middleware + +import ( + "bufio" + "bytes" + "io/ioutil" + "net" + "net/http" + + "io" + + "github.com/labstack/echo" +) + +type ( + // BodyDumpConfig defines the config for BodyDump middleware. + BodyDumpConfig struct { + // Skipper defines a function to skip middleware. + Skipper Skipper + + // Handler receives request and response payload. + // Required. + Handler BodyDumpHandler + } + + // BodyDumpHandler receives the request and response payload. + BodyDumpHandler func(echo.Context, []byte, []byte) + + bodyDumpResponseWriter struct { + io.Writer + http.ResponseWriter + } +) + +var ( + // DefaultBodyDumpConfig is the default Gzip middleware config. + DefaultBodyDumpConfig = BodyDumpConfig{ + Skipper: DefaultSkipper, + } +) + +// BodyDump returns a BodyDump middleware. +// +// BodyLimit middleware captures the request and response payload and calls the +// registered handler. +func BodyDump(handler BodyDumpHandler) echo.MiddlewareFunc { + c := DefaultBodyDumpConfig + c.Handler = handler + return BodyDumpWithConfig(c) +} + +// BodyDumpWithConfig returns a BodyDump middleware with config. +// See: `BodyDump()`. +func BodyDumpWithConfig(config BodyDumpConfig) echo.MiddlewareFunc { + // Defaults + if config.Handler == nil { + panic("echo: body-dump middleware requires a handler function") + } + if config.Skipper == nil { + config.Skipper = DefaultBodyDumpConfig.Skipper + } + + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) (err error) { + if config.Skipper(c) { + return next(c) + } + + // Request + reqBody := []byte{} + if c.Request().Body != nil { // Read + reqBody, _ = ioutil.ReadAll(c.Request().Body) + } + c.Request().Body = ioutil.NopCloser(bytes.NewBuffer(reqBody)) // Reset + + // Response + resBody := new(bytes.Buffer) + mw := io.MultiWriter(c.Response().Writer, resBody) + writer := &bodyDumpResponseWriter{Writer: mw, ResponseWriter: c.Response().Writer} + c.Response().Writer = writer + + if err = next(c); err != nil { + c.Error(err) + } + + // Callback + config.Handler(c, reqBody, resBody.Bytes()) + + return + } + } +} + +func (w *bodyDumpResponseWriter) WriteHeader(code int) { + w.ResponseWriter.WriteHeader(code) +} + +func (w *bodyDumpResponseWriter) Write(b []byte) (int, error) { + return w.Writer.Write(b) +} + +func (w *bodyDumpResponseWriter) Flush() { + w.ResponseWriter.(http.Flusher).Flush() +} + +func (w *bodyDumpResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return w.ResponseWriter.(http.Hijacker).Hijack() +} + +func (w *bodyDumpResponseWriter) CloseNotify() <-chan bool { + return w.ResponseWriter.(http.CloseNotifier).CloseNotify() +} diff --git a/vendor/github.com/labstack/echo/middleware/body_limit.go b/vendor/github.com/labstack/echo/middleware/body_limit.go index a2ff8d62..b964cd29 100644 --- a/vendor/github.com/labstack/echo/middleware/body_limit.go +++ b/vendor/github.com/labstack/echo/middleware/body_limit.go @@ -30,7 +30,7 @@ type ( ) var ( - // DefaultBodyLimitConfig is the default Gzip middleware config. + // DefaultBodyLimitConfig is the default BodyLimit middleware config. DefaultBodyLimitConfig = BodyLimitConfig{ Skipper: DefaultSkipper, } @@ -60,7 +60,7 @@ func BodyLimitWithConfig(config BodyLimitConfig) echo.MiddlewareFunc { limit, err := bytes.Parse(config.Limit) if err != nil { - panic(fmt.Errorf("invalid body-limit=%s", config.Limit)) + panic(fmt.Errorf("echo: invalid body-limit=%s", config.Limit)) } config.limit = limit pool := limitedReaderPool(config) diff --git a/vendor/github.com/labstack/echo/middleware/compress.go b/vendor/github.com/labstack/echo/middleware/compress.go index cffadbd1..1615624c 100644 --- a/vendor/github.com/labstack/echo/middleware/compress.go +++ b/vendor/github.com/labstack/echo/middleware/compress.go @@ -67,7 +67,7 @@ func GzipWithConfig(config GzipConfig) echo.MiddlewareFunc { res := c.Response() res.Header().Add(echo.HeaderVary, echo.HeaderAcceptEncoding) if strings.Contains(c.Request().Header.Get(echo.HeaderAcceptEncoding), gzipScheme) { - res.Header().Add(echo.HeaderContentEncoding, gzipScheme) // Issue #806 + res.Header().Set(echo.HeaderContentEncoding, gzipScheme) // Issue #806 rw := res.Writer w, err := gzip.NewWriterLevel(rw, config.Level) if err != nil { @@ -98,6 +98,7 @@ func (w *gzipResponseWriter) WriteHeader(code int) { if code == http.StatusNoContent { // Issue #489 w.ResponseWriter.Header().Del(echo.HeaderContentEncoding) } + w.Header().Del(echo.HeaderContentLength) // Issue #444 w.ResponseWriter.WriteHeader(code) } diff --git a/vendor/github.com/labstack/echo/middleware/jwt.go b/vendor/github.com/labstack/echo/middleware/jwt.go index 5d2072e7..47d885b0 100644 --- a/vendor/github.com/labstack/echo/middleware/jwt.go +++ b/vendor/github.com/labstack/echo/middleware/jwt.go @@ -1,7 +1,6 @@ package middleware import ( - "errors" "fmt" "net/http" "reflect" @@ -57,6 +56,12 @@ const ( AlgorithmHS256 = "HS256" ) +// Errors +var ( + ErrJWTMissing = echo.NewHTTPError(http.StatusBadRequest, "Missing or malformed jwt") + ErrJWTInvalid = echo.NewHTTPError(http.StatusUnauthorized, "Invalid or expired jwt") +) + var ( // DefaultJWTConfig is the default JWT auth middleware config. DefaultJWTConfig = JWTConfig{ @@ -77,7 +82,7 @@ var ( // // See: https://jwt.io/introduction // See `JWTConfig.TokenLookup` -func JWT(key []byte) echo.MiddlewareFunc { +func JWT(key interface{}) echo.MiddlewareFunc { c := DefaultJWTConfig c.SigningKey = key return JWTWithConfig(c) @@ -134,14 +139,15 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc { auth, err := extractor(c) if err != nil { - return echo.NewHTTPError(http.StatusBadRequest, err.Error()) + return err } token := new(jwt.Token) // Issue #647, #656 if _, ok := config.Claims.(jwt.MapClaims); ok { token, err = jwt.Parse(auth, config.keyFunc) } else { - claims := reflect.ValueOf(config.Claims).Interface().(jwt.Claims) + t := reflect.ValueOf(config.Claims).Type().Elem() + claims := reflect.New(t).Interface().(jwt.Claims) token, err = jwt.ParseWithClaims(auth, claims, config.keyFunc) } if err == nil && token.Valid { @@ -149,7 +155,11 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc { c.Set(config.ContextKey, token) return next(c) } - return echo.ErrUnauthorized + return &echo.HTTPError{ + Code: ErrJWTInvalid.Code, + Message: ErrJWTInvalid.Message, + Inner: err, + } } } } @@ -162,7 +172,7 @@ func jwtFromHeader(header string, authScheme string) jwtExtractor { if len(auth) > l+1 && auth[:l] == authScheme { return auth[l+1:], nil } - return "", errors.New("Missing or invalid jwt in the request header") + return "", ErrJWTMissing } } @@ -171,7 +181,7 @@ func jwtFromQuery(param string) jwtExtractor { return func(c echo.Context) (string, error) { token := c.QueryParam(param) if token == "" { - return "", errors.New("Missing jwt in the query string") + return "", ErrJWTMissing } return token, nil } @@ -182,7 +192,7 @@ func jwtFromCookie(name string) jwtExtractor { return func(c echo.Context) (string, error) { cookie, err := c.Cookie(name) if err != nil { - return "", errors.New("Missing jwt in the cookie") + return "", ErrJWTMissing } return cookie.Value, nil } diff --git a/vendor/github.com/labstack/echo/middleware/key_auth.go b/vendor/github.com/labstack/echo/middleware/key_auth.go index 5ef87e3d..24625260 100644 --- a/vendor/github.com/labstack/echo/middleware/key_auth.go +++ b/vendor/github.com/labstack/echo/middleware/key_auth.go @@ -72,7 +72,7 @@ func KeyAuthWithConfig(config KeyAuthConfig) echo.MiddlewareFunc { config.KeyLookup = DefaultKeyAuthConfig.KeyLookup } if config.Validator == nil { - panic("key-auth middleware requires a validator function") + panic("echo: key-auth middleware requires a validator function") } // Initialize diff --git a/vendor/github.com/labstack/echo/middleware/proxy.go b/vendor/github.com/labstack/echo/middleware/proxy.go index 7eb24abf..4f55f39d 100644 --- a/vendor/github.com/labstack/echo/middleware/proxy.go +++ b/vendor/github.com/labstack/echo/middleware/proxy.go @@ -1,7 +1,6 @@ package middleware import ( - "errors" "fmt" "io" "math/rand" @@ -54,35 +53,38 @@ type ( } ) +var ( + // DefaultProxyConfig is the default Proxy middleware config. + DefaultProxyConfig = ProxyConfig{ + Skipper: DefaultSkipper, + } +) + func proxyHTTP(t *ProxyTarget) http.Handler { return httputil.NewSingleHostReverseProxy(t.URL) } func proxyRaw(t *ProxyTarget, c echo.Context) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - h, ok := w.(http.Hijacker) - if !ok { - c.Error(errors.New("proxy raw, not a hijacker")) - return - } - in, _, err := h.Hijack() + in, _, err := c.Response().Hijack() if err != nil { - c.Error(fmt.Errorf("proxy raw, hijack error=%v, url=%s", r.URL, err)) + c.Error(fmt.Errorf("proxy raw, hijack error=%v, url=%s", t.URL, err)) return } defer in.Close() out, err := net.Dial("tcp", t.URL.Host) if err != nil { - he := echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("proxy raw, dial error=%v, url=%s", r.URL, err)) + he := echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("proxy raw, dial error=%v, url=%s", t.URL, err)) c.Error(he) return } defer out.Close() + // Write header err = r.Write(out) if err != nil { - he := echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("proxy raw, request copy error=%v, url=%s", r.URL, err)) + he := echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("proxy raw, request header copy error=%v, url=%s", t.URL, err)) c.Error(he) return } @@ -97,7 +99,7 @@ func proxyRaw(t *ProxyTarget, c echo.Context) http.Handler { go cp(in, out) err = <-errc if err != nil && err != io.EOF { - c.Logger().Errorf("proxy raw, error=%v, url=%s", r.URL, err) + c.Logger().Errorf("proxy raw, copy body error=%v, url=%s", t.URL, err) } }) } @@ -118,8 +120,18 @@ func (r *RoundRobinBalancer) Next() *ProxyTarget { return t } -// Proxy returns an HTTP/WebSocket reverse proxy middleware. -func Proxy(config ProxyConfig) echo.MiddlewareFunc { +// Proxy returns a Proxy middleware. +// +// Proxy middleware forwards the request to upstream server using a configured load balancing technique. +func Proxy(balancer ProxyBalancer) echo.MiddlewareFunc { + c := DefaultProxyConfig + c.Balancer = balancer + return ProxyWithConfig(c) +} + +// ProxyWithConfig returns a Proxy middleware with config. +// See: `Proxy()` +func ProxyWithConfig(config ProxyConfig) echo.MiddlewareFunc { // Defaults if config.Skipper == nil { config.Skipper = DefaultLoggerConfig.Skipper @@ -130,6 +142,10 @@ func Proxy(config ProxyConfig) echo.MiddlewareFunc { return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) (err error) { + if config.Skipper(c) { + return next(c) + } + req := c.Request() res := c.Response() tgt := config.Balancer.Next() diff --git a/vendor/github.com/labstack/echo/middleware/recover.go b/vendor/github.com/labstack/echo/middleware/recover.go index 96fa62c9..687a198a 100644 --- a/vendor/github.com/labstack/echo/middleware/recover.go +++ b/vendor/github.com/labstack/echo/middleware/recover.go @@ -5,7 +5,6 @@ import ( "runtime" "github.com/labstack/echo" - "github.com/labstack/gommon/color" ) type ( @@ -64,17 +63,14 @@ func RecoverWithConfig(config RecoverConfig) echo.MiddlewareFunc { defer func() { if r := recover(); r != nil { - var err error - switch r := r.(type) { - case error: - err = r - default: + err, ok := r.(error) + if !ok { err = fmt.Errorf("%v", r) } stack := make([]byte, config.StackSize) length := runtime.Stack(stack, !config.DisableStackAll) if !config.DisablePrintStack { - c.Logger().Printf("[%s] %s %s\n", color.Red("PANIC RECOVER"), err, stack[:length]) + c.Logger().Printf("[PANIC RECOVER] %v %s\n", err, stack[:length]) } c.Error(err) } diff --git a/vendor/github.com/labstack/echo/middleware/static.go b/vendor/github.com/labstack/echo/middleware/static.go index e715c1c4..29686e0c 100644 --- a/vendor/github.com/labstack/echo/middleware/static.go +++ b/vendor/github.com/labstack/echo/middleware/static.go @@ -2,6 +2,7 @@ package middleware import ( "fmt" + "net/http" "os" "path" "path/filepath" @@ -66,7 +67,7 @@ func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc { } return func(next echo.HandlerFunc) echo.HandlerFunc { - return func(c echo.Context) error { + return func(c echo.Context) (err error) { if config.Skipper(c) { return next(c) } @@ -75,17 +76,25 @@ func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc { if strings.HasSuffix(c.Path(), "*") { // When serving from a group, e.g. `/static*`. p = c.Param("*") } + p, err = echo.PathUnescape(p) + if err != nil { + return + } name := filepath.Join(config.Root, path.Clean("/"+p)) // "/"+ for security fi, err := os.Stat(name) if err != nil { if os.IsNotExist(err) { - if config.HTML5 && path.Ext(p) == "" { - return c.File(filepath.Join(config.Root, config.Index)) + if err = next(c); err != nil { + if he, ok := err.(*echo.HTTPError); ok { + if config.HTML5 && he.Code == http.StatusNotFound { + return c.File(filepath.Join(config.Root, config.Index)) + } + } + return } - return next(c) } - return err + return } if fi.IsDir() { @@ -99,7 +108,7 @@ func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc { if os.IsNotExist(err) { return next(c) } - return err + return } return c.File(index) @@ -110,20 +119,20 @@ func StaticWithConfig(config StaticConfig) echo.MiddlewareFunc { } } -func listDir(name string, res *echo.Response) error { +func listDir(name string, res *echo.Response) (err error) { dir, err := os.Open(name) if err != nil { - return err + return } dirs, err := dir.Readdir(-1) if err != nil { - return err + return } // Create a directory index res.Header().Set(echo.HeaderContentType, echo.MIMETextHTMLCharsetUTF8) if _, err = fmt.Fprintf(res, "<pre>\n"); err != nil { - return err + return } for _, d := range dirs { name := d.Name() @@ -133,9 +142,9 @@ func listDir(name string, res *echo.Response) error { name += "/" } if _, err = fmt.Fprintf(res, "<a href=\"%s\" style=\"color: %s;\">%s</a>\n", name, color, name); err != nil { - return err + return } } _, err = fmt.Fprintf(res, "</pre>\n") - return err + return } |