fastecho

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2025 License: Apache-2.0 Imports: 35 Imported by: 0

README

Fastecho is a Go library that provides an easily configurable, ready-to-use echo server. It is a wrapper on top of the echo framework and it adds extra functionalities that are often required when setting up web servers.

How to run

For specifics, check the detailed features below.

    // load env vars
    err := core.Envs.SetEnv()
	if err != nil {
		log.Fatalf("failed to set environment variables: %s", err)
	}

    // set up a DB and pass it to handler as you like
	db, err := fastecho.NewDB()
	if err != nil {
		log.Fatalf("failed to connect to the database: %s", err)
	}

	config := fastecho.Config{
		ExtraEnvs:           core.Envs,
		ValidationRegistrar: validator.RegisterValidations,
		Routes: func(e *echo.Echo, r *router.Router) error {
			return configureRoutes(e, r, db)
		},
		// Properties which would be shared across all the requests in the service via ServiceContext
		ContextProps: map[string]interface{}{
			"my_property": "",
		},
		Opts: fastecho.Opts{
			Tracing: fastecho.TracingOpts{
				Skip:        !core.Envs[consts.OtelTracing].BooleanValue,
				ServiceName: core.Envs[consts.OtelServiceName].Value,
			},
			HealthChecks: fastecho.HealthChecksOpts{
				Skip: false,
				DB:   db,
			},
		},
	}

	// Starting service...
	if err := fastecho.Run(&config); err != nil {
		log.Fatalf("Service stopped! \n %s", err)
	}

Features:

Logger

We integrated go.uber.org/zap

Dynamic request context

You can inject custom properties into the service context via props. This object is of type any so you can pass anything into your context to make it accessible in your endpoints.

You could also access request level properties by making use of RequestProps in ServiceContext.

func (h *Handler) GetData(ctx echo.Context) error {
    sctx := context.GetServiceContext[any](ctx)
    log := sctx.ZapLogger
	// props contain service level properties which are shared across all requests
	props := sctx.Props.(map[string]interface{})

	// requestProps contain request level properties which can be set and accessed from within the handler or middleware
	sctx.RequestProps["country"] = "NL"
    ...
}
Endpoint router

The router is providing a couple of preset endpoints for swagger, monitoring and health checks but custom endpoints can also be injected. The router wrapper in the example above can be used to register additional endpoints.

Example:

func configureRoutes(e *echo.Echo, r *router.Router, db *gorm.DB) error {
	myHandler := NewHandler(db)

	v1 := e.Group("/v1")
	myGroup := v1.Group("/example")

	router.AddRoute(r, myGroup, "/data", myHandler, http.MethodGet)
	return nil
}
Request validation

Custom validation can be registered using the provided validator. You need to define a function in which you register custom validations and then add it to the config.

func RegisterValidations(validator *router.Validator) error {
	validator.Vdt.RegisterStructValidation(daterange.ValidateBasicDateRange(), daterange.BasicDateRange{})

	return nil
}
Middleware injection

Custom middleware can be injected easily just like routes.

func configureRoutes(e *echo.Echo, r *router.Router, db *gorm.DB) error {
	v1 := e.Group("/v1")
	myGroup := v1.Group("/data")

	myGroup.Use(middleware.MyCustomMiddleware())

	return nil
}
Swagger

Swagger is baked into the router wrapper. The title and path can be used via these environment variables:

swaggerUITitle swaggerJSONPath

The swagger documentation is configured on the root path suffixed with /swagger/.

Health probe endpoints

The health endpoints are configured on the root path suffixed with /health/live and /health/ready.

Environment variables

Environment variables are read by default from the environment or from a .env file in the root of the directory.

The required ENV vars are:

  • SwaggerUITitle
  • ServiceName

Here's an example on how to define env vars and how to load them before starting fastecho:

// define variables
var (
	Envs = env.Map{
		consts.SwaggerUITitle: {
			DefaultValue: "FFP Sales forecast connector API",
		},
		consts.OtelServiceName: {
			DefaultValue: "ffp-sales-forecast-connector-v1",
		},
		consts.OtelTracing: {
			DefaultValue: "false",
			IsBoolean:    true,
		},
		// The variables related to the DB are already defined in fastecho
	}
)

// load them
    err := core.Envs.SetEnv()
	if err != nil {
		log.Fatalf("failed to set environment variables: %s", err)
	}
OTEL tracing (optional)

Tracing is enabled only if the OTEL_TRACING env var is set to true.

Database (optional)

Fastecho has an optional postgres DB connection baked into it using gorm. We are using goose for migrations rather than gorm Automigrate. The migrations are expected to be under db/migrations in the root of your folder.

Plugins

Plugins are a set of handlers and their binded components(validators, middlewares, etc) which can be reused across multiple services using fastecho.

Usage
fastechoConfig.Use(<pluginConfig>)

Miscellaneous

Fastecho is fully compatible with Echoprobe

Contributing

Please read CONTRIBUTING for more details about making a contribution to this open source project and ensure that you follow our CODE_OF_CONDUCT.

Contact

If you have any other issues or questions regarding this project, feel free to contact one of the code owners/maintainers for a more in-depth discussion.

Licence

This open source project is licensed under the "Apache-2.0", read the LICENCE terms for more details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewDB

func NewDB() (*gorm.DB, error)

NewDB creates a new *gorm.DB the configuration of which is through environment variables.

func Run

func Run(cfg *Config) error

Run starts a new instance of fastecho.

Types

type Config

type Config struct {
	ExtraEnvs           env.Map
	ValidationRegistrar func(v *router.Validator) error
	Routes              func(e *echo.Echo, r *router.Router) error
	// ContextProps would be shared across all requests in the service
	ContextProps any
	Opts         Opts
	Plugins      []Plugin
}

Config serves as input configuration for fastecho.

func (*Config) Use added in v0.1.0

func (c *Config) Use(p Plugin)

type FastEcho

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

func Initialize

func Initialize(cfg *Config) (*FastEcho, error)

Initialize sets up a new instance of FastEcho and returns a prepared FastEcho type, but does not boot the server.

func (*FastEcho) Handler

func (fe *FastEcho) Handler() http.Handler

Handler returns the Echo handler for the defined FastEcho server.

func (*FastEcho) Shutdown

func (fe *FastEcho) Shutdown(ctx gocontext.Context) error

Shutdown cleanly shuts down the server and any tracing providers.

type HealthChecksOpts

type HealthChecksOpts struct {
	Skip bool
	DB   *gorm.DB
}

HealthChecksOpts define configuration options for health checks.

type MetricsOpts

type MetricsOpts struct {
	Skip bool
}

MetricsOpts define configuration options for metrics.

type Opts

type Opts struct {
	Metrics      MetricsOpts
	Tracing      TracingOpts
	HealthChecks HealthChecksOpts
}

Opts define configuration options for fastecho.

type Plugin added in v0.1.0

type Plugin struct {
	ValidationRegistrar func(v *router.Validator) error
	Routes              func(e *echo.Echo, r *router.Router) error
}

type TracingOpts

type TracingOpts struct {
	Skip        bool
	ServiceName string
}

TracingOpts define configuration options for tracing.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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