echo

package
v1.7.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 20, 2026 License: MIT Imports: 25 Imported by: 0

README

echo v5

Factory for Echo v5 (github.com/labstack/echo/v5). It lives beside echo/v4: same options, same config keys (boost.factory.echo.*) and the same plugin set, written against the v5 API. An app picks one of the two; a service moves from v4 to v5 by changing the import paths and the handler signature.

Usage

import (
	"context"
	"net/http"

	e "github.com/labstack/echo/v5"
	"github.com/xgodev/boost"
	"github.com/xgodev/boost/factory/contrib/labstack/echo/v5"
	"github.com/xgodev/boost/factory/contrib/labstack/echo/v5/plugins/local/extra/health"
	"github.com/xgodev/boost/factory/contrib/labstack/echo/v5/plugins/native/recover"
)

func main() {
	boost.Start()
	ctx := context.Background()

	srv, err := echo.NewServer(ctx, recover.Register, health.Register)
	if err != nil {
		panic(err)
	}

	srv.GET("/hello", func(c *e.Context) error {
		return c.String(http.StatusOK, "Hello, World!")
	})

	srv.Serve(ctx) // blocks until srv.Shutdown(ctx)
}

Constructors:

Constructor Options from
NewServer(ctx, plugins...) boost.factory.echo.*
NewServerWithConfigPath(ctx, path, plugins...) boost.factory.echo.* overridden by path.*
NewServerWithOptions(ctx, opts, plugins...) the given *Options

Each returns (*Server, error): a plugin that fails stops the build and its error is returned. Serve blocks and logs any error but the http.ErrServerClosed that Shutdown causes; Shutdown drains the server within the context deadline. *Server is a multiserver.Server.

With fx, fx/modules/factory/contrib/labstack/echo/v5.Module() provides *echo.Server and *e.Echo and joins the multiserver group, so the multiserver module serves it on the app start and shuts it down on the stop. Plugins come from the optional []echo.Plugin in the graph.

Configuration

Key Default Meaning
boost.factory.echo.port 8080 listen port
boost.factory.echo.type REST REST answers errors as JSON, anything else as text
boost.factory.echo.protocol HTTP HTTP or H2C
boost.factory.echo.hideBanner true hide the Echo v5.x line
boost.factory.echo.disableHTTP2 false TLS offers only HTTP/1.1
boost.factory.echo.tls.enabled false serve TLS
boost.factory.echo.tls.type AUTO AUTO (self-signed) or FILE
boost.factory.echo.tls.auto.host localhost host of the self-signed certificate
boost.factory.echo.tls.file.cert / .key "" PEM files for FILE
boost.factory.echo.hc2.* HTTP/2 server options for H2C

Plugins

Every plugin has a package Register(ctx, srv) error that reads its keys under boost.factory.echo.plugins.<name>, and the constructor trio NewX(), NewXWithConfigPath(path), NewXWithOptions(opts).

Plugin Package Keys (…plugins.)
CORS plugins/native/cors cors.enabled, cors.allowed.{origins,headers,methods,credentials}, cors.exposed.headers, cors.maxAge
Gzip plugins/native/gzip gzip.enabled, gzip.level
Recover plugins/native/recover recover.enabled
Request ID plugins/native/requestid requestId.enabled
Body limit plugins/native/bodylimit bodyLimit.enabled, bodyLimit.size (8M)
Body dump plugins/native/bodydump bodydump.enabled
Error handler plugins/extra/error_handler errorHandler.enabled
Semaphore plugins/extra/semaphore semaphore.enabled, semaphore.limit (10000, then 503)
Health plugins/local/extra/health health.enabled, health.route (/health)
Multiserver check plugins/local/extra/multi-server multiServer.enabled, multiServer.route (/check)
Resource status plugins/local/model/restresponse status.enabled, status.route (/resource-status)
Request log plugins/local/wrapper/log logger.enabled, logger.level (DEBUG)
Prometheus plugins/contrib/labstack/echo-contrib/v5/echoprometheus prometheus.enabled, prometheus.route.{path,enabled}, prometheus.collector.enabled
pprof plugins/contrib/labstack/echo-contrib/v5/pprof pprof.enabled, pprof.prefix (/debug/pprof)
OpenTelemetry plugins/contrib/labstack/echo-otel/v5 otel.enabled, otel.serverName
Datadog plugins/contrib/datadog/dd-trace-go/v2 datadog.enabled (no-op while the tracer is off)
goccy/go-json plugins/contrib/goccy/go-json/v0 goccyGoJson.enabled
bytedance/sonic plugins/contrib/bytedance/sonic/v1 bytedanceSonic.enabled
Swagger UI plugins/contrib/swaggo/echo-swagger/v2 swagger.enabled, swagger.route (/swagger/*)

The Prometheus collectors register once per process in the default registry, so every echo server of the app reports into the same echo_* metrics. The OpenTelemetry plugin uses the providers of factory/contrib/go.opentelemetry.io/otel/v1.

Differences from v4

  • Handlers take *echo.Context (v5) instead of echo.Context; route methods return echo.RouteInfo; ErrorHandlerJSON/ErrorHandlerString take (c, err).
  • Echo logs through log/slog; WrapLogger bridges it to the boost logger.
  • Constructors and plugins return their errors instead of panicking or calling log.Fatal.
  • cors.allowed.credentials defaults to false: echo v5 refuses credentials with the * origin. Set explicit origins to turn it on.
  • bodyLimit.* and bodydump.* keys are registered under their plugin path (v4 missed them) and H2C reads hc2.* under the server path.
  • Prometheus, pprof and OpenTelemetry use the v5 echo-contrib/echo-otel packages; Swagger UI uses swaggo/echo-swagger/v2 (v4 has its v1 plugin).
  • The builder REST door still generates echo v4 code.

Documentation

Index

Constants

View Source
const (

	// PluginsRoot is the config root every echo v5 plugin key lives under.
	PluginsRoot = root + ".plugins"
)

Variables

This section is empty.

Functions

func ConfigAdd

func ConfigAdd(path string)

ConfigAdd registers the echo server config keys under path.

func ErrorHandlerJSON

func ErrorHandlerJSON(c *e.Context, err error)

ErrorHandlerJSON implements JSON content type error handler.

func ErrorHandlerString

func ErrorHandlerString(c *e.Context, err error)

ErrorHandlerString implements plain text content type error handler.

func ErrorStatusCode

func ErrorStatusCode(err error) int

ErrorStatusCode translates err to the respective HTTP status code.

func WrapLogger

func WrapLogger(logger log.Logger) *slog.Logger

WrapLogger returns a slog logger, the logger echo v5 uses, that writes through the boost logger. Attributes become boost fields; group names prefix the keys of the attributes inside them ("http.address").

Types

type Options

type Options struct {
	HideBanner   bool
	DisableHTTP2 bool `config:"disableHTTP2"`
	Port         int
	Type         string
	Protocol     string
	TLS          struct {
		Enabled bool
		Type    string
		Auto    struct {
			Host string
		}
		File struct {
			Cert string
			Key  string
		}
	} `config:"tls"`
	Json struct {
		Pretty struct {
			Enabled bool
		}
	}
}

Options echo server options.

func NewOptions

func NewOptions() (*Options, error)

NewOptions returns options from config file or environment vars.

func NewOptionsWithPath

func NewOptionsWithPath(path string) (opts *Options, err error)

NewOptionsWithPath unmarshals a given key path into options and returns it.

type Plugin

type Plugin = factory.Plugin[*Server]

Plugin defines an echo server Plugin function to execute.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server represents an echo v5 server.

func NewServer

func NewServer(ctx context.Context, plugins ...Plugin) (*Server, error)

NewServer returns a new echo server with default options.

func NewServerWithConfigPath

func NewServerWithConfigPath(ctx context.Context, path string, plugins ...Plugin) (*Server, error)

NewServerWithConfigPath returns a new echo server with options from config path.

func NewServerWithOptions

func NewServerWithOptions(ctx context.Context, opt *Options, plugins ...Plugin) (*Server, error)

NewServerWithOptions returns a new echo server with options. A plugin that fails stops the build: the error is returned and later plugins do not run.

func (*Server) Add

func (s *Server) Add(method string, path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) echo.RouteInfo

Add registers the handler and middlewares for method route at path.

func (*Server) Any

Any registers the handler and middlewares for all method routes at path.

func (*Server) CONNECT

func (s *Server) CONNECT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) echo.RouteInfo

CONNECT registers the handler and middlewares for CONNECT route at path.

func (*Server) DELETE

func (s *Server) DELETE(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) echo.RouteInfo

DELETE registers the handler and middlewares for DELETE route at path.

func (*Server) File

func (s *Server) File(path, file string, m ...echo.MiddlewareFunc) echo.RouteInfo

File registers a path to a server file.

func (*Server) GET

GET registers the handler and middlewares for GET route at path.

func (*Server) Group

func (s *Server) Group(prefix string, m ...echo.MiddlewareFunc) *echo.Group

Group creates a router group with prefix and registers middlewares.

func (*Server) HEAD

func (s *Server) HEAD(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) echo.RouteInfo

HEAD registers the handler and middlewares for HEAD route at path.

func (*Server) Instance

func (s *Server) Instance() *echo.Echo

Instance returns the wrapped echo server instance.

func (*Server) Match

func (s *Server) Match(methods []string, path string, handler echo.HandlerFunc, middleware ...echo.MiddlewareFunc) echo.Routes

Match registers the handler and middlewares for method routes at path.

func (*Server) OPTIONS

func (s *Server) OPTIONS(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) echo.RouteInfo

OPTIONS registers the handler and middlewares for OPTIONS route at path.

func (*Server) Options

func (s *Server) Options() *Options

Options returns echo server options.

func (*Server) PATCH

func (s *Server) PATCH(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) echo.RouteInfo

PATCH registers the handler and middlewares for PATCH route at path.

func (*Server) POST

func (s *Server) POST(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) echo.RouteInfo

POST registers the handler and middlewares for POST route at path.

func (*Server) PUT

PUT registers the handler and middlewares for PUT route at path.

func (*Server) Pre

func (s *Server) Pre(middleware ...echo.MiddlewareFunc)

Pre registers middlewares that will run before router.

func (*Server) Serve

func (s *Server) Serve(ctx context.Context)

Serve starts the echo server and blocks until Shutdown stops it. Errors are logged; the http.ErrServerClosed that Shutdown causes is not an error.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context)

Shutdown stops the echo server gracefully, bounded by ctx. Called before Serve, it makes a later Serve return at once.

func (*Server) Static

func (s *Server) Static(prefix, root string, m ...echo.MiddlewareFunc) echo.RouteInfo

Static registers a static path to server static files at root dir.

func (*Server) Use

func (s *Server) Use(middleware ...echo.MiddlewareFunc)

Use registers middlewares that will run after router.

Directories

Path Synopsis
plugins
contrib/swaggo/echo-swagger/v2
Package swagger serves the Swagger UI and the swag docs on an echo v5 server, through github.com/swaggo/echo-swagger/v2.
Package swagger serves the Swagger UI and the swag docs on an echo v5 server, through github.com/swaggo/echo-swagger/v2.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL