vatel

package module
v0.12.3 Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2022 License: MIT Imports: 22 Imported by: 0

README

vatel

Enerprise Grade REST Framework Build on fasthttp

Documentation

Index

Constants

View Source
const (
	LogUnknown      LogOption = 0
	LogFull                   = LogEnter | LogExit | LogReqBody | LogReqInput | LogRespBody
	LogFullOnExit             = LogExit | LogReqBody | LogReqInput | LogRespBody
	LogConfidential           = LogExit
)

Variables

View Source
var (
	ErrAuthorizationHeaderMissed = errors.New("header Authorization missed").Code("VTL-0001").StatusCode(401).Critical()
	ErrAccessTokenRevoked        = errors.New("access token revoked").Code("VTL-0002").StatusCode(401).Critical()
)

Functions

func WithAlarmer

func WithAlarmer(ala Alarmer) func(*Option)

func WithDefaultLogOption

func WithDefaultLogOption(lo LogOption) func(*Option)

func WithJsonMasker

func WithJsonMasker(jm JsonMasker) func(*Option)

func WithMetricReporter

func WithMetricReporter(mr MetricReporter) func(*Option)

func WithRequestID

func WithRequestID() func(*Option)

func WithStaticLoggingLevel

func WithStaticLoggingLevel() func(*Option)

func WithUrlPrefix

func WithUrlPrefix(s string) func(*Option)

func WithVerboseError

func WithVerboseError(b bool) func(*Option)

WithVerboseError sets verbose mode for error response to the client.

Types

type Alarmer

type Alarmer interface {
	Alarm(err error)
}

Alarmer is the interface that wraps a single method Alarm.

type Authorizer

type Authorizer interface {
	IsAllowed(requestPerms []byte, endpointPerms ...uint) (bool, error)
}

Authorizer is the interface that wraps IsAllowed method.

Authorizer accepts request permissions and permissions required by endpoint. Returns true if all endpointPerms are inside requestPerms.

type Context

type Context interface {
	BodyWriter() io.Writer
	SetContentType([]byte) *VatelContext
	SetStatusCode(code int) *VatelContext
	FormFile(key string) (*multipart.FileHeader, error)
	FormValue(key string) []byte
	SaveMultipartFile(fh *multipart.FileHeader, path string) error
	Header(name string) []byte
	TokenPayload() TokenPayloader
	SetTokenPayload(tp TokenPayloader)
	SetHeader(name, val []byte) *VatelContext
	RequestCtx() *fasthttp.RequestCtx
	Set(key string, val interface{}) *VatelContext
	Get(key string) interface{}
	VisitUserValues(func(key []byte, val interface{}))
}

func NewContext

func NewContext(ctx *fasthttp.RequestCtx) Context

type Dater

type Dater interface {
	Parse(string) (interface{}, error)
	Set(interface{})
}

type Endpoint

type Endpoint struct {
	LogOptions LogOption

	// Method holds HTTP method name (e.g GET, POST, PUT, DELETE).
	Method string

	// Wraps response by gzip compression function.
	Compress bool

	// Path holds url path with fasthttp parameters (e.g. /customers/{id}).
	Path string

	// Perms holds list of permissions. Nil if endpoint is public.
	Perms []string

	// Controller holds reference to the object implementing interface Handler.
	Controller func() Handler

	// ResponseContentType by default has "application/json; charset: utf-8;"
	ResponseContentType string

	// NoInputLog defines debug logging rule for request data. If true, endpoint request body
	// will not be written to the log. (i.e authentication endpoint).
	NoInputLog bool

	// NoResultLog defines debug logging rule for response data. If true, endpoint response body
	// will not be written to the log. (i.e authentication  endpoint)
	NoResultLog bool

	ManualStatusCode bool

	//
	SuccessStatusCode int

	LanguageLabel string
	// contains filtered or unexported fields
}

Endpoint describes a REST endpoint attributes and related request Handler.

func NewEndpoint

func NewEndpoint(method, path string, perms []string, c func() Handler) *Endpoint

NewEndpoint builds Endpoint.

type Endpointer

type Endpointer interface {
	Endpoints() []Endpoint
}

Endpointer is the interface that wraps a single Endpoints method.

Endpoints returns []Endpoints to be handled by API gateway.

type Handler

type Handler interface {
	Handle(Context) error
}

Handler is the interface what wraps Handle method.

Handle invocates by API gateway mux.

type Inputer

type Inputer interface {
	Input() interface{}
}

Inputer is the interface what wraps Input method.

Input returns reference to the object what will be promoted with input data by vatel.

If endpoint's handler expects input data, Input method should be implemented.

GET, DELETE methods: input values will be taken from URL query. POST, PUT, PATCH methods: input values will be taken from JSON body.

type JsonMasker

type JsonMasker interface {
	Fields(structure interface{}, tag string) jsonmask.Fields
	Mask(src []byte, fields jsonmask.Fields) ([]byte, error)
}

JsonMasker is the interface that wraps Mask and Fields methods.

Fields returns meta data of the struct which is receiver of coming JSON data. The metadata is used further in the method Mask.

Mask modifies JSON using rules specified for each field structure. Returns JSON with masked sensitive values.

type LogOption

type LogOption uint32
const (
	LogSilent LogOption = 1 << iota
	LogEnter
	LogExit
	LogReqBody
	LogReqInput
	LogRespBody
	LogRespOutput
)

type Logger

type Logger interface {
	Log()
}

type MetricReporter

type MetricReporter interface {
	ReportMetric(method, path string, statusCode int, dur float64, size int)
}

MetricReporter is the interface what wraps a single method ReportMetric.

HTTP requests handler uses MetricReporter to submit processing metrics to prometheus.

type MiddlewarePos

type MiddlewarePos int
const (
	BeforeAuthorization MiddlewarePos = iota
	AfterAuthorization
	OnSuccessResponse
	OnErrorResponse
)

type Option

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

type Paramer

type Paramer interface {
	Param() interface{}
}

Paramer is the interface what wraps a single Param method.

Param returns reference to the struct what will be promoted with values from URL.

Example: if we have /customer/{id}/bill/{billnum} then Param() should return reference to struct

{
		CustomerID int `param:"id"
	 	BillNum string `param:"billnum"`
}

If there is URL params and variables like /customer/{id}?sortBy=name&balanceAbove=100 methods Param and Input can return reference to the same struct.

type PermissionManager

type PermissionManager interface {
	PermissionBitPos(perm string) (uint, bool)
}

PermissionManager ...

type RequestDebugger

type RequestDebugger interface {
	IsDebugRequired(TokenPayloader) (in, out bool)
}

type Resulter

type Resulter interface {
	Result() interface{}
}

Resulter is the interface what wraps a single Result method.

Result returns reference to the object what will be send to the client when endpoint handler completes succesfully.

If endpoint's controller have outgoing data, Result method should be implemented.

type RevokeTokenChecker

type RevokeTokenChecker interface {
	IsTokenRevoked(accessToken string) (bool, error)
}

RevokeTokenChecker is the interface what wraps a single method IsTokenRevoked.

IsTokenRevoked returns true if access token was revoked.

type TokenDecoder

type TokenDecoder interface {
	Decode(encodedToken []byte) (Tokener, error)
}

TokenDecoder is the interface what wraps a single method Decode.

TokenDecoder decodes token and returns object Tokener.

type TokenPayloader

type TokenPayloader interface {
	User() uuid.UUID
	Login() string
	Role() int
	Perms() []byte
	Extra() interface{}
	Debug() bool
}

TokenPayloader is the interface that wraps access methods to JWT payload parts.

User returns value of user attribute from the token.

Perms returns bitset array with user role's permissions.

type Tokener

type Tokener interface {
	SystemPayload() map[string]interface{}
	ApplicationPayload() TokenPayloader
}

Tokener is the interface that wraps methods SystemPayload and UserPayload.

SystemPayload returns JWT part related to JWT itself.

UserPayload returns an object that represents JWT payload specified by user.

type Vatel

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

Vatel holds

func NewVatel

func NewVatel(optFunc ...func(*Option)) *Vatel

NewVatel returns new instance of Vatel.

func (*Vatel) Add

func (v *Vatel) Add(e ...Endpointer)

Add add endpoints to the list.

The method does not check Endpoint for corectness and uqiqueness here. Paths validation implemented by method BuildHandlers.

func (*Vatel) AddMiddleware

func (v *Vatel) AddMiddleware(pos MiddlewarePos, f ...func(Context) error)

AddMiddleware adds middlewares to be called for every requests in the same order.

func (*Vatel) BuildHandlers

func (v *Vatel) BuildHandlers(mux *router.Router, l *zerolog.Logger) error

BuildHandlers initializes http mux with rules by converting []Endpoint added before. Returns errors instead of panic.

func (*Vatel) DisableAuthorizer

func (v *Vatel) DisableAuthorizer()

func (*Vatel) Endpoints

func (v *Vatel) Endpoints() []Endpoint

Endpoints returns all registered endpoints.

func (*Vatel) MustBuildHandlers

func (v *Vatel) MustBuildHandlers(mux *router.Router, l *zerolog.Logger)

MustBuildHandlers initializes http mux with rules by converting []Endpoint added before. Panics if:

  • there are Perms but SetAuthorizer or SetTokenDecoder were not called. -

func (*Vatel) SetAuthorizer

func (v *Vatel) SetAuthorizer(a Authorizer)

SetAuthorizer assigns authorization implementation. If Authorizer is not assigned, all Endpoint's Perms will be ignored.

func (*Vatel) SetPermissionManager

func (v *Vatel) SetPermissionManager(pm PermissionManager)

SetPermissionManager assigns implementation of permission manager.

func (*Vatel) SetRequestDebugger

func (v *Vatel) SetRequestDebugger(rd RequestDebugger)

SetRequestDebugger assigns request debugger implementation.

func (*Vatel) SetRevokeTokenChecker

func (v *Vatel) SetRevokeTokenChecker(rtc RevokeTokenChecker)

SetRevokeTokenChecker assigns implementation of access token validation in the storage of revoked access tokens.

func (*Vatel) SetTokenDecoder

func (v *Vatel) SetTokenDecoder(tp TokenDecoder)

SetTokenDecoder assigns session token decoder.

type VatelContext

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

func (*VatelContext) BodyWriter

func (ctx *VatelContext) BodyWriter() io.Writer

func (*VatelContext) FormFile

func (ctx *VatelContext) FormFile(key string) (*multipart.FileHeader, error)

func (*VatelContext) FormValue

func (ctx *VatelContext) FormValue(key string) []byte

func (*VatelContext) Get

func (ctx *VatelContext) Get(key string) interface{}

func (*VatelContext) Header

func (ctx *VatelContext) Header(name string) []byte

func (*VatelContext) Log

func (ctx *VatelContext) Log(key string, val interface{}) *VatelContext

func (*VatelContext) LogValues

func (ctx *VatelContext) LogValues() map[string]interface{}

func (*VatelContext) RequestCtx

func (ctx *VatelContext) RequestCtx() *fasthttp.RequestCtx

RequestCtx returns fasthttp's context.

func (*VatelContext) SaveMultipartFile

func (ctx *VatelContext) SaveMultipartFile(fh *multipart.FileHeader, path string) error

func (*VatelContext) Set

func (ctx *VatelContext) Set(key string, val interface{}) *VatelContext

func (*VatelContext) SetContentType

func (ctx *VatelContext) SetContentType(contentType []byte) *VatelContext

func (*VatelContext) SetHeader

func (ctx *VatelContext) SetHeader(name, val []byte) *VatelContext

func (*VatelContext) SetStatusCode

func (ctx *VatelContext) SetStatusCode(code int) *VatelContext

SetStatusCode sets HTTP status code.

func (*VatelContext) SetTokenPayload

func (ctx *VatelContext) SetTokenPayload(tp TokenPayloader)

func (*VatelContext) TokenPayload

func (ctx *VatelContext) TokenPayload() TokenPayloader

func (*VatelContext) VisitUserValues

func (ctx *VatelContext) VisitUserValues(f func(key []byte, v interface{}))

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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