echo

package
v1.0.0-dev.204 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2025 License: MIT Imports: 21 Imported by: 0

README

Echo Integration for Boost

Overview

The Echo integration in Boost provides a robust wrapper around the popular Echo web framework (v4), offering simplified server initialization, configuration management, middleware integration, and plugin support. This package enables developers to quickly set up HTTP, H2C, and TLS servers with a clean API while leveraging Boost's ecosystem.

Features

  • Simplified Server Creation: Easy initialization with sensible defaults
  • Configuration Management: Support for file-based configuration
  • Plugin Architecture: Extensible design with plugin support
  • Middleware Integration: Built-in support for Echo middleware
  • Protocol Support: HTTP, H2C, and TLS (including auto-certificate generation)
  • Routing API: Complete access to Echo's routing capabilities
  • Boost Integration: Seamless integration with Boost logging and other components

Installation

import (
    "github.com/xgodev/boost/factory/contrib/labstack/echo/v4"
)

Basic Usage

Creating a Server
// Create a new server with default options
server, err := echo.NewServer(ctx)
if err != nil {
    log.Fatal(err)
}

// Define routes
server.GET("/hello", func(c echo.Context) error {
    return c.String(http.StatusOK, "Hello, World!")
})

// Start the server
server.Serve(ctx)
Using Configuration File
// Create a server with options from config file
server, err := echo.NewServerWithConfigPath(ctx, "/path/to/config.yaml")
if err != nil {
    log.Fatal(err)
}

// Define routes and start server
// ...
Using Plugins
// Create plugins
corsPlugin := echoplugins.CORS(ctx)
recoverPlugin := echoplugins.Recover(ctx)

// Create server with plugins
server, err := echo.NewServer(ctx, corsPlugin, recoverPlugin)
if err != nil {
    log.Fatal(err)
}

// Define routes and start server
// ...

Configuration Options

The Echo server can be configured with various options:

options := &echo.Options{
    Port:         8080,
    Protocol:     "HTTP", // "HTTP", "H2C", or "TLS"
    HideBanner:   true,
    DisableHTTP2: false,
    TLS: echo.TLSOptions{
        Enabled: false,
        Type:    "FILE", // "FILE" or "AUTO"
        File: echo.TLSFileOptions{
            Cert: "/path/to/cert.pem",
            Key:  "/path/to/key.pem",
        },
        Auto: echo.TLSAutoOptions{
            Host: "example.com",
        },
    },
}

server := echo.NewServerWithOptions(ctx, options)

Available Plugins

The Echo integration includes several built-in plugins organized into categories:

Native Plugins

These plugins wrap Echo's native middleware:

  • BodyDump: Dumps request and response bodies
  • BodyLimit: Sets the maximum allowed request body size
  • CORS: Configures Cross-Origin Resource Sharing
  • GZIP: Compresses responses using gzip
  • Recover: Recovers from panics and returns 500 error
  • RequestID: Adds a unique request ID to each request
Extra Plugins

Additional functionality beyond Echo's native capabilities:

  • ErrorHandler: Custom error handling
  • Semaphore: Request rate limiting
Local Plugins

Boost-specific integrations:

  • Health: Health check endpoints
  • MultiServer: Run multiple Echo servers
  • RestResponse: Standardized REST response format
  • Log: Integration with Boost logging
Contrib Plugins

Third-party integrations:

  • Echo-Pprof: Profiling endpoints
  • Prometheus: Metrics collection
  • Swagger: API documentation

Example: Complete Server with Middleware

package main

import (
    "context"
    "net/http"

    "github.com/labstack/echo/v4"
    echoserver "github.com/xgodev/boost/factory/contrib/labstack/echo/v4"
    "github.com/xgodev/boost/factory/contrib/labstack/echo/v4/plugins/native/cors"
    "github.com/xgodev/boost/factory/contrib/labstack/echo/v4/plugins/native/recover"
    "github.com/xgodev/boost/factory/contrib/labstack/echo/v4/plugins/local/wrapper/log"
)

func main() {
    ctx := context.Background()
    
    // Create plugins
    corsPlugin := cors.New(ctx)
    recoverPlugin := recover.New(ctx)
    logPlugin := log.New(ctx)
    
    // Create server with plugins
    server, err := echoserver.NewServer(ctx, corsPlugin, recoverPlugin, logPlugin)
    if err != nil {
        panic(err)
    }
    
    // Define routes
    server.GET("/", func(c echo.Context) error {
        return c.String(http.StatusOK, "Hello, World!")
    })
    
    // Group routes
    api := server.Group("/api")
    api.GET("/users", getUsers)
    api.POST("/users", createUser)
    
    // Start server
    server.Serve(ctx)
}

func getUsers(c echo.Context) error {
    return c.JSON(http.StatusOK, []string{"user1", "user2"})
}

func createUser(c echo.Context) error {
    // Implementation...
    return c.JSON(http.StatusCreated, map[string]string{"status": "created"})
}

Integration with Boost

The Echo integration works seamlessly with other Boost components:

  • Logging: Automatically integrates with Boost's logging system
  • Configuration: Uses Boost's configuration management
  • Metrics: Can be integrated with Prometheus for metrics collection
  • Health Checks: Built-in health check endpoints

Best Practices

  1. Use Plugins for Middleware: Organize middleware as plugins for better code organization
  2. Group Related Routes: Use the Group method to organize related endpoints
  3. Leverage Configuration Files: Store server configuration in external files
  4. Implement Proper Error Handling: Use the ErrorHandler plugin for consistent error responses
  5. Add Request Logging: Use the Log plugin to log all requests
  6. Set Appropriate Timeouts: Configure timeouts to prevent resource exhaustion
  7. Use TLS in Production: Enable TLS for production environments

Contributing

Contributions to improve the Echo integration are welcome. Please follow the Boost project's contribution guidelines.

License

This package is part of the Boost project and is subject to its license terms.

Documentation

Index

Constants

View Source
const (
	PluginsRoot = root + ".plugins"
)

Variables

This section is empty.

Functions

func ConfigAdd

func ConfigAdd(path string)

func ErrorHandlerJSON

func ErrorHandlerJSON(err error, c e.Context)

ErrorHandlerJSON implements JSON content type error handler.

func ErrorHandlerString

func ErrorHandlerString(err error, c e.Context)

ErrorHandlerString implements plain text content type error handler.

func ErrorStatusCode

func ErrorStatusCode(err error) int

ErrorStatusCode translates to the respective status code.

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 func(context.Context, *Server) error

Plugin defines an echo server Plugin function to execute.

type Server

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

Server represents a echo 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

NewServerWithOptions returns a new echo server with options.

func (*Server) Add

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

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

func (*Server) Any

func (s *Server) Any(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) []*echo.Route

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.Route

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.Route

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.Route

File registers a path to a server file.

func (*Server) GET

func (s *Server) GET(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route

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.Route

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.Route

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.Route

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.Route

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.Route

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

func (*Server) PUT

func (s *Server) PUT(path string, h echo.HandlerFunc, m ...echo.MiddlewareFunc) *echo.Route

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 echo server.

func (*Server) Shutdown

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

Shutdown stops echo server.

func (*Server) Static

func (s *Server) Static(prefix, root string) *echo.Route

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.

type WrappedLogger

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

WrappedLogger represents a wrapped logger with util methods.

func WrapLogger

func WrapLogger(l log.Logger) *WrappedLogger

WrapLogger wraps an instace of logger interface.

func (WrappedLogger) Debug

func (wl WrappedLogger) Debug(i ...interface{})

Debug logs a debug message.

func (WrappedLogger) Debugf

func (wl WrappedLogger) Debugf(s string, i ...interface{})

Debugf logs a formatted debug message.

func (WrappedLogger) Debugj

func (wl WrappedLogger) Debugj(j l.JSON)

Debugj not implemented yet.

func (WrappedLogger) Error

func (wl WrappedLogger) Error(i ...interface{})

Error logs an error message.

func (WrappedLogger) Errorf

func (wl WrappedLogger) Errorf(s string, i ...interface{})

Errorf logs a formatted error message.

func (WrappedLogger) Errorj

func (wl WrappedLogger) Errorj(j l.JSON)

Warnj not implemented yet.

func (WrappedLogger) Fatal

func (wl WrappedLogger) Fatal(i ...interface{})

Fatal logs a fatal message.

func (WrappedLogger) Fatalf

func (wl WrappedLogger) Fatalf(s string, i ...interface{})

Fatalf logs a formatted fatal message.

func (WrappedLogger) Fatalj

func (wl WrappedLogger) Fatalj(j l.JSON)

Warnj not implemented yet.

func (WrappedLogger) Info

func (wl WrappedLogger) Info(i ...interface{})

Warnf logs an info message.

func (WrappedLogger) Infof

func (wl WrappedLogger) Infof(s string, i ...interface{})

Infof logs a formatted info message.

func (WrappedLogger) Infoj

func (wl WrappedLogger) Infoj(j l.JSON)

Infoj not implemented yet.

func (WrappedLogger) Level

func (wl WrappedLogger) Level() l.Lvl

Level not implemented yet.

func (WrappedLogger) Output

func (wl WrappedLogger) Output() io.Writer

Output returns logger output writer.

func (WrappedLogger) Panic

func (wl WrappedLogger) Panic(i ...interface{})

Warnj not implemented yet.

func (WrappedLogger) Panicf

func (wl WrappedLogger) Panicf(format string, args ...interface{})

Warnj not implemented yet.

func (WrappedLogger) Panicj

func (wl WrappedLogger) Panicj(j l.JSON)

Warnj not implemented yet.

func (WrappedLogger) Prefix

func (wl WrappedLogger) Prefix() string

Prefix not implemented yet.

func (WrappedLogger) Print

func (wl WrappedLogger) Print(i ...interface{})

Print logs a message.

func (WrappedLogger) Printf

func (wl WrappedLogger) Printf(s string, i ...interface{})

Print logs a formatted message.

func (WrappedLogger) Printj

func (wl WrappedLogger) Printj(j l.JSON)

Level not implemented yet.

func (WrappedLogger) SetHeader

func (wl WrappedLogger) SetHeader(h string)

SetHeader not implemented yet.

func (WrappedLogger) SetLevel

func (wl WrappedLogger) SetLevel(v l.Lvl)

SetLevel not implemented yet.

func (WrappedLogger) SetOutput

func (wl WrappedLogger) SetOutput(w io.Writer)

Warnj not implemented yet.

func (WrappedLogger) SetPrefix

func (wl WrappedLogger) SetPrefix(p string)

SetPrefix not implemented yet.

func (WrappedLogger) Warn

func (wl WrappedLogger) Warn(i ...interface{})

Warn logs a warn message.

func (WrappedLogger) Warnf

func (wl WrappedLogger) Warnf(s string, i ...interface{})

Warnf logs a formatted warn message.

func (WrappedLogger) Warnj

func (wl WrappedLogger) Warnj(j l.JSON)

Warnj not implemented yet.

Directories

Path Synopsis
examples
beyond command
googlecall command
h2c command
health command
helloworld command
multiecho command
multiserver command
notfound command
tls command
plugins
contrib/go.opentelemetry.io/contrib/v0
This package implements integration between echo (https://github.com/labstack/echo) and OpenTelemetry.
This package implements integration between echo (https://github.com/labstack/echo) and OpenTelemetry.

Jump to

Keyboard shortcuts

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