kit

package module
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2023 License: MIT Imports: 45 Imported by: 0

README

kit Integration Publication Go Reference

Highly opitionated Go backend kit.

  • TODO: TODOS INSIDE THE CODE
  • TODO: A TABLE WITH EVERY GO PROGRAMMING ASPECT AND THE kit.

Documentation

Overview

Package kit implements a highly opitionated Go backend kit.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrDeadlineExceeded           = NewError("deadline exceeded")
	ErrLoggerGeneric              = NewError("logger failed")
	ErrLoggerTimedOut             = NewError("logger timed out")
	ErrBinderGeneric              = NewError("binder failed")
	ErrExceptionHandlerGeneric    = NewError("error handler failed")
	ErrMigratorGeneric            = NewError("migrator failed")
	ErrMigratorTimedOut           = NewError("migrator timed out")
	ErrObserverGeneric            = NewError("observer failed")
	ErrObserverTimedOut           = NewError("observer timed out")
	ErrSerializerGeneric          = NewError("serializer failed")
	ErrRendererGeneric            = NewError("renderer failed")
	ErrLocalizerGeneric           = NewError("localizer failed")
	ErrServerGeneric              = NewError("server failed")
	ErrServerTimedOut             = NewError("server timed out")
	ErrDatabaseGeneric            = NewError("database failed")
	ErrDatabaseTimedOut           = NewError("database timed out")
	ErrDatabaseUnhealthy          = NewError("database unhealthy")
	ErrDatabaseTransactionFailed  = NewError("database transaction failed")
	ErrDatabaseNoRows             = NewError("database no rows in result set")
	ErrDatabaseIntegrityViolation = NewError("database integrity constraint violation")
	ErrCacheGeneric               = NewError("cache failed")
	ErrCacheTimedOut              = NewError("cache timed out")
	ErrCacheUnhealthy             = NewError("cache unhealthy")
	ErrCacheMiss                  = NewError("cache key not found")
	ErrWorkerGeneric              = NewError("worker failed")
	ErrWorkerTimedOut             = NewError("worker timed out")
	ErrEnqueuerGeneric            = NewError("enqueuer failed")
	ErrEnqueuerTimedOut           = NewError("enqueuer timed out")
)

Builtin errors.

View Source
var (
	// ExcServerGeneric generic server exception.
	ExcServerGeneric = NewException(http.StatusInternalServerError, "ERR_SERVER_GENERIC")
	// ExcServerUnavailable server Unavailable exception.
	ExcServerUnavailable = NewException(http.StatusServiceUnavailable, "ERR_SERVER_UNAVAILABLE")
	// ExcRequestTimeout request timeout exception.
	ExcRequestTimeout = NewException(http.StatusGatewayTimeout, "ERR_REQUEST_TIMEOUT")
	// ExcClientGeneric generic client exception.
	ExcClientGeneric = NewException(http.StatusBadRequest, "ERR_CLIENT_GENERIC")
	// ExcInvalidRequest invalid request exception.
	ExcInvalidRequest = NewException(http.StatusBadRequest, "ERR_INVALID_REQUEST")
	// ExcNotFound not found exception.
	ExcNotFound = NewException(http.StatusNotFound, "ERR_NOT_FOUND")
	// ExcUnauthorized unauthorized exception.
	ExcUnauthorized = NewException(http.StatusUnauthorized, "ERR_UNAUTHORIZED")
)

Builtin exceptions.

View Source
var Utils = _utils{
	// contains filtered or unexported fields
}

Utils contains the builtin utils.

Functions

func NewError

func NewError(message string) func() *Error

func NewException

func NewException(status int, code string) func() *Exception

Types

type Binder

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

func NewBinder

func NewBinder(observer Observer, config BinderConfig) *Binder

func (*Binder) Bind

func (self *Binder) Bind(i any, c echo.Context) error

type BinderConfig

type BinderConfig struct {
}

type Cache

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

func NewCache

func NewCache(ctx context.Context, observer Observer, config CacheConfig, retry *CacheRetryConfig) (*Cache, error)

func (*Cache) Close

func (self *Cache) Close(ctx context.Context) error

func (*Cache) Delete

func (self *Cache) Delete(ctx context.Context, key string) error

func (*Cache) Get

func (self *Cache) Get(ctx context.Context, key string, dest any) error

func (*Cache) Health

func (self *Cache) Health(ctx context.Context) error

func (*Cache) Set

func (self *Cache) Set(ctx context.Context, key string, value any, ttl *time.Duration) error

type CacheConfig

type CacheConfig struct {
	CacheHost            string
	CachePort            int
	CachePassword        string
	CacheMinConns        *int
	CacheMaxConns        *int
	CacheMaxConnIdleTime *time.Duration
	CacheMaxConnLifeTime *time.Duration
	CacheReadTimeout     *time.Duration
	CacheWriteTimeout    *time.Duration
	CacheDialTimeout     *time.Duration
	CacheAcquireTimeout  *time.Duration
	CacheLocalConfig     *CacheLocalConfig
}

type CacheLocalConfig added in v0.12.0

type CacheLocalConfig struct {
	Size int
	TTL  time.Duration
}

type CacheRetryConfig

type CacheRetryConfig struct {
	Attempts     int
	InitialDelay time.Duration
	LimitDelay   time.Duration
}

type Database

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

func NewDatabase

func NewDatabase(ctx context.Context, observer Observer, config DatabaseConfig,
	retry *DatabaseRetryConfig) (*Database, error)

func (*Database) Close

func (self *Database) Close(ctx context.Context) error

func (*Database) Exec

func (self *Database) Exec(ctx context.Context, stmt *sqlf.Stmt) (int, error)

func (*Database) Health

func (self *Database) Health(ctx context.Context) error

func (*Database) Query

func (self *Database) Query(ctx context.Context, stmt *sqlf.Stmt) error

func (*Database) Transaction

func (self *Database) Transaction(ctx context.Context, fn func(ctx context.Context) error) error

type DatabaseConfig

type DatabaseConfig struct {
	DatabaseHost            string
	DatabasePort            int
	DatabaseSSLMode         string
	DatabaseUser            string
	DatabasePassword        string
	DatabaseName            string
	AppName                 string
	DatabaseMinConns        *int
	DatabaseMaxConns        *int
	DatabaseMaxConnIdleTime *time.Duration
	DatabaseMaxConnLifeTime *time.Duration
}

type DatabaseRetryConfig

type DatabaseRetryConfig struct {
	Attempts     int
	InitialDelay time.Duration
	LimitDelay   time.Duration
}

type Enqueuer added in v0.8.0

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

func NewEnqueuer added in v0.8.0

func NewEnqueuer(observer Observer, config EnqueuerConfig) *Enqueuer

func (*Enqueuer) Close added in v0.8.0

func (self *Enqueuer) Close(ctx context.Context) error

func (*Enqueuer) Enqueue added in v0.8.0

func (self *Enqueuer) Enqueue(ctx context.Context, task string, params any, options ...asynq.Option) error

type EnqueuerConfig added in v0.8.0

type EnqueuerConfig struct {
	CacheHost         string
	CachePort         int
	CachePassword     string
	CacheMaxConns     *int
	CacheReadTimeout  *time.Duration
	CacheWriteTimeout *time.Duration
	CacheDialTimeout  *time.Duration
}

type Environment added in v0.4.0

type Environment string
var (
	EnvDevelopment Environment = "dev"
	EnvIntegration Environment = "ci"
	EnvProduction  Environment = "prod"
)

Builtin environments.

type Error

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

func (Error) Error

func (self Error) Error() string

func (Error) Is

func (self Error) Is(err error) bool

func (Error) Unwrap

func (self Error) Unwrap() error

func (*Error) With

func (self *Error) With(message string) *Error

func (*Error) Withf

func (self *Error) Withf(message string, args ...any) *Error

func (*Error) Wrap

func (self *Error) Wrap(err error) *Error

func (*Error) WrapAs

func (self *Error) WrapAs(err error) *Error

func (*Error) WrapAsWithDepth

func (self *Error) WrapAsWithDepth(depth int, err error) *Error

func (*Error) WrapWithDepth

func (self *Error) WrapWithDepth(depth int, err error) *Error

type Exception

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

func (*Exception) Cause

func (self *Exception) Cause(err error) *Exception

func (*Exception) CauseAs

func (self *Exception) CauseAs(err error) *Exception

func (Exception) Code

func (self Exception) Code() string

func (Exception) Error

func (self Exception) Error() string

func (Exception) Is

func (self Exception) Is(err error) bool

func (Exception) MarshalJSON

func (self Exception) MarshalJSON() ([]byte, error)

func (*Exception) Redact

func (self *Exception) Redact()

func (Exception) Status

func (self Exception) Status() int

func (Exception) Unwrap

func (self Exception) Unwrap() error

func (*Exception) With

func (self *Exception) With(message string) *Exception

func (*Exception) Withf

func (self *Exception) Withf(message string, args ...any) *Exception

type ExceptionHandler

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

func NewExceptionHandler

func NewExceptionHandler(observer Observer, config ExceptionHandlerConfig) *ExceptionHandler

func (*ExceptionHandler) Handle

func (self *ExceptionHandler) Handle(err error, ctx echo.Context)

type ExceptionHandlerConfig

type ExceptionHandlerConfig struct {
	Environment Environment
}

type Key added in v0.2.0

type Key string
var (
	KeyBase                Key = "kit:"
	KeyDatabaseTransaction Key = KeyBase + "database:transaction"
	KeyLocalizerLocale     Key = KeyBase + "localizer:locale"
	KeyTraceID             Key = KeyBase + "trace:id"
)

Builtin context/cache keys.

type Level added in v0.4.0

type Level int
var (
	LvlTrace Level = -5
	LvlDebug Level = -4
	LvlInfo  Level = -3
	LvlWarn  Level = -2
	LvlError Level = -1
	LvlNone  Level
)

Builtin levels.

type Localizer

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

func NewLocalizer

func NewLocalizer(observer Observer, config LocalizerConfig) (*Localizer, error)

func (Localizer) GetLocale

func (self Localizer) GetLocale(ctx context.Context) language.Tag

func (Localizer) Localize

func (self Localizer) Localize(ctx context.Context, copy string, i ...any) string

func (*Localizer) Refresh

func (self *Localizer) Refresh() error

func (Localizer) SetLocale

func (self Localizer) SetLocale(ctx context.Context, locale language.Tag) context.Context

type LocalizerConfig

type LocalizerConfig struct {
	LocalesPath      *string
	LocaleExtensions *regexp.Regexp
	DefaultLocale    language.Tag
}

type Logger

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

func NewLogger

func NewLogger(config LoggerConfig) *Logger

func (Logger) Close

func (self Logger) Close(ctx context.Context) error

func (Logger) Debug

func (self Logger) Debug(i ...any)

func (Logger) Debugf

func (self Logger) Debugf(format string, i ...any)

func (Logger) Error

func (self Logger) Error(i ...any)

func (Logger) Errorf

func (self Logger) Errorf(format string, i ...any)

func (Logger) Fatal

func (self Logger) Fatal(i ...any)

func (Logger) Fatalf

func (self Logger) Fatalf(format string, i ...any)

func (Logger) Flush

func (self Logger) Flush(ctx context.Context) error

func (*Logger) Header

func (self *Logger) Header() string

func (Logger) Info

func (self Logger) Info(i ...any)

func (Logger) Infof

func (self Logger) Infof(format string, i ...any)

func (Logger) Level

func (self Logger) Level() Level

func (Logger) Logger

func (self Logger) Logger() *zerolog.Logger

func (Logger) Output

func (self Logger) Output() io.Writer

func (Logger) Panic

func (self Logger) Panic(i ...any)

func (Logger) Panicf

func (self Logger) Panicf(format string, i ...any)

func (Logger) Prefix

func (self Logger) Prefix() string

func (Logger) Print

func (self Logger) Print(i ...any)

func (Logger) Printf

func (self Logger) Printf(format string, i ...any)

func (*Logger) SetHeader

func (self *Logger) SetHeader(h string)

func (*Logger) SetLevel

func (self *Logger) SetLevel(l Level)

func (*Logger) SetOutput

func (self *Logger) SetOutput(w io.Writer)

func (*Logger) SetPrefix

func (self *Logger) SetPrefix(p string)

func (*Logger) SetVerbose

func (self *Logger) SetVerbose(v bool)

func (Logger) Verbose

func (self Logger) Verbose() bool

func (Logger) Warn

func (self Logger) Warn(i ...any)

func (Logger) Warnf

func (self Logger) Warnf(format string, i ...any)

func (Logger) WithLevel

func (self Logger) WithLevel(level Level, i ...any)

func (Logger) WithLevelf

func (self Logger) WithLevelf(level Level, format string, i ...any)

type LoggerConfig

type LoggerConfig struct {
	AppName        string
	Level          Level
	SkipFrameCount *int
}

type Migrator

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

func NewMigrator

func NewMigrator(ctx context.Context, observer Observer, config MigratorConfig,
	retry *MigratorRetryConfig) (*Migrator, error)

func (*Migrator) Apply

func (self *Migrator) Apply(ctx context.Context, schemaVersion int) error

TODO: concurrent-safe

func (*Migrator) Assert

func (self *Migrator) Assert(ctx context.Context, schemaVersion int) error

TODO: concurrent-safe

func (*Migrator) Close

func (self *Migrator) Close(ctx context.Context) error

func (*Migrator) Rollback

func (self *Migrator) Rollback(ctx context.Context, schemaVersion int) error

TODO: concurrent-safe

type MigratorConfig

type MigratorConfig struct {
	MigrationsPath   *string
	DatabaseHost     string
	DatabasePort     int
	DatabaseSSLMode  string
	DatabaseUser     string
	DatabasePassword string
	DatabaseName     string
}

type MigratorRetryConfig

type MigratorRetryConfig struct {
	Attempts     int
	InitialDelay time.Duration
	LimitDelay   time.Duration
}

type Observer

type Observer struct {
	Logger
	// contains filtered or unexported fields
}

func NewObserver

func NewObserver(ctx context.Context, config ObserverConfig, retry *ObserverRetryConfig) (*Observer, error)

func (Observer) Close

func (self Observer) Close(ctx context.Context) error

func (Observer) Debug

func (self Observer) Debug(ctx context.Context, i ...any)

func (Observer) Debugf

func (self Observer) Debugf(ctx context.Context, format string, i ...any)

func (Observer) Error

func (self Observer) Error(ctx context.Context, i ...any)

func (Observer) Errorf

func (self Observer) Errorf(ctx context.Context, format string, i ...any)

func (Observer) Fatal

func (self Observer) Fatal(ctx context.Context, i ...any)

func (Observer) Fatalf

func (self Observer) Fatalf(ctx context.Context, format string, i ...any)

func (Observer) Flush

func (self Observer) Flush(ctx context.Context) error

func (Observer) GetTrace

func (self Observer) GetTrace(ctx context.Context) xid.ID

func (Observer) Info

func (self Observer) Info(ctx context.Context, i ...any)

func (Observer) Infof

func (self Observer) Infof(ctx context.Context, format string, i ...any)

func (Observer) Metric

func (self Observer) Metric()

TODO

func (Observer) Panic

func (self Observer) Panic(ctx context.Context, i ...any)

func (Observer) Panicf

func (self Observer) Panicf(ctx context.Context, format string, i ...any)

func (Observer) Print

func (self Observer) Print(ctx context.Context, i ...any)

func (Observer) Printf

func (self Observer) Printf(ctx context.Context, format string, i ...any)

func (Observer) SetTrace

func (self Observer) SetTrace(ctx context.Context, traceID xid.ID) context.Context

func (Observer) TraceQuery

func (self Observer) TraceQuery(ctx context.Context, sql string, args ...any) (context.Context, func())

func (Observer) TraceRequest

func (self Observer) TraceRequest(ctx context.Context, request *http.Request) (context.Context, func())

func (Observer) TraceSpan

func (self Observer) TraceSpan(ctx context.Context, name ...string) (context.Context, func())

func (Observer) TraceTask added in v0.11.0

func (self Observer) TraceTask(ctx context.Context, task *asynq.Task) (context.Context, func())

func (Observer) Warn

func (self Observer) Warn(ctx context.Context, i ...any)

func (Observer) Warnf

func (self Observer) Warnf(ctx context.Context, format string, i ...any)

func (Observer) WithLevel

func (self Observer) WithLevel(ctx context.Context, level Level, i ...any)

func (Observer) WithLevelf

func (self Observer) WithLevelf(ctx context.Context, level Level, format string, i ...any)

type ObserverConfig

type ObserverConfig struct {
	Environment  Environment
	Release      string
	AppName      string
	Level        Level
	SentryConfig *ObserverSentryConfig
	GilkConfig   *ObserverGilkConfig
}

type ObserverGilkConfig

type ObserverGilkConfig struct {
	Port int
}

type ObserverRetryConfig

type ObserverRetryConfig struct {
	Attempts     int
	InitialDelay time.Duration
	LimitDelay   time.Duration
}

type ObserverSentryConfig

type ObserverSentryConfig struct {
	Dsn string
}

type Renderer

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

func NewRenderer

func NewRenderer(observer Observer, config RendererConfig) (*Renderer, error)

func (*Renderer) Render

func (self *Renderer) Render(w io.Writer, name string, data any, c echo.Context) error

func (*Renderer) RenderBytes

func (self *Renderer) RenderBytes(template string, data any) ([]byte, error)

func (*Renderer) RenderString

func (self *Renderer) RenderString(template string, data any) (string, error)

func (*Renderer) RenderWriter

func (self *Renderer) RenderWriter(w io.Writer, template string, data any) error

type RendererConfig

type RendererConfig struct {
	TemplatesPath      *string
	TemplateExtensions *regexp.Regexp
}

type Serializer

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

func NewSerializer

func NewSerializer(observer Observer, config SerializerConfig) *Serializer

func (*Serializer) Deserialize

func (self *Serializer) Deserialize(c echo.Context, i any) error

func (*Serializer) Serialize

func (self *Serializer) Serialize(c echo.Context, i any, indent string) error

type SerializerConfig

type SerializerConfig struct {
}

type Server

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

func NewServer

func NewServer(observer Observer, serializer Serializer, binder Binder,
	renderer Renderer, exceptionHandler ExceptionHandler, config ServerConfig) *Server

func (*Server) Close

func (self *Server) Close(ctx context.Context) error

func (*Server) Default added in v0.7.0

func (self *Server) Default(middleware ...echo.MiddlewareFunc) *echo.Group

func (*Server) Host

func (self *Server) Host(host string, middleware ...echo.MiddlewareFunc) *echo.Group

func (*Server) Run

func (self *Server) Run(ctx context.Context) error

func (*Server) Use

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

type ServerConfig

type ServerConfig struct {
	Environment              Environment
	AppPort                  int
	RequestHeaderMaxSize     *int
	RequestBodyMaxSize       *int
	RequestFileMaxSize       *int
	RequestKeepAliveTimeout  *time.Duration
	RequestReadTimeout       *time.Duration
	RequestReadHeaderTimeout *time.Duration
	RequestIPExtractor       *func(*http.Request) string
	ResponseWriteTimeout     *time.Duration
}

type Worker

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

func NewWorker added in v0.8.0

func NewWorker(observer Observer, config WorkerConfig) *Worker

func (*Worker) Close added in v0.8.0

func (self *Worker) Close(ctx context.Context) error

func (*Worker) Register added in v0.8.0

func (self *Worker) Register(task string, handler func(context.Context, *asynq.Task) error)

func (*Worker) Run added in v0.8.0

func (self *Worker) Run(ctx context.Context) error

func (*Worker) Schedule added in v0.8.0

func (self *Worker) Schedule(task string, params any, cron string, options ...asynq.Option)

func (*Worker) Use added in v0.8.0

func (self *Worker) Use(middleware ...asynq.MiddlewareFunc)

type WorkerConfig added in v0.8.0

type WorkerConfig struct {
	CacheHost            string
	CachePort            int
	CachePassword        string
	CacheMaxConns        *int
	CacheReadTimeout     *time.Duration
	CacheWriteTimeout    *time.Duration
	CacheDialTimeout     *time.Duration
	WorkerQueues         map[string]int
	WorkerConcurrency    *int
	WorkerStrictPriority *bool
	WorkerStopTimeout    *time.Duration
	WorkerTimeZone       *time.Location
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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