srv

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2020 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Example
package main

import (
	"net/http"
	"os"

	"github.com/TsvetanMilanov/go-graceful-server-shutdown/gss"
	"github.com/TsvetanMilanov/go-simple-di/di"
	"github.com/TsvetanMilanov/go-srv/srv"
	"github.com/TsvetanMilanov/go-srv/srv/log"
	"github.com/gin-gonic/gin"
)

type dbClient struct{}

func (db *dbClient) GetData() map[string]interface{} {
	return map[string]interface{}{"key": "value"}
}

type dataService struct {
	DBClient *dbClient `di:""`

	// The reqLogger dependency will be included in the reqDI container.
	RequestLogger log.Logger `di:"name=reqLogger"`
	// A srv.TraceIDProvider dependency will be included in the reqDI container.
	TraceIDProvider srv.TraceIDProvider `di:""`
}

func (s *dataService) GetData() map[string]interface{} {
	s.RequestLogger.Info("this is log from the request logger")
	s.RequestLogger.Info(s.TraceIDProvider.GetTraceID())

	// Use the resolved DBClient.
	return s.DBClient.GetData()
}

type controller struct{}

func (controller *controller) Get(c *gin.Context) {
	dataSvc := new(dataService)
	reqDI, _ := srv.GetReqDI(c)

	err := reqDI.Resolve(dataSvc)
	if err != nil {
		panic(err)
	}

	c.JSON(http.StatusOK, dataSvc.GetData())
}

func main() {
	// Function which registers all application dependencies.
	// This function will be invoked only once.
	var registerAppDependencies = func(container *di.Container) error {
		return container.Register(
			&di.Dependency{Value: new(controller)},
		)
	}

	// This function will be invoked before each request.
	// You can register all dependencies which needs to be resolved for each request here.
	// The container instance will be new for each request.
	var reqDIConfigurator = func(req *http.Request, container *di.Container) error {
		return container.Register(
			&di.Dependency{Value: new(dataService)},
			&di.Dependency{Value: new(dbClient)},
		)
	}

	// Function which receives a router object which has some predefined configurations
	// and can be used to finish the router configuration with the resolved app dependencies.
	var configureRouter = func(router *gin.Engine, appDI *di.Container) error {
		// Set the env to production.
		if env, ok := os.LookupEnv("GO_ENV"); ok && env == "production" {
			gin.SetMode(gin.ReleaseMode)
		}

		tc := new(controller)
		// Use the appDI container to resolve the registered app dependencies (e.g. controllers)
		err := appDI.Resolve(tc)
		if err != nil {
			return err
		}

		// Register all routes.
		router.GET("/data", tc.Get)

		return nil
	}

	app, err := srv.NewAppBuilder().
		Initialize(os.Stdout).
		EnableMetricsServer(nil, nil). // You can pass custom prometheus gatherer or registerer here.
		RegisterAppDependencies(registerAppDependencies).
		ResolveAppDependencies().
		RegisterReqDIConfigurator(reqDIConfigurator).
		ConfigureApp(func(appDI *di.Container) error { return nil }).
		RegisterRouter(gin.New()).
		AddDefaultMiddlewares().
		ConfigureRouter(configureRouter).
		BuildApp()

	if err != nil {
		panic(err)
	}

	err = app.Start(&gss.Settings{Addr: ":80"}, nil)
	if err != nil {
		panic(err)
	}
}
Output:

Index

Examples

Constants

View Source
const (
	// AppLoggerName is the name of the app logger instance.
	AppLoggerName = "appLogger"

	// ReqLoggerName is the name of the req logger instance.
	ReqLoggerName = "reqLogger"

	// AppDIName is the name of the app di container.
	AppDIName = "appDi"

	// ReqDIName is the name of the req di container.
	ReqDIName = "reqDi"

	// TraceIDName is the name of the trace id property.
	TraceIDName = "traceId"

	// TraceIDReqHeaderName is the name of the header which will be used
	// to acquire trace id.
	TraceIDReqHeaderName = "X-Trace-Id"
)

Variables

This section is empty.

Functions

func GetReqDI

func GetReqDI(c context.Context) (*di.Container, error)

GetReqDI tries to get the request di from the context.

func GetRequestLoggerOrDefaultChild

func GetRequestLoggerOrDefaultChild(c context.Context, defaultLogger log.Logger) log.Logger

GetRequestLoggerOrDefaultChild returns the request logger or the child of the default logger.

Types

type App

type App interface {
	Start(srvSettings, metricsSrvSettings *gss.Settings) error
	GetRouter() http.Handler
	GetMetricsRouter() http.Handler
	GetLogger() log.Logger
}

App provides methods for working with the web app.

type AppBuilder

type AppBuilder interface {
	BuildApp() (App, error)
}

AppBuilder provides method to build the web application.

type AppConfigurator

type AppConfigurator interface {
	RouterRegisterer
	// This step is not required.
	ConfigureApp(configurator DIContainerUser) RouterRegisterer
}

AppConfigurator provides method for configuring the application. This method provides access to the resolved app dependencies. Use it to set the log level for example.

type AppDependenciesRegisterer

type AppDependenciesRegisterer interface {
	RegisterAppDependencies(registerer DIContainerUser) AppDependenciesResolver
}

AppDependenciesRegisterer provides method for registering the app dependencies.

type AppDependenciesResolver

type AppDependenciesResolver interface {
	ResolveAppDependencies() ReqDIConfiguratorRegisterer
}

AppDependenciesResolver provides method for resolving all app dependencies.

type AppInitializer

type AppInitializer interface {
	Initialize(loggerOut io.Writer) MetricsServerConfigurator
}

AppInitializer provides method for initializing the web application.

func NewAppBuilder

func NewAppBuilder() AppInitializer

NewAppBuilder creates new web application builder.

type DIContainerUser

type DIContainerUser = func(container *di.Container) error

DIContainerUser is a function which receives a di container and provides implementation which uses it.

type DefaultMiddlewaresConfigurator

type DefaultMiddlewaresConfigurator interface {
	RouterConfigurator
	// This step is not required.
	AddDefaultMiddlewares() RouterConfigurator
}

DefaultMiddlewaresConfigurator provides method which adds the default middlewares to the router.

type MetricsServerConfigurator

type MetricsServerConfigurator interface {
	AppDependenciesRegisterer

	// This step is not required.
	EnableMetricsServer(gatherer prometheus.Gatherer, options *middleware.Options) MetricsServerConfigurator
}

MetricsServerConfigurator provides methods for configuring the metrics server.

type ReqDIConfiguratorRegisterer

type ReqDIConfiguratorRegisterer interface {
	AppConfigurator
	RegisterReqDIConfigurator(configurator RequestDIConfiguratorFunc) AppConfigurator
}

ReqDIConfiguratorRegisterer provides method for configuring the request di.

type RequestDIConfiguratorFunc

type RequestDIConfiguratorFunc = func(req *http.Request, reqDI *di.Container) error

RequestDIConfiguratorFunc function which can be used to configure the request di.

type RouterConfigurator

type RouterConfigurator interface {
	ConfigureRouter(configurator RouterConfiguratorFunc) AppBuilder
}

RouterConfigurator provides method for configuring the router.

type RouterConfiguratorFunc

type RouterConfiguratorFunc = func(router *gin.Engine, appDI *di.Container) error

RouterConfiguratorFunc function which can be used to configure the router.

type RouterRegisterer

type RouterRegisterer interface {
	RegisterRouter(router *gin.Engine) DefaultMiddlewaresConfigurator
}

RouterRegisterer provides method for registering the app router.

type TraceIDProvider

type TraceIDProvider interface {
	GetTraceID() string
}

TraceIDProvider provides methods for acquiring trace id.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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