2017-02-18 14:00:46 -08:00
|
|
|
/*
|
|
|
|
Package echo implements high performance, minimalist Go web framework.
|
|
|
|
|
|
|
|
Example:
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2019-01-31 08:06:36 -08:00
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
"github.com/labstack/echo/v4/middleware"
|
2017-02-18 14:00:46 -08:00
|
|
|
)
|
|
|
|
|
|
|
|
// Handler
|
|
|
|
func hello(c echo.Context) error {
|
|
|
|
return c.String(http.StatusOK, "Hello, World!")
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
// Echo instance
|
|
|
|
e := echo.New()
|
|
|
|
|
|
|
|
// Middleware
|
|
|
|
e.Use(middleware.Logger())
|
|
|
|
e.Use(middleware.Recover())
|
|
|
|
|
|
|
|
// Routes
|
|
|
|
e.GET("/", hello)
|
|
|
|
|
|
|
|
// Start server
|
|
|
|
e.Logger.Fatal(e.Start(":1323"))
|
|
|
|
}
|
|
|
|
|
|
|
|
Learn more at https://echo.labstack.com
|
|
|
|
*/
|
|
|
|
package echo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2018-11-18 09:55:05 -08:00
|
|
|
stdContext "context"
|
2017-02-18 14:00:46 -08:00
|
|
|
"crypto/tls"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2019-06-16 14:33:25 -07:00
|
|
|
"io/ioutil"
|
2017-06-05 15:01:05 -07:00
|
|
|
stdLog "log"
|
2017-02-18 14:00:46 -08:00
|
|
|
"net"
|
|
|
|
"net/http"
|
2018-11-18 09:55:05 -08:00
|
|
|
"net/url"
|
2020-09-04 14:29:13 -07:00
|
|
|
"os"
|
2017-06-05 15:01:05 -07:00
|
|
|
"path/filepath"
|
2017-02-18 14:00:46 -08:00
|
|
|
"reflect"
|
|
|
|
"runtime"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/labstack/gommon/color"
|
|
|
|
"github.com/labstack/gommon/log"
|
2019-06-16 14:33:25 -07:00
|
|
|
"golang.org/x/crypto/acme"
|
2017-02-18 14:00:46 -08:00
|
|
|
"golang.org/x/crypto/acme/autocert"
|
2020-05-23 15:06:21 -07:00
|
|
|
"golang.org/x/net/http2"
|
|
|
|
"golang.org/x/net/http2/h2c"
|
2017-02-18 14:00:46 -08:00
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
// Echo is the top-level framework instance.
|
|
|
|
Echo struct {
|
2019-06-16 14:33:25 -07:00
|
|
|
common
|
2021-03-20 14:40:23 -07:00
|
|
|
// startupMutex is mutex to lock Echo instance access during server configuration and startup. Useful for to get
|
|
|
|
// listener address info (on which interface/port was listener binded) without having data races.
|
|
|
|
startupMutex sync.RWMutex
|
2019-01-31 08:06:36 -08:00
|
|
|
StdLogger *stdLog.Logger
|
2017-02-18 14:00:46 -08:00
|
|
|
colorer *color.Color
|
|
|
|
premiddleware []MiddlewareFunc
|
|
|
|
middleware []MiddlewareFunc
|
|
|
|
maxParam *int
|
|
|
|
router *Router
|
2019-06-16 14:33:25 -07:00
|
|
|
routers map[string]*Router
|
2017-02-18 14:00:46 -08:00
|
|
|
notFoundHandler HandlerFunc
|
|
|
|
pool sync.Pool
|
|
|
|
Server *http.Server
|
|
|
|
TLSServer *http.Server
|
|
|
|
Listener net.Listener
|
|
|
|
TLSListener net.Listener
|
2017-12-07 14:00:56 -08:00
|
|
|
AutoTLSManager autocert.Manager
|
2017-02-18 14:00:46 -08:00
|
|
|
DisableHTTP2 bool
|
|
|
|
Debug bool
|
2017-06-05 15:01:05 -07:00
|
|
|
HideBanner bool
|
2018-02-20 15:48:10 -08:00
|
|
|
HidePort bool
|
2017-02-18 14:00:46 -08:00
|
|
|
HTTPErrorHandler HTTPErrorHandler
|
|
|
|
Binder Binder
|
2021-07-31 09:27:55 -07:00
|
|
|
JSONSerializer JSONSerializer
|
2017-02-18 14:00:46 -08:00
|
|
|
Validator Validator
|
|
|
|
Renderer Renderer
|
2018-11-18 09:55:05 -08:00
|
|
|
Logger Logger
|
2020-05-23 15:06:21 -07:00
|
|
|
IPExtractor IPExtractor
|
2021-03-20 14:40:23 -07:00
|
|
|
ListenerNetwork string
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Route contains a handler and information for matching against requests.
|
|
|
|
Route struct {
|
2017-12-07 14:00:56 -08:00
|
|
|
Method string `json:"method"`
|
|
|
|
Path string `json:"path"`
|
|
|
|
Name string `json:"name"`
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// HTTPError represents an error that occurred while handling a request.
|
|
|
|
HTTPError struct {
|
2019-09-07 13:46:58 -07:00
|
|
|
Code int `json:"-"`
|
|
|
|
Message interface{} `json:"message"`
|
|
|
|
Internal error `json:"-"` // Stores the error returned by an external dependency
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// MiddlewareFunc defines a function to process middleware.
|
|
|
|
MiddlewareFunc func(HandlerFunc) HandlerFunc
|
|
|
|
|
2019-01-31 08:06:36 -08:00
|
|
|
// HandlerFunc defines a function to serve HTTP requests.
|
2017-02-18 14:00:46 -08:00
|
|
|
HandlerFunc func(Context) error
|
|
|
|
|
|
|
|
// HTTPErrorHandler is a centralized HTTP error handler.
|
|
|
|
HTTPErrorHandler func(error, Context)
|
|
|
|
|
|
|
|
// Validator is the interface that wraps the Validate function.
|
|
|
|
Validator interface {
|
|
|
|
Validate(i interface{}) error
|
|
|
|
}
|
|
|
|
|
2021-07-31 09:27:55 -07:00
|
|
|
// JSONSerializer is the interface that encodes and decodes JSON to and from interfaces.
|
|
|
|
JSONSerializer interface {
|
|
|
|
Serialize(c Context, i interface{}, indent string) error
|
|
|
|
Deserialize(c Context, i interface{}) error
|
|
|
|
}
|
|
|
|
|
2017-02-18 14:00:46 -08:00
|
|
|
// Renderer is the interface that wraps the Render function.
|
|
|
|
Renderer interface {
|
|
|
|
Render(io.Writer, string, interface{}, Context) error
|
|
|
|
}
|
|
|
|
|
|
|
|
// Map defines a generic map of type `map[string]interface{}`.
|
|
|
|
Map map[string]interface{}
|
|
|
|
|
2019-06-16 14:33:25 -07:00
|
|
|
// Common struct for Echo & Group.
|
|
|
|
common struct{}
|
2017-02-18 14:00:46 -08:00
|
|
|
)
|
|
|
|
|
|
|
|
// HTTP methods
|
2019-01-31 08:06:36 -08:00
|
|
|
// NOTE: Deprecated, please use the stdlib constants directly instead.
|
2017-02-18 14:00:46 -08:00
|
|
|
const (
|
2019-01-31 08:06:36 -08:00
|
|
|
CONNECT = http.MethodConnect
|
|
|
|
DELETE = http.MethodDelete
|
|
|
|
GET = http.MethodGet
|
|
|
|
HEAD = http.MethodHead
|
|
|
|
OPTIONS = http.MethodOptions
|
|
|
|
PATCH = http.MethodPatch
|
|
|
|
POST = http.MethodPost
|
|
|
|
// PROPFIND = "PROPFIND"
|
|
|
|
PUT = http.MethodPut
|
|
|
|
TRACE = http.MethodTrace
|
2017-02-18 14:00:46 -08:00
|
|
|
)
|
|
|
|
|
|
|
|
// MIME types
|
|
|
|
const (
|
|
|
|
MIMEApplicationJSON = "application/json"
|
|
|
|
MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8
|
|
|
|
MIMEApplicationJavaScript = "application/javascript"
|
|
|
|
MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
|
|
|
|
MIMEApplicationXML = "application/xml"
|
|
|
|
MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + charsetUTF8
|
2017-06-05 15:01:05 -07:00
|
|
|
MIMETextXML = "text/xml"
|
|
|
|
MIMETextXMLCharsetUTF8 = MIMETextXML + "; " + charsetUTF8
|
2017-02-18 14:00:46 -08:00
|
|
|
MIMEApplicationForm = "application/x-www-form-urlencoded"
|
|
|
|
MIMEApplicationProtobuf = "application/protobuf"
|
|
|
|
MIMEApplicationMsgpack = "application/msgpack"
|
|
|
|
MIMETextHTML = "text/html"
|
|
|
|
MIMETextHTMLCharsetUTF8 = MIMETextHTML + "; " + charsetUTF8
|
|
|
|
MIMETextPlain = "text/plain"
|
|
|
|
MIMETextPlainCharsetUTF8 = MIMETextPlain + "; " + charsetUTF8
|
|
|
|
MIMEMultipartForm = "multipart/form-data"
|
|
|
|
MIMEOctetStream = "application/octet-stream"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
charsetUTF8 = "charset=UTF-8"
|
2019-01-31 08:06:36 -08:00
|
|
|
// PROPFIND Method can be used on collection and property resources.
|
|
|
|
PROPFIND = "PROPFIND"
|
2019-06-16 14:33:25 -07:00
|
|
|
// REPORT Method can be used to get information about a resource, see rfc 3253
|
|
|
|
REPORT = "REPORT"
|
2017-02-18 14:00:46 -08:00
|
|
|
)
|
|
|
|
|
|
|
|
// Headers
|
|
|
|
const (
|
2017-06-05 15:01:05 -07:00
|
|
|
HeaderAccept = "Accept"
|
|
|
|
HeaderAcceptEncoding = "Accept-Encoding"
|
|
|
|
HeaderAllow = "Allow"
|
|
|
|
HeaderAuthorization = "Authorization"
|
|
|
|
HeaderContentDisposition = "Content-Disposition"
|
|
|
|
HeaderContentEncoding = "Content-Encoding"
|
|
|
|
HeaderContentLength = "Content-Length"
|
|
|
|
HeaderContentType = "Content-Type"
|
|
|
|
HeaderCookie = "Cookie"
|
|
|
|
HeaderSetCookie = "Set-Cookie"
|
|
|
|
HeaderIfModifiedSince = "If-Modified-Since"
|
|
|
|
HeaderLastModified = "Last-Modified"
|
|
|
|
HeaderLocation = "Location"
|
|
|
|
HeaderUpgrade = "Upgrade"
|
|
|
|
HeaderVary = "Vary"
|
|
|
|
HeaderWWWAuthenticate = "WWW-Authenticate"
|
|
|
|
HeaderXForwardedFor = "X-Forwarded-For"
|
|
|
|
HeaderXForwardedProto = "X-Forwarded-Proto"
|
|
|
|
HeaderXForwardedProtocol = "X-Forwarded-Protocol"
|
|
|
|
HeaderXForwardedSsl = "X-Forwarded-Ssl"
|
|
|
|
HeaderXUrlScheme = "X-Url-Scheme"
|
|
|
|
HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
|
|
|
|
HeaderXRealIP = "X-Real-IP"
|
|
|
|
HeaderXRequestID = "X-Request-ID"
|
2022-01-18 11:42:25 -08:00
|
|
|
HeaderXCorrelationID = "X-Correlation-ID"
|
2018-11-18 09:55:05 -08:00
|
|
|
HeaderXRequestedWith = "X-Requested-With"
|
2017-06-05 15:01:05 -07:00
|
|
|
HeaderServer = "Server"
|
|
|
|
HeaderOrigin = "Origin"
|
|
|
|
|
|
|
|
// Access control
|
2017-02-18 14:00:46 -08:00
|
|
|
HeaderAccessControlRequestMethod = "Access-Control-Request-Method"
|
|
|
|
HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers"
|
|
|
|
HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin"
|
|
|
|
HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods"
|
|
|
|
HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers"
|
|
|
|
HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
|
|
|
|
HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers"
|
|
|
|
HeaderAccessControlMaxAge = "Access-Control-Max-Age"
|
|
|
|
|
|
|
|
// Security
|
2019-06-16 14:33:25 -07:00
|
|
|
HeaderStrictTransportSecurity = "Strict-Transport-Security"
|
|
|
|
HeaderXContentTypeOptions = "X-Content-Type-Options"
|
|
|
|
HeaderXXSSProtection = "X-XSS-Protection"
|
|
|
|
HeaderXFrameOptions = "X-Frame-Options"
|
|
|
|
HeaderContentSecurityPolicy = "Content-Security-Policy"
|
|
|
|
HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
|
|
|
|
HeaderXCSRFToken = "X-CSRF-Token"
|
2019-09-07 13:46:58 -07:00
|
|
|
HeaderReferrerPolicy = "Referrer-Policy"
|
2017-02-18 14:00:46 -08:00
|
|
|
)
|
|
|
|
|
2017-06-05 15:01:05 -07:00
|
|
|
const (
|
2019-01-31 08:06:36 -08:00
|
|
|
// Version of Echo
|
2022-01-18 11:42:25 -08:00
|
|
|
Version = "4.6.3"
|
2017-06-05 15:01:05 -07:00
|
|
|
website = "https://echo.labstack.com"
|
|
|
|
// http://patorjk.com/software/taag/#p=display&f=Small%20Slant&t=Echo
|
|
|
|
banner = `
|
|
|
|
____ __
|
|
|
|
/ __/___/ / ___
|
|
|
|
/ _// __/ _ \/ _ \
|
|
|
|
/___/\__/_//_/\___/ %s
|
|
|
|
High performance, minimalist Go web framework
|
|
|
|
%s
|
|
|
|
____________________________________O/_______
|
|
|
|
O\
|
|
|
|
`
|
|
|
|
)
|
|
|
|
|
2017-02-18 14:00:46 -08:00
|
|
|
var (
|
|
|
|
methods = [...]string{
|
2019-01-31 08:06:36 -08:00
|
|
|
http.MethodConnect,
|
|
|
|
http.MethodDelete,
|
|
|
|
http.MethodGet,
|
|
|
|
http.MethodHead,
|
|
|
|
http.MethodOptions,
|
|
|
|
http.MethodPatch,
|
|
|
|
http.MethodPost,
|
2018-11-18 09:55:05 -08:00
|
|
|
PROPFIND,
|
2019-01-31 08:06:36 -08:00
|
|
|
http.MethodPut,
|
|
|
|
http.MethodTrace,
|
2019-06-16 14:33:25 -07:00
|
|
|
REPORT,
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
// Errors
|
|
|
|
var (
|
|
|
|
ErrUnsupportedMediaType = NewHTTPError(http.StatusUnsupportedMediaType)
|
|
|
|
ErrNotFound = NewHTTPError(http.StatusNotFound)
|
|
|
|
ErrUnauthorized = NewHTTPError(http.StatusUnauthorized)
|
2017-06-05 15:01:05 -07:00
|
|
|
ErrForbidden = NewHTTPError(http.StatusForbidden)
|
2017-02-18 14:00:46 -08:00
|
|
|
ErrMethodNotAllowed = NewHTTPError(http.StatusMethodNotAllowed)
|
|
|
|
ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge)
|
2019-01-31 08:06:36 -08:00
|
|
|
ErrTooManyRequests = NewHTTPError(http.StatusTooManyRequests)
|
|
|
|
ErrBadRequest = NewHTTPError(http.StatusBadRequest)
|
|
|
|
ErrBadGateway = NewHTTPError(http.StatusBadGateway)
|
|
|
|
ErrInternalServerError = NewHTTPError(http.StatusInternalServerError)
|
|
|
|
ErrRequestTimeout = NewHTTPError(http.StatusRequestTimeout)
|
|
|
|
ErrServiceUnavailable = NewHTTPError(http.StatusServiceUnavailable)
|
2018-11-18 09:55:05 -08:00
|
|
|
ErrValidatorNotRegistered = errors.New("validator not registered")
|
|
|
|
ErrRendererNotRegistered = errors.New("renderer not registered")
|
|
|
|
ErrInvalidRedirectCode = errors.New("invalid redirect status code")
|
|
|
|
ErrCookieNotFound = errors.New("cookie not found")
|
2019-06-16 14:33:25 -07:00
|
|
|
ErrInvalidCertOrKeyType = errors.New("invalid cert or key type, must be string or []byte")
|
2021-03-20 14:40:23 -07:00
|
|
|
ErrInvalidListenerNetwork = errors.New("invalid listener network")
|
2017-02-18 14:00:46 -08:00
|
|
|
)
|
|
|
|
|
|
|
|
// Error handlers
|
|
|
|
var (
|
|
|
|
NotFoundHandler = func(c Context) error {
|
|
|
|
return ErrNotFound
|
|
|
|
}
|
|
|
|
|
|
|
|
MethodNotAllowedHandler = func(c Context) error {
|
|
|
|
return ErrMethodNotAllowed
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
// New creates an instance of Echo.
|
|
|
|
func New() (e *Echo) {
|
|
|
|
e = &Echo{
|
|
|
|
Server: new(http.Server),
|
|
|
|
TLSServer: new(http.Server),
|
|
|
|
AutoTLSManager: autocert.Manager{
|
|
|
|
Prompt: autocert.AcceptTOS,
|
|
|
|
},
|
2021-03-20 14:40:23 -07:00
|
|
|
Logger: log.New("echo"),
|
|
|
|
colorer: color.New(),
|
|
|
|
maxParam: new(int),
|
|
|
|
ListenerNetwork: "tcp",
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
e.Server.Handler = e
|
|
|
|
e.TLSServer.Handler = e
|
|
|
|
e.HTTPErrorHandler = e.DefaultHTTPErrorHandler
|
|
|
|
e.Binder = &DefaultBinder{}
|
2021-07-31 09:27:55 -07:00
|
|
|
e.JSONSerializer = &DefaultJSONSerializer{}
|
2017-12-07 14:00:56 -08:00
|
|
|
e.Logger.SetLevel(log.ERROR)
|
2019-01-31 08:06:36 -08:00
|
|
|
e.StdLogger = stdLog.New(e.Logger.Output(), e.Logger.Prefix()+": ", 0)
|
2017-02-18 14:00:46 -08:00
|
|
|
e.pool.New = func() interface{} {
|
|
|
|
return e.NewContext(nil, nil)
|
|
|
|
}
|
|
|
|
e.router = NewRouter(e)
|
2019-06-16 14:33:25 -07:00
|
|
|
e.routers = map[string]*Router{}
|
2017-02-18 14:00:46 -08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewContext returns a Context instance.
|
|
|
|
func (e *Echo) NewContext(r *http.Request, w http.ResponseWriter) Context {
|
|
|
|
return &context{
|
|
|
|
request: r,
|
|
|
|
response: NewResponse(w, e),
|
|
|
|
store: make(Map),
|
|
|
|
echo: e,
|
|
|
|
pvalues: make([]string, *e.maxParam),
|
|
|
|
handler: NotFoundHandler,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-16 14:33:25 -07:00
|
|
|
// Router returns the default router.
|
2017-02-18 14:00:46 -08:00
|
|
|
func (e *Echo) Router() *Router {
|
|
|
|
return e.router
|
|
|
|
}
|
|
|
|
|
2019-06-16 14:33:25 -07:00
|
|
|
// Routers returns the map of host => router.
|
|
|
|
func (e *Echo) Routers() map[string]*Router {
|
|
|
|
return e.routers
|
|
|
|
}
|
|
|
|
|
2017-02-18 14:00:46 -08:00
|
|
|
// DefaultHTTPErrorHandler is the default HTTP error handler. It sends a JSON response
|
|
|
|
// with status code.
|
2021-10-16 15:47:22 -07:00
|
|
|
//
|
|
|
|
// NOTE: In case errors happens in middleware call-chain that is returning from handler (which did not return an error).
|
|
|
|
// When handler has already sent response (ala c.JSON()) and there is error in middleware that is returning from
|
|
|
|
// handler. Then the error that global error handler received will be ignored because we have already "commited" the
|
|
|
|
// response and status code header has been sent to the client.
|
2017-02-18 14:00:46 -08:00
|
|
|
func (e *Echo) DefaultHTTPErrorHandler(err error, c Context) {
|
2021-10-16 15:47:22 -07:00
|
|
|
|
|
|
|
if c.Response().Committed {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-09-07 13:46:58 -07:00
|
|
|
he, ok := err.(*HTTPError)
|
|
|
|
if ok {
|
2018-11-18 09:55:05 -08:00
|
|
|
if he.Internal != nil {
|
2019-09-07 13:46:58 -07:00
|
|
|
if herr, ok := he.Internal.(*HTTPError); ok {
|
|
|
|
he = herr
|
|
|
|
}
|
2017-12-07 14:00:56 -08:00
|
|
|
}
|
2017-02-18 14:00:46 -08:00
|
|
|
} else {
|
2019-09-07 13:46:58 -07:00
|
|
|
he = &HTTPError{
|
|
|
|
Code: http.StatusInternalServerError,
|
|
|
|
Message: http.StatusText(http.StatusInternalServerError),
|
|
|
|
}
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
2020-01-09 12:02:56 -08:00
|
|
|
|
|
|
|
// Issue #1426
|
|
|
|
code := he.Code
|
|
|
|
message := he.Message
|
2021-03-20 14:40:23 -07:00
|
|
|
if m, ok := he.Message.(string); ok {
|
|
|
|
if e.Debug {
|
|
|
|
message = Map{"message": m, "error": err.Error()}
|
|
|
|
} else {
|
|
|
|
message = Map{"message": m}
|
|
|
|
}
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
2017-12-07 14:00:56 -08:00
|
|
|
// Send response
|
2021-10-16 15:47:22 -07:00
|
|
|
if c.Request().Method == http.MethodHead { // Issue #608
|
|
|
|
err = c.NoContent(he.Code)
|
|
|
|
} else {
|
|
|
|
err = c.JSON(code, message)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
e.Logger.Error(err)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Pre adds middleware to the chain which is run before router.
|
|
|
|
func (e *Echo) Pre(middleware ...MiddlewareFunc) {
|
|
|
|
e.premiddleware = append(e.premiddleware, middleware...)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Use adds middleware to the chain which is run after router.
|
|
|
|
func (e *Echo) Use(middleware ...MiddlewareFunc) {
|
|
|
|
e.middleware = append(e.middleware, middleware...)
|
|
|
|
}
|
|
|
|
|
|
|
|
// CONNECT registers a new CONNECT route for a path with matching handler in the
|
|
|
|
// router with optional route-level middleware.
|
2017-12-07 14:00:56 -08:00
|
|
|
func (e *Echo) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
|
2019-01-31 08:06:36 -08:00
|
|
|
return e.Add(http.MethodConnect, path, h, m...)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// DELETE registers a new DELETE route for a path with matching handler in the router
|
|
|
|
// with optional route-level middleware.
|
2017-12-07 14:00:56 -08:00
|
|
|
func (e *Echo) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
|
2019-01-31 08:06:36 -08:00
|
|
|
return e.Add(http.MethodDelete, path, h, m...)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// GET registers a new GET route for a path with matching handler in the router
|
|
|
|
// with optional route-level middleware.
|
2017-12-07 14:00:56 -08:00
|
|
|
func (e *Echo) GET(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
|
2019-01-31 08:06:36 -08:00
|
|
|
return e.Add(http.MethodGet, path, h, m...)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// HEAD registers a new HEAD route for a path with matching handler in the
|
|
|
|
// router with optional route-level middleware.
|
2017-12-07 14:00:56 -08:00
|
|
|
func (e *Echo) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
|
2019-01-31 08:06:36 -08:00
|
|
|
return e.Add(http.MethodHead, path, h, m...)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// OPTIONS registers a new OPTIONS route for a path with matching handler in the
|
|
|
|
// router with optional route-level middleware.
|
2017-12-07 14:00:56 -08:00
|
|
|
func (e *Echo) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
|
2019-01-31 08:06:36 -08:00
|
|
|
return e.Add(http.MethodOptions, path, h, m...)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// PATCH registers a new PATCH route for a path with matching handler in the
|
|
|
|
// router with optional route-level middleware.
|
2017-12-07 14:00:56 -08:00
|
|
|
func (e *Echo) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
|
2019-01-31 08:06:36 -08:00
|
|
|
return e.Add(http.MethodPatch, path, h, m...)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// POST registers a new POST route for a path with matching handler in the
|
|
|
|
// router with optional route-level middleware.
|
2017-12-07 14:00:56 -08:00
|
|
|
func (e *Echo) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
|
2019-01-31 08:06:36 -08:00
|
|
|
return e.Add(http.MethodPost, path, h, m...)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// PUT registers a new PUT route for a path with matching handler in the
|
|
|
|
// router with optional route-level middleware.
|
2017-12-07 14:00:56 -08:00
|
|
|
func (e *Echo) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
|
2019-01-31 08:06:36 -08:00
|
|
|
return e.Add(http.MethodPut, path, h, m...)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// TRACE registers a new TRACE route for a path with matching handler in the
|
|
|
|
// router with optional route-level middleware.
|
2017-12-07 14:00:56 -08:00
|
|
|
func (e *Echo) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
|
2019-01-31 08:06:36 -08:00
|
|
|
return e.Add(http.MethodTrace, path, h, m...)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Any registers a new route for all HTTP methods and path with matching handler
|
|
|
|
// in the router with optional route-level middleware.
|
2017-12-07 14:00:56 -08:00
|
|
|
func (e *Echo) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route {
|
2018-02-20 15:48:10 -08:00
|
|
|
routes := make([]*Route, len(methods))
|
|
|
|
for i, m := range methods {
|
|
|
|
routes[i] = e.Add(m, path, handler, middleware...)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
2017-12-07 14:00:56 -08:00
|
|
|
return routes
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Match registers a new route for multiple HTTP methods and path with matching
|
|
|
|
// handler in the router with optional route-level middleware.
|
2017-12-07 14:00:56 -08:00
|
|
|
func (e *Echo) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route {
|
2018-02-20 15:48:10 -08:00
|
|
|
routes := make([]*Route, len(methods))
|
|
|
|
for i, m := range methods {
|
|
|
|
routes[i] = e.Add(m, path, handler, middleware...)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
2017-12-07 14:00:56 -08:00
|
|
|
return routes
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Static registers a new route with path prefix to serve static files from the
|
|
|
|
// provided root directory.
|
2017-12-07 14:00:56 -08:00
|
|
|
func (e *Echo) Static(prefix, root string) *Route {
|
2017-06-05 15:01:05 -07:00
|
|
|
if root == "" {
|
|
|
|
root = "." // For security we want to restrict to CWD.
|
|
|
|
}
|
2019-06-16 14:33:25 -07:00
|
|
|
return e.static(prefix, root, e.GET)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
2019-06-16 14:33:25 -07:00
|
|
|
func (common) static(prefix, root string, get func(string, HandlerFunc, ...MiddlewareFunc) *Route) *Route {
|
2017-02-18 14:00:46 -08:00
|
|
|
h := func(c Context) error {
|
2018-11-18 09:55:05 -08:00
|
|
|
p, err := url.PathUnescape(c.Param("*"))
|
2017-12-07 14:00:56 -08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-09-04 14:29:13 -07:00
|
|
|
|
2021-03-20 14:40:23 -07:00
|
|
|
name := filepath.Join(root, filepath.Clean("/"+p)) // "/"+ for security
|
2020-09-04 14:29:13 -07:00
|
|
|
fi, err := os.Stat(name)
|
|
|
|
if err != nil {
|
|
|
|
// The access path does not exist
|
|
|
|
return NotFoundHandler(c)
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the request is for a directory and does not end with "/"
|
|
|
|
p = c.Request().URL.Path // path must not be empty.
|
|
|
|
if fi.IsDir() && p[len(p)-1] != '/' {
|
|
|
|
// Redirect to ends with "/"
|
|
|
|
return c.Redirect(http.StatusMovedPermanently, p+"/")
|
|
|
|
}
|
2017-06-05 15:01:05 -07:00
|
|
|
return c.File(name)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
2021-03-20 14:40:23 -07:00
|
|
|
// Handle added routes based on trailing slash:
|
|
|
|
// /prefix => exact route "/prefix" + any route "/prefix/*"
|
|
|
|
// /prefix/ => only any route "/prefix/*"
|
|
|
|
if prefix != "" {
|
|
|
|
if prefix[len(prefix)-1] == '/' {
|
|
|
|
// Only add any route for intentional trailing slash
|
|
|
|
return get(prefix+"*", h)
|
|
|
|
}
|
|
|
|
get(prefix, h)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
2019-06-16 14:33:25 -07:00
|
|
|
return get(prefix+"/*", h)
|
|
|
|
}
|
2017-12-07 14:00:56 -08:00
|
|
|
|
2019-06-16 14:33:25 -07:00
|
|
|
func (common) file(path, file string, get func(string, HandlerFunc, ...MiddlewareFunc) *Route,
|
|
|
|
m ...MiddlewareFunc) *Route {
|
|
|
|
return get(path, func(c Context) error {
|
|
|
|
return c.File(file)
|
|
|
|
}, m...)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
2019-01-31 08:06:36 -08:00
|
|
|
// File registers a new route with path to serve a static file with optional route-level middleware.
|
|
|
|
func (e *Echo) File(path, file string, m ...MiddlewareFunc) *Route {
|
2019-06-16 14:33:25 -07:00
|
|
|
return e.file(path, file, e.GET, m...)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
2019-06-16 14:33:25 -07:00
|
|
|
func (e *Echo) add(host, method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route {
|
2017-02-18 14:00:46 -08:00
|
|
|
name := handlerName(handler)
|
2019-06-16 14:33:25 -07:00
|
|
|
router := e.findRouter(host)
|
|
|
|
router.Add(method, path, func(c Context) error {
|
2020-09-04 14:29:13 -07:00
|
|
|
h := applyMiddleware(handler, middleware...)
|
2017-02-18 14:00:46 -08:00
|
|
|
return h(c)
|
|
|
|
})
|
2017-06-05 15:01:05 -07:00
|
|
|
r := &Route{
|
2017-12-07 14:00:56 -08:00
|
|
|
Method: method,
|
|
|
|
Path: path,
|
|
|
|
Name: name,
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
e.router.routes[method+path] = r
|
2017-12-07 14:00:56 -08:00
|
|
|
return r
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
2019-06-16 14:33:25 -07:00
|
|
|
// Add registers a new route for an HTTP method and path with matching handler
|
|
|
|
// in the router with optional route-level middleware.
|
|
|
|
func (e *Echo) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route {
|
|
|
|
return e.add("", method, path, handler, middleware...)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Host creates a new router group for the provided host and optional host-level middleware.
|
|
|
|
func (e *Echo) Host(name string, m ...MiddlewareFunc) (g *Group) {
|
|
|
|
e.routers[name] = NewRouter(e)
|
|
|
|
g = &Group{host: name, echo: e}
|
|
|
|
g.Use(m...)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-02-18 14:00:46 -08:00
|
|
|
// Group creates a new router group with prefix and optional group-level middleware.
|
|
|
|
func (e *Echo) Group(prefix string, m ...MiddlewareFunc) (g *Group) {
|
|
|
|
g = &Group{prefix: prefix, echo: e}
|
|
|
|
g.Use(m...)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// URI generates a URI from handler.
|
|
|
|
func (e *Echo) URI(handler HandlerFunc, params ...interface{}) string {
|
2017-12-07 14:00:56 -08:00
|
|
|
name := handlerName(handler)
|
|
|
|
return e.Reverse(name, params...)
|
|
|
|
}
|
|
|
|
|
|
|
|
// URL is an alias for `URI` function.
|
|
|
|
func (e *Echo) URL(h HandlerFunc, params ...interface{}) string {
|
|
|
|
return e.URI(h, params...)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reverse generates an URL from route name and provided parameters.
|
|
|
|
func (e *Echo) Reverse(name string, params ...interface{}) string {
|
2017-02-18 14:00:46 -08:00
|
|
|
uri := new(bytes.Buffer)
|
|
|
|
ln := len(params)
|
|
|
|
n := 0
|
|
|
|
for _, r := range e.router.routes {
|
2017-12-07 14:00:56 -08:00
|
|
|
if r.Name == name {
|
2017-02-18 14:00:46 -08:00
|
|
|
for i, l := 0, len(r.Path); i < l; i++ {
|
2021-03-20 14:40:23 -07:00
|
|
|
if (r.Path[i] == ':' || r.Path[i] == '*') && n < ln {
|
2017-02-18 14:00:46 -08:00
|
|
|
for ; i < l && r.Path[i] != '/'; i++ {
|
|
|
|
}
|
|
|
|
uri.WriteString(fmt.Sprintf("%v", params[n]))
|
|
|
|
n++
|
|
|
|
}
|
|
|
|
if i < l {
|
|
|
|
uri.WriteByte(r.Path[i])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return uri.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Routes returns the registered routes.
|
2017-06-05 15:01:05 -07:00
|
|
|
func (e *Echo) Routes() []*Route {
|
2018-11-18 09:55:05 -08:00
|
|
|
routes := make([]*Route, 0, len(e.router.routes))
|
2017-02-18 14:00:46 -08:00
|
|
|
for _, v := range e.router.routes {
|
|
|
|
routes = append(routes, v)
|
|
|
|
}
|
|
|
|
return routes
|
|
|
|
}
|
|
|
|
|
|
|
|
// AcquireContext returns an empty `Context` instance from the pool.
|
|
|
|
// You must return the context by calling `ReleaseContext()`.
|
|
|
|
func (e *Echo) AcquireContext() Context {
|
|
|
|
return e.pool.Get().(Context)
|
|
|
|
}
|
|
|
|
|
|
|
|
// ReleaseContext returns the `Context` instance back to the pool.
|
|
|
|
// You must call it after `AcquireContext()`.
|
|
|
|
func (e *Echo) ReleaseContext(c Context) {
|
|
|
|
e.pool.Put(c)
|
|
|
|
}
|
|
|
|
|
|
|
|
// ServeHTTP implements `http.Handler` interface, which serves HTTP requests.
|
|
|
|
func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
// Acquire context
|
|
|
|
c := e.pool.Get().(*context)
|
|
|
|
c.Reset(r, w)
|
2018-11-18 09:55:05 -08:00
|
|
|
h := NotFoundHandler
|
|
|
|
|
|
|
|
if e.premiddleware == nil {
|
2020-09-04 14:29:13 -07:00
|
|
|
e.findRouter(r.Host).Find(r.Method, GetPath(r), c)
|
2018-11-18 09:55:05 -08:00
|
|
|
h = c.Handler()
|
2019-06-16 14:33:25 -07:00
|
|
|
h = applyMiddleware(h, e.middleware...)
|
2018-11-18 09:55:05 -08:00
|
|
|
} else {
|
|
|
|
h = func(c Context) error {
|
2020-09-04 14:29:13 -07:00
|
|
|
e.findRouter(r.Host).Find(r.Method, GetPath(r), c)
|
2018-11-18 09:55:05 -08:00
|
|
|
h := c.Handler()
|
2019-06-16 14:33:25 -07:00
|
|
|
h = applyMiddleware(h, e.middleware...)
|
2018-11-18 09:55:05 -08:00
|
|
|
return h(c)
|
|
|
|
}
|
2019-06-16 14:33:25 -07:00
|
|
|
h = applyMiddleware(h, e.premiddleware...)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Execute chain
|
|
|
|
if err := h(c); err != nil {
|
|
|
|
e.HTTPErrorHandler(err, c)
|
|
|
|
}
|
2018-11-18 09:55:05 -08:00
|
|
|
|
|
|
|
// Release context
|
|
|
|
e.pool.Put(c)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Start starts an HTTP server.
|
|
|
|
func (e *Echo) Start(address string) error {
|
2021-03-20 14:40:23 -07:00
|
|
|
e.startupMutex.Lock()
|
2017-02-18 14:00:46 -08:00
|
|
|
e.Server.Addr = address
|
2021-03-20 14:40:23 -07:00
|
|
|
if err := e.configureServer(e.Server); err != nil {
|
|
|
|
e.startupMutex.Unlock()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
e.startupMutex.Unlock()
|
|
|
|
return e.Server.Serve(e.Listener)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// StartTLS starts an HTTPS server.
|
2019-06-16 14:33:25 -07:00
|
|
|
// If `certFile` or `keyFile` is `string` the values are treated as file paths.
|
|
|
|
// If `certFile` or `keyFile` is `[]byte` the values are treated as the certificate or key as-is.
|
|
|
|
func (e *Echo) StartTLS(address string, certFile, keyFile interface{}) (err error) {
|
2021-03-20 14:40:23 -07:00
|
|
|
e.startupMutex.Lock()
|
2019-06-16 14:33:25 -07:00
|
|
|
var cert []byte
|
|
|
|
if cert, err = filepathOrContent(certFile); err != nil {
|
2021-03-20 14:40:23 -07:00
|
|
|
e.startupMutex.Unlock()
|
2019-06-16 14:33:25 -07:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var key []byte
|
|
|
|
if key, err = filepathOrContent(keyFile); err != nil {
|
2021-03-20 14:40:23 -07:00
|
|
|
e.startupMutex.Unlock()
|
2019-06-16 14:33:25 -07:00
|
|
|
return
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
2019-06-16 14:33:25 -07:00
|
|
|
|
2017-02-18 14:00:46 -08:00
|
|
|
s := e.TLSServer
|
|
|
|
s.TLSConfig = new(tls.Config)
|
|
|
|
s.TLSConfig.Certificates = make([]tls.Certificate, 1)
|
2019-06-16 14:33:25 -07:00
|
|
|
if s.TLSConfig.Certificates[0], err = tls.X509KeyPair(cert, key); err != nil {
|
2021-03-20 14:40:23 -07:00
|
|
|
e.startupMutex.Unlock()
|
2017-02-18 14:00:46 -08:00
|
|
|
return
|
|
|
|
}
|
2019-06-16 14:33:25 -07:00
|
|
|
|
2021-03-20 14:40:23 -07:00
|
|
|
e.configureTLS(address)
|
|
|
|
if err := e.configureServer(s); err != nil {
|
|
|
|
e.startupMutex.Unlock()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
e.startupMutex.Unlock()
|
|
|
|
return s.Serve(e.TLSListener)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
2019-06-16 14:33:25 -07:00
|
|
|
func filepathOrContent(fileOrContent interface{}) (content []byte, err error) {
|
|
|
|
switch v := fileOrContent.(type) {
|
|
|
|
case string:
|
|
|
|
return ioutil.ReadFile(v)
|
|
|
|
case []byte:
|
|
|
|
return v, nil
|
|
|
|
default:
|
|
|
|
return nil, ErrInvalidCertOrKeyType
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-02-18 14:00:46 -08:00
|
|
|
// StartAutoTLS starts an HTTPS server using certificates automatically installed from https://letsencrypt.org.
|
|
|
|
func (e *Echo) StartAutoTLS(address string) error {
|
2021-03-20 14:40:23 -07:00
|
|
|
e.startupMutex.Lock()
|
2017-02-18 14:00:46 -08:00
|
|
|
s := e.TLSServer
|
|
|
|
s.TLSConfig = new(tls.Config)
|
|
|
|
s.TLSConfig.GetCertificate = e.AutoTLSManager.GetCertificate
|
2019-06-16 14:33:25 -07:00
|
|
|
s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, acme.ALPNProto)
|
2021-03-20 14:40:23 -07:00
|
|
|
|
|
|
|
e.configureTLS(address)
|
|
|
|
if err := e.configureServer(s); err != nil {
|
|
|
|
e.startupMutex.Unlock()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
e.startupMutex.Unlock()
|
|
|
|
return s.Serve(e.TLSListener)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
2021-03-20 14:40:23 -07:00
|
|
|
func (e *Echo) configureTLS(address string) {
|
2017-02-18 14:00:46 -08:00
|
|
|
s := e.TLSServer
|
|
|
|
s.Addr = address
|
|
|
|
if !e.DisableHTTP2 {
|
|
|
|
s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "h2")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// StartServer starts a custom http server.
|
|
|
|
func (e *Echo) StartServer(s *http.Server) (err error) {
|
2021-03-20 14:40:23 -07:00
|
|
|
e.startupMutex.Lock()
|
|
|
|
if err := e.configureServer(s); err != nil {
|
|
|
|
e.startupMutex.Unlock()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if s.TLSConfig != nil {
|
|
|
|
e.startupMutex.Unlock()
|
|
|
|
return s.Serve(e.TLSListener)
|
|
|
|
}
|
|
|
|
e.startupMutex.Unlock()
|
|
|
|
return s.Serve(e.Listener)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *Echo) configureServer(s *http.Server) (err error) {
|
2017-02-18 14:00:46 -08:00
|
|
|
// Setup
|
|
|
|
e.colorer.SetOutput(e.Logger.Output())
|
2019-01-31 08:06:36 -08:00
|
|
|
s.ErrorLog = e.StdLogger
|
2017-06-05 15:01:05 -07:00
|
|
|
s.Handler = e
|
|
|
|
if e.Debug {
|
|
|
|
e.Logger.SetLevel(log.DEBUG)
|
|
|
|
}
|
|
|
|
|
|
|
|
if !e.HideBanner {
|
2018-11-18 09:55:05 -08:00
|
|
|
e.colorer.Printf(banner, e.colorer.Red("v"+Version), e.colorer.Blue(website))
|
2017-06-05 15:01:05 -07:00
|
|
|
}
|
2017-02-18 14:00:46 -08:00
|
|
|
|
|
|
|
if s.TLSConfig == nil {
|
|
|
|
if e.Listener == nil {
|
2021-03-20 14:40:23 -07:00
|
|
|
e.Listener, err = newListener(s.Addr, e.ListenerNetwork)
|
2017-02-18 14:00:46 -08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2018-02-20 15:48:10 -08:00
|
|
|
if !e.HidePort {
|
2017-06-05 15:01:05 -07:00
|
|
|
e.colorer.Printf("⇨ http server started on %s\n", e.colorer.Green(e.Listener.Addr()))
|
|
|
|
}
|
2021-03-20 14:40:23 -07:00
|
|
|
return nil
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
if e.TLSListener == nil {
|
2021-03-20 14:40:23 -07:00
|
|
|
l, err := newListener(s.Addr, e.ListenerNetwork)
|
2017-02-18 14:00:46 -08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
e.TLSListener = tls.NewListener(l, s.TLSConfig)
|
|
|
|
}
|
2018-02-20 15:48:10 -08:00
|
|
|
if !e.HidePort {
|
2017-06-05 15:01:05 -07:00
|
|
|
e.colorer.Printf("⇨ https server started on %s\n", e.colorer.Green(e.TLSListener.Addr()))
|
|
|
|
}
|
2021-03-20 14:40:23 -07:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ListenerAddr returns net.Addr for Listener
|
|
|
|
func (e *Echo) ListenerAddr() net.Addr {
|
|
|
|
e.startupMutex.RLock()
|
|
|
|
defer e.startupMutex.RUnlock()
|
|
|
|
if e.Listener == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return e.Listener.Addr()
|
|
|
|
}
|
|
|
|
|
|
|
|
// TLSListenerAddr returns net.Addr for TLSListener
|
|
|
|
func (e *Echo) TLSListenerAddr() net.Addr {
|
|
|
|
e.startupMutex.RLock()
|
|
|
|
defer e.startupMutex.RUnlock()
|
|
|
|
if e.TLSListener == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return e.TLSListener.Addr()
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
2020-05-23 15:06:21 -07:00
|
|
|
// StartH2CServer starts a custom http/2 server with h2c (HTTP/2 Cleartext).
|
|
|
|
func (e *Echo) StartH2CServer(address string, h2s *http2.Server) (err error) {
|
2021-03-20 14:40:23 -07:00
|
|
|
e.startupMutex.Lock()
|
2020-05-23 15:06:21 -07:00
|
|
|
// Setup
|
|
|
|
s := e.Server
|
|
|
|
s.Addr = address
|
|
|
|
e.colorer.SetOutput(e.Logger.Output())
|
|
|
|
s.ErrorLog = e.StdLogger
|
|
|
|
s.Handler = h2c.NewHandler(e, h2s)
|
|
|
|
if e.Debug {
|
|
|
|
e.Logger.SetLevel(log.DEBUG)
|
|
|
|
}
|
|
|
|
|
|
|
|
if !e.HideBanner {
|
|
|
|
e.colorer.Printf(banner, e.colorer.Red("v"+Version), e.colorer.Blue(website))
|
|
|
|
}
|
|
|
|
|
|
|
|
if e.Listener == nil {
|
2021-03-20 14:40:23 -07:00
|
|
|
e.Listener, err = newListener(s.Addr, e.ListenerNetwork)
|
2020-05-23 15:06:21 -07:00
|
|
|
if err != nil {
|
2021-03-20 14:40:23 -07:00
|
|
|
e.startupMutex.Unlock()
|
2020-05-23 15:06:21 -07:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !e.HidePort {
|
|
|
|
e.colorer.Printf("⇨ http server started on %s\n", e.colorer.Green(e.Listener.Addr()))
|
|
|
|
}
|
2021-03-20 14:40:23 -07:00
|
|
|
e.startupMutex.Unlock()
|
2020-05-23 15:06:21 -07:00
|
|
|
return s.Serve(e.Listener)
|
|
|
|
}
|
|
|
|
|
2018-11-18 09:55:05 -08:00
|
|
|
// Close immediately stops the server.
|
|
|
|
// It internally calls `http.Server#Close()`.
|
|
|
|
func (e *Echo) Close() error {
|
2021-03-20 14:40:23 -07:00
|
|
|
e.startupMutex.Lock()
|
|
|
|
defer e.startupMutex.Unlock()
|
2018-11-18 09:55:05 -08:00
|
|
|
if err := e.TLSServer.Close(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return e.Server.Close()
|
|
|
|
}
|
|
|
|
|
2019-01-31 08:06:36 -08:00
|
|
|
// Shutdown stops the server gracefully.
|
2018-11-18 09:55:05 -08:00
|
|
|
// It internally calls `http.Server#Shutdown()`.
|
|
|
|
func (e *Echo) Shutdown(ctx stdContext.Context) error {
|
2021-03-20 14:40:23 -07:00
|
|
|
e.startupMutex.Lock()
|
|
|
|
defer e.startupMutex.Unlock()
|
2018-11-18 09:55:05 -08:00
|
|
|
if err := e.TLSServer.Shutdown(ctx); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return e.Server.Shutdown(ctx)
|
|
|
|
}
|
|
|
|
|
2017-02-18 14:00:46 -08:00
|
|
|
// NewHTTPError creates a new HTTPError instance.
|
|
|
|
func NewHTTPError(code int, message ...interface{}) *HTTPError {
|
|
|
|
he := &HTTPError{Code: code, Message: http.StatusText(code)}
|
|
|
|
if len(message) > 0 {
|
|
|
|
he.Message = message[0]
|
|
|
|
}
|
|
|
|
return he
|
|
|
|
}
|
|
|
|
|
|
|
|
// Error makes it compatible with `error` interface.
|
|
|
|
func (he *HTTPError) Error() string {
|
2020-05-23 15:06:21 -07:00
|
|
|
if he.Internal == nil {
|
|
|
|
return fmt.Sprintf("code=%d, message=%v", he.Code, he.Message)
|
|
|
|
}
|
2019-09-07 13:46:58 -07:00
|
|
|
return fmt.Sprintf("code=%d, message=%v, internal=%v", he.Code, he.Message, he.Internal)
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
2019-01-31 08:06:36 -08:00
|
|
|
// SetInternal sets error to HTTPError.Internal
|
|
|
|
func (he *HTTPError) SetInternal(err error) *HTTPError {
|
|
|
|
he.Internal = err
|
|
|
|
return he
|
|
|
|
}
|
|
|
|
|
2020-09-04 14:29:13 -07:00
|
|
|
// Unwrap satisfies the Go 1.13 error wrapper interface.
|
|
|
|
func (he *HTTPError) Unwrap() error {
|
|
|
|
return he.Internal
|
|
|
|
}
|
|
|
|
|
2017-02-18 14:00:46 -08:00
|
|
|
// WrapHandler wraps `http.Handler` into `echo.HandlerFunc`.
|
|
|
|
func WrapHandler(h http.Handler) HandlerFunc {
|
|
|
|
return func(c Context) error {
|
|
|
|
h.ServeHTTP(c.Response(), c.Request())
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// WrapMiddleware wraps `func(http.Handler) http.Handler` into `echo.MiddlewareFunc`
|
|
|
|
func WrapMiddleware(m func(http.Handler) http.Handler) MiddlewareFunc {
|
|
|
|
return func(next HandlerFunc) HandlerFunc {
|
|
|
|
return func(c Context) (err error) {
|
|
|
|
m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
c.SetRequest(r)
|
2019-09-07 13:46:58 -07:00
|
|
|
c.SetResponse(NewResponse(w, c.Echo()))
|
2017-02-18 14:00:46 -08:00
|
|
|
err = next(c)
|
|
|
|
})).ServeHTTP(c.Response(), c.Request())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-04 14:29:13 -07:00
|
|
|
// GetPath returns RawPath, if it's empty returns Path from URL
|
2021-03-20 14:40:23 -07:00
|
|
|
// Difference between RawPath and Path is:
|
|
|
|
// * Path is where request path is stored. Value is stored in decoded form: /%47%6f%2f becomes /Go/.
|
|
|
|
// * RawPath is an optional field which only gets set if the default encoding is different from Path.
|
2020-09-04 14:29:13 -07:00
|
|
|
func GetPath(r *http.Request) string {
|
2018-11-18 09:55:05 -08:00
|
|
|
path := r.URL.RawPath
|
|
|
|
if path == "" {
|
|
|
|
path = r.URL.Path
|
|
|
|
}
|
|
|
|
return path
|
|
|
|
}
|
|
|
|
|
2019-06-16 14:33:25 -07:00
|
|
|
func (e *Echo) findRouter(host string) *Router {
|
|
|
|
if len(e.routers) > 0 {
|
|
|
|
if r, ok := e.routers[host]; ok {
|
|
|
|
return r
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return e.router
|
|
|
|
}
|
|
|
|
|
2017-02-18 14:00:46 -08:00
|
|
|
func handlerName(h HandlerFunc) string {
|
|
|
|
t := reflect.ValueOf(h).Type()
|
|
|
|
if t.Kind() == reflect.Func {
|
|
|
|
return runtime.FuncForPC(reflect.ValueOf(h).Pointer()).Name()
|
|
|
|
}
|
|
|
|
return t.String()
|
|
|
|
}
|
|
|
|
|
2018-11-18 09:55:05 -08:00
|
|
|
// // PathUnescape is wraps `url.PathUnescape`
|
|
|
|
// func PathUnescape(s string) (string, error) {
|
|
|
|
// return url.PathUnescape(s)
|
|
|
|
// }
|
|
|
|
|
2017-02-18 14:00:46 -08:00
|
|
|
// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
|
|
|
|
// connections. It's used by ListenAndServe and ListenAndServeTLS so
|
|
|
|
// dead TCP connections (e.g. closing laptop mid-download) eventually
|
|
|
|
// go away.
|
|
|
|
type tcpKeepAliveListener struct {
|
|
|
|
*net.TCPListener
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
|
2019-06-16 14:33:25 -07:00
|
|
|
if c, err = ln.AcceptTCP(); err != nil {
|
|
|
|
return
|
|
|
|
} else if err = c.(*net.TCPConn).SetKeepAlive(true); err != nil {
|
|
|
|
return
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
2020-05-23 15:06:21 -07:00
|
|
|
// Ignore error from setting the KeepAlivePeriod as some systems, such as
|
|
|
|
// OpenBSD, do not support setting TCP_USER_TIMEOUT on IPPROTO_TCP
|
|
|
|
_ = c.(*net.TCPConn).SetKeepAlivePeriod(3 * time.Minute)
|
2019-06-16 14:33:25 -07:00
|
|
|
return
|
2017-02-18 14:00:46 -08:00
|
|
|
}
|
|
|
|
|
2021-03-20 14:40:23 -07:00
|
|
|
func newListener(address, network string) (*tcpKeepAliveListener, error) {
|
|
|
|
if network != "tcp" && network != "tcp4" && network != "tcp6" {
|
|
|
|
return nil, ErrInvalidListenerNetwork
|
|
|
|
}
|
|
|
|
l, err := net.Listen(network, address)
|
2017-02-18 14:00:46 -08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &tcpKeepAliveListener{l.(*net.TCPListener)}, nil
|
|
|
|
}
|
2019-06-16 14:33:25 -07:00
|
|
|
|
|
|
|
func applyMiddleware(h HandlerFunc, middleware ...MiddlewareFunc) HandlerFunc {
|
|
|
|
for i := len(middleware) - 1; i >= 0; i-- {
|
|
|
|
h = middleware[i](h)
|
|
|
|
}
|
|
|
|
return h
|
|
|
|
}
|