2 Package echo implements high performance, minimalist Go web framework.
11 "github.com/labstack/echo"
12 "github.com/labstack/echo/middleware"
16 func hello(c echo.Context) error {
17 return c.String(http.StatusOK, "Hello, World!")
25 e.Use(middleware.Logger())
26 e.Use(middleware.Recover())
32 e.Logger.Fatal(e.Start(":1323"))
35 Learn more at https://echo.labstack.com
57 "github.com/labstack/gommon/color"
58 "github.com/labstack/gommon/log"
59 "golang.org/x/crypto/acme/autocert"
63 // Echo is the top-level framework instance.
65 stdLogger *stdLog.Logger
67 premiddleware []MiddlewareFunc
68 middleware []MiddlewareFunc
71 notFoundHandler HandlerFunc
74 TLSServer *http.Server
76 TLSListener net.Listener
77 AutoTLSManager autocert.Manager
82 HTTPErrorHandler HTTPErrorHandler
89 // Route contains a handler and information for matching against requests.
91 Method string `json:"method"`
92 Path string `json:"path"`
93 Name string `json:"name"`
96 // HTTPError represents an error that occurred while handling a request.
100 Internal error // Stores the error returned by an external dependency
103 // MiddlewareFunc defines a function to process middleware.
104 MiddlewareFunc func(HandlerFunc) HandlerFunc
106 // HandlerFunc defines a function to server HTTP requests.
107 HandlerFunc func(Context) error
109 // HTTPErrorHandler is a centralized HTTP error handler.
110 HTTPErrorHandler func(error, Context)
112 // Validator is the interface that wraps the Validate function.
113 Validator interface {
114 Validate(i interface{}) error
117 // Renderer is the interface that wraps the Render function.
119 Render(io.Writer, string, interface{}, Context) error
122 // Map defines a generic map of type `map[string]interface{}`.
123 Map map[string]interface{}
125 // i is the interface for Echo and Group.
127 GET(string, HandlerFunc, ...MiddlewareFunc) *Route
140 PROPFIND = "PROPFIND"
147 MIMEApplicationJSON = "application/json"
148 MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8
149 MIMEApplicationJavaScript = "application/javascript"
150 MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
151 MIMEApplicationXML = "application/xml"
152 MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + charsetUTF8
153 MIMETextXML = "text/xml"
154 MIMETextXMLCharsetUTF8 = MIMETextXML + "; " + charsetUTF8
155 MIMEApplicationForm = "application/x-www-form-urlencoded"
156 MIMEApplicationProtobuf = "application/protobuf"
157 MIMEApplicationMsgpack = "application/msgpack"
158 MIMETextHTML = "text/html"
159 MIMETextHTMLCharsetUTF8 = MIMETextHTML + "; " + charsetUTF8
160 MIMETextPlain = "text/plain"
161 MIMETextPlainCharsetUTF8 = MIMETextPlain + "; " + charsetUTF8
162 MIMEMultipartForm = "multipart/form-data"
163 MIMEOctetStream = "application/octet-stream"
167 charsetUTF8 = "charset=UTF-8"
172 HeaderAccept = "Accept"
173 HeaderAcceptEncoding = "Accept-Encoding"
174 HeaderAllow = "Allow"
175 HeaderAuthorization = "Authorization"
176 HeaderContentDisposition = "Content-Disposition"
177 HeaderContentEncoding = "Content-Encoding"
178 HeaderContentLength = "Content-Length"
179 HeaderContentType = "Content-Type"
180 HeaderCookie = "Cookie"
181 HeaderSetCookie = "Set-Cookie"
182 HeaderIfModifiedSince = "If-Modified-Since"
183 HeaderLastModified = "Last-Modified"
184 HeaderLocation = "Location"
185 HeaderUpgrade = "Upgrade"
187 HeaderWWWAuthenticate = "WWW-Authenticate"
188 HeaderXForwardedFor = "X-Forwarded-For"
189 HeaderXForwardedProto = "X-Forwarded-Proto"
190 HeaderXForwardedProtocol = "X-Forwarded-Protocol"
191 HeaderXForwardedSsl = "X-Forwarded-Ssl"
192 HeaderXUrlScheme = "X-Url-Scheme"
193 HeaderXHTTPMethodOverride = "X-HTTP-Method-Override"
194 HeaderXRealIP = "X-Real-IP"
195 HeaderXRequestID = "X-Request-ID"
196 HeaderXRequestedWith = "X-Requested-With"
197 HeaderServer = "Server"
198 HeaderOrigin = "Origin"
201 HeaderAccessControlRequestMethod = "Access-Control-Request-Method"
202 HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers"
203 HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin"
204 HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods"
205 HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers"
206 HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
207 HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers"
208 HeaderAccessControlMaxAge = "Access-Control-Max-Age"
211 HeaderStrictTransportSecurity = "Strict-Transport-Security"
212 HeaderXContentTypeOptions = "X-Content-Type-Options"
213 HeaderXXSSProtection = "X-XSS-Protection"
214 HeaderXFrameOptions = "X-Frame-Options"
215 HeaderContentSecurityPolicy = "Content-Security-Policy"
216 HeaderXCSRFToken = "X-CSRF-Token"
221 website = "https://echo.labstack.com"
222 // http://patorjk.com/software/taag/#p=display&f=Small%20Slant&t=Echo
227 /___/\__/_//_/\___/ %s
228 High performance, minimalist Go web framework
230 ____________________________________O/_______
236 methods = [...]string{
252 ErrUnsupportedMediaType = NewHTTPError(http.StatusUnsupportedMediaType)
253 ErrNotFound = NewHTTPError(http.StatusNotFound)
254 ErrUnauthorized = NewHTTPError(http.StatusUnauthorized)
255 ErrForbidden = NewHTTPError(http.StatusForbidden)
256 ErrMethodNotAllowed = NewHTTPError(http.StatusMethodNotAllowed)
257 ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge)
258 ErrValidatorNotRegistered = errors.New("validator not registered")
259 ErrRendererNotRegistered = errors.New("renderer not registered")
260 ErrInvalidRedirectCode = errors.New("invalid redirect status code")
261 ErrCookieNotFound = errors.New("cookie not found")
266 NotFoundHandler = func(c Context) error {
270 MethodNotAllowedHandler = func(c Context) error {
271 return ErrMethodNotAllowed
275 // New creates an instance of Echo.
276 func New() (e *Echo) {
278 Server: new(http.Server),
279 TLSServer: new(http.Server),
280 AutoTLSManager: autocert.Manager{
281 Prompt: autocert.AcceptTOS,
283 Logger: log.New("echo"),
284 colorer: color.New(),
288 e.TLSServer.Handler = e
289 e.HTTPErrorHandler = e.DefaultHTTPErrorHandler
290 e.Binder = &DefaultBinder{}
291 e.Logger.SetLevel(log.ERROR)
292 e.stdLogger = stdLog.New(e.Logger.Output(), e.Logger.Prefix()+": ", 0)
293 e.pool.New = func() interface{} {
294 return e.NewContext(nil, nil)
296 e.router = NewRouter(e)
300 // NewContext returns a Context instance.
301 func (e *Echo) NewContext(r *http.Request, w http.ResponseWriter) Context {
304 response: NewResponse(w, e),
307 pvalues: make([]string, *e.maxParam),
308 handler: NotFoundHandler,
312 // Router returns router.
313 func (e *Echo) Router() *Router {
317 // DefaultHTTPErrorHandler is the default HTTP error handler. It sends a JSON response
319 func (e *Echo) DefaultHTTPErrorHandler(err error, c Context) {
321 code = http.StatusInternalServerError
325 if he, ok := err.(*HTTPError); ok {
328 if he.Internal != nil {
329 msg = fmt.Sprintf("%v, %v", err, he.Internal)
334 msg = http.StatusText(code)
336 if _, ok := msg.(string); ok {
337 msg = Map{"message": msg}
343 if !c.Response().Committed {
344 if c.Request().Method == HEAD { // Issue #608
345 err = c.NoContent(code)
347 err = c.JSON(code, msg)
355 // Pre adds middleware to the chain which is run before router.
356 func (e *Echo) Pre(middleware ...MiddlewareFunc) {
357 e.premiddleware = append(e.premiddleware, middleware...)
360 // Use adds middleware to the chain which is run after router.
361 func (e *Echo) Use(middleware ...MiddlewareFunc) {
362 e.middleware = append(e.middleware, middleware...)
365 // CONNECT registers a new CONNECT route for a path with matching handler in the
366 // router with optional route-level middleware.
367 func (e *Echo) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
368 return e.Add(CONNECT, path, h, m...)
371 // DELETE registers a new DELETE route for a path with matching handler in the router
372 // with optional route-level middleware.
373 func (e *Echo) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
374 return e.Add(DELETE, path, h, m...)
377 // GET registers a new GET route for a path with matching handler in the router
378 // with optional route-level middleware.
379 func (e *Echo) GET(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
380 return e.Add(GET, path, h, m...)
383 // HEAD registers a new HEAD route for a path with matching handler in the
384 // router with optional route-level middleware.
385 func (e *Echo) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
386 return e.Add(HEAD, path, h, m...)
389 // OPTIONS registers a new OPTIONS route for a path with matching handler in the
390 // router with optional route-level middleware.
391 func (e *Echo) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
392 return e.Add(OPTIONS, path, h, m...)
395 // PATCH registers a new PATCH route for a path with matching handler in the
396 // router with optional route-level middleware.
397 func (e *Echo) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
398 return e.Add(PATCH, path, h, m...)
401 // POST registers a new POST route for a path with matching handler in the
402 // router with optional route-level middleware.
403 func (e *Echo) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
404 return e.Add(POST, path, h, m...)
407 // PUT registers a new PUT route for a path with matching handler in the
408 // router with optional route-level middleware.
409 func (e *Echo) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
410 return e.Add(PUT, path, h, m...)
413 // TRACE registers a new TRACE route for a path with matching handler in the
414 // router with optional route-level middleware.
415 func (e *Echo) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {
416 return e.Add(TRACE, path, h, m...)
419 // Any registers a new route for all HTTP methods and path with matching handler
420 // in the router with optional route-level middleware.
421 func (e *Echo) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route {
422 routes := make([]*Route, len(methods))
423 for i, m := range methods {
424 routes[i] = e.Add(m, path, handler, middleware...)
429 // Match registers a new route for multiple HTTP methods and path with matching
430 // handler in the router with optional route-level middleware.
431 func (e *Echo) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc) []*Route {
432 routes := make([]*Route, len(methods))
433 for i, m := range methods {
434 routes[i] = e.Add(m, path, handler, middleware...)
439 // Static registers a new route with path prefix to serve static files from the
440 // provided root directory.
441 func (e *Echo) Static(prefix, root string) *Route {
443 root = "." // For security we want to restrict to CWD.
445 return static(e, prefix, root)
448 func static(i i, prefix, root string) *Route {
449 h := func(c Context) error {
450 p, err := url.PathUnescape(c.Param("*"))
454 name := filepath.Join(root, path.Clean("/"+p)) // "/"+ for security
459 return i.GET(prefix+"*", h)
462 return i.GET(prefix+"/*", h)
465 // File registers a new route with path to serve a static file.
466 func (e *Echo) File(path, file string) *Route {
467 return e.GET(path, func(c Context) error {
472 // Add registers a new route for an HTTP method and path with matching handler
473 // in the router with optional route-level middleware.
474 func (e *Echo) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route {
475 name := handlerName(handler)
476 e.router.Add(method, path, func(c Context) error {
479 for i := len(middleware) - 1; i >= 0; i-- {
489 e.router.routes[method+path] = r
493 // Group creates a new router group with prefix and optional group-level middleware.
494 func (e *Echo) Group(prefix string, m ...MiddlewareFunc) (g *Group) {
495 g = &Group{prefix: prefix, echo: e}
500 // URI generates a URI from handler.
501 func (e *Echo) URI(handler HandlerFunc, params ...interface{}) string {
502 name := handlerName(handler)
503 return e.Reverse(name, params...)
506 // URL is an alias for `URI` function.
507 func (e *Echo) URL(h HandlerFunc, params ...interface{}) string {
508 return e.URI(h, params...)
511 // Reverse generates an URL from route name and provided parameters.
512 func (e *Echo) Reverse(name string, params ...interface{}) string {
513 uri := new(bytes.Buffer)
516 for _, r := range e.router.routes {
518 for i, l := 0, len(r.Path); i < l; i++ {
519 if r.Path[i] == ':' && n < ln {
520 for ; i < l && r.Path[i] != '/'; i++ {
522 uri.WriteString(fmt.Sprintf("%v", params[n]))
526 uri.WriteByte(r.Path[i])
535 // Routes returns the registered routes.
536 func (e *Echo) Routes() []*Route {
537 routes := make([]*Route, 0, len(e.router.routes))
538 for _, v := range e.router.routes {
539 routes = append(routes, v)
544 // AcquireContext returns an empty `Context` instance from the pool.
545 // You must return the context by calling `ReleaseContext()`.
546 func (e *Echo) AcquireContext() Context {
547 return e.pool.Get().(Context)
550 // ReleaseContext returns the `Context` instance back to the pool.
551 // You must call it after `AcquireContext()`.
552 func (e *Echo) ReleaseContext(c Context) {
556 // ServeHTTP implements `http.Handler` interface, which serves HTTP requests.
557 func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request) {
559 c := e.pool.Get().(*context)
565 if e.premiddleware == nil {
566 path := r.URL.RawPath
570 e.router.Find(m, getPath(r), c)
572 for i := len(e.middleware) - 1; i >= 0; i-- {
573 h = e.middleware[i](h)
576 h = func(c Context) error {
577 path := r.URL.RawPath
581 e.router.Find(m, getPath(r), c)
583 for i := len(e.middleware) - 1; i >= 0; i-- {
584 h = e.middleware[i](h)
588 for i := len(e.premiddleware) - 1; i >= 0; i-- {
589 h = e.premiddleware[i](h)
594 if err := h(c); err != nil {
595 e.HTTPErrorHandler(err, c)
602 // Start starts an HTTP server.
603 func (e *Echo) Start(address string) error {
604 e.Server.Addr = address
605 return e.StartServer(e.Server)
608 // StartTLS starts an HTTPS server.
609 func (e *Echo) StartTLS(address string, certFile, keyFile string) (err error) {
610 if certFile == "" || keyFile == "" {
611 return errors.New("invalid tls configuration")
614 s.TLSConfig = new(tls.Config)
615 s.TLSConfig.Certificates = make([]tls.Certificate, 1)
616 s.TLSConfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
620 return e.startTLS(address)
623 // StartAutoTLS starts an HTTPS server using certificates automatically installed from https://letsencrypt.org.
624 func (e *Echo) StartAutoTLS(address string) error {
625 if e.Listener == nil {
626 go http.ListenAndServe(":http", e.AutoTLSManager.HTTPHandler(nil))
630 s.TLSConfig = new(tls.Config)
631 s.TLSConfig.GetCertificate = e.AutoTLSManager.GetCertificate
632 return e.startTLS(address)
635 func (e *Echo) startTLS(address string) error {
639 s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "h2")
641 return e.StartServer(e.TLSServer)
644 // StartServer starts a custom http server.
645 func (e *Echo) StartServer(s *http.Server) (err error) {
647 e.colorer.SetOutput(e.Logger.Output())
648 s.ErrorLog = e.stdLogger
651 e.Logger.SetLevel(log.DEBUG)
655 e.colorer.Printf(banner, e.colorer.Red("v"+Version), e.colorer.Blue(website))
658 if s.TLSConfig == nil {
659 if e.Listener == nil {
660 e.Listener, err = newListener(s.Addr)
666 e.colorer.Printf("⇨ http server started on %s\n", e.colorer.Green(e.Listener.Addr()))
668 return s.Serve(e.Listener)
670 if e.TLSListener == nil {
671 l, err := newListener(s.Addr)
675 e.TLSListener = tls.NewListener(l, s.TLSConfig)
678 e.colorer.Printf("⇨ https server started on %s\n", e.colorer.Green(e.TLSListener.Addr()))
680 return s.Serve(e.TLSListener)
683 // Close immediately stops the server.
684 // It internally calls `http.Server#Close()`.
685 func (e *Echo) Close() error {
686 if err := e.TLSServer.Close(); err != nil {
689 return e.Server.Close()
692 // Shutdown stops server the gracefully.
693 // It internally calls `http.Server#Shutdown()`.
694 func (e *Echo) Shutdown(ctx stdContext.Context) error {
695 if err := e.TLSServer.Shutdown(ctx); err != nil {
698 return e.Server.Shutdown(ctx)
701 // NewHTTPError creates a new HTTPError instance.
702 func NewHTTPError(code int, message ...interface{}) *HTTPError {
703 he := &HTTPError{Code: code, Message: http.StatusText(code)}
704 if len(message) > 0 {
705 he.Message = message[0]
710 // Error makes it compatible with `error` interface.
711 func (he *HTTPError) Error() string {
712 return fmt.Sprintf("code=%d, message=%v", he.Code, he.Message)
715 // WrapHandler wraps `http.Handler` into `echo.HandlerFunc`.
716 func WrapHandler(h http.Handler) HandlerFunc {
717 return func(c Context) error {
718 h.ServeHTTP(c.Response(), c.Request())
723 // WrapMiddleware wraps `func(http.Handler) http.Handler` into `echo.MiddlewareFunc`
724 func WrapMiddleware(m func(http.Handler) http.Handler) MiddlewareFunc {
725 return func(next HandlerFunc) HandlerFunc {
726 return func(c Context) (err error) {
727 m(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
730 })).ServeHTTP(c.Response(), c.Request())
736 func getPath(r *http.Request) string {
737 path := r.URL.RawPath
744 func handlerName(h HandlerFunc) string {
745 t := reflect.ValueOf(h).Type()
746 if t.Kind() == reflect.Func {
747 return runtime.FuncForPC(reflect.ValueOf(h).Pointer()).Name()
752 // // PathUnescape is wraps `url.PathUnescape`
753 // func PathUnescape(s string) (string, error) {
754 // return url.PathUnescape(s)
757 // tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
758 // connections. It's used by ListenAndServe and ListenAndServeTLS so
759 // dead TCP connections (e.g. closing laptop mid-download) eventually
761 type tcpKeepAliveListener struct {
765 func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
766 tc, err := ln.AcceptTCP()
770 tc.SetKeepAlive(true)
771 tc.SetKeepAlivePeriod(3 * time.Minute)
775 func newListener(address string) (*tcpKeepAliveListener, error) {
776 l, err := net.Listen("tcp", address)
780 return &tcpKeepAliveListener{l.(*net.TCPListener)}, nil