vatel

package module
v0.13.7 Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2024 License: MIT Imports: 24 Imported by: 2

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 added in v0.10.0

func WithAlarmer(ala Alarmer) func(*Option)

func WithDefaultLogOption added in v0.7.0

func WithDefaultLogOption(lo LogOption) func(*Option)

func WithJsonMasker added in v0.10.0

func WithJsonMasker(jm JsonMasker) func(*Option)

func WithLogger added in v0.13.2

func WithLogger(log *zerolog.Logger) func(*WsOption)

func WithMetricReporter added in v0.11.0

func WithMetricReporter(mr MetricReporter) func(*Option)

func WithRequestID added in v0.8.0

func WithRequestID() func(*Option)

func WithStaticLoggingLevel added in v0.7.0

func WithStaticLoggingLevel() func(*Option)

func WithTokenDecoder added in v0.13.5

func WithTokenDecoder(td TokenDecoder) func(*WsOption)

func WithUrlPrefix added in v0.7.0

func WithUrlPrefix(s string) func(*Option)

func WithVerboseError added in v0.7.2

func WithVerboseError(b bool) func(*Option)

WithVerboseError sets verbose mode for error response to the client.

func WithWebsocketSupport added in v0.13.5

func WithWebsocketSupport(wv *WebsocketVatel) func(*Option)

Types

type AccessTokenUpdateHandler added in v0.13.5

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

func (*AccessTokenUpdateHandler) Handle added in v0.13.5

Handle implements github.com/axkit/vatel Handler interface. The handler has no logic because if access token is invalid, middleware would not pass it to the handler.

func (*AccessTokenUpdateHandler) Input added in v0.13.5

func (c *AccessTokenUpdateHandler) Input() interface{}

func (*AccessTokenUpdateHandler) Result added in v0.13.5

func (c *AccessTokenUpdateHandler) Result() interface{}

type Alarmer added in v0.10.0

type Alarmer interface {
	Alarm(err error)
}

Alarmer is the interface that wraps a single method Alarm.

type AuthMessageData added in v0.13.0

type AuthMessageData struct {
	AccessToken string `json:"accessToken"`
}

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) Context
	SetStatusCode(code int) Context
	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) Context
	RequestCtx() *fasthttp.RequestCtx
	Set(key string, val interface{}) Context
	Get(key string) interface{}
	VisitUserValues(func(key []byte, val interface{}))
}

func NewContext

func NewContext(ctx *fasthttp.RequestCtx) Context

type Dater added in v0.2.0

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, WS).
	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

	WebsocketController func() WebsocketHandler

	// 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 added in v0.3.0

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 added in v0.10.0

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 added in v0.7.0

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

type Logger

type Logger interface {
	Log()
}

type MetricReporter added in v0.11.0

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 added in v0.8.0

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

type Option added in v0.7.0

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

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

type RevokeTokenChecker added in v0.3.0

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() int
	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 correctness and uniqueness here. Paths validation implemented by method BuildHandlers.

func (*Vatel) AddMiddleware added in v0.3.0

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

AddMiddleware adds middleware to be called for every requests in the order of adding.

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. Vatel itself has only one endpoint GET /, which returns the list of 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 added in v0.6.0

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 added in v0.7.0

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{}) Context

func (*VatelContext) LogValues

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

func (*VatelContext) RequestCtx added in v0.1.0

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 added in v0.7.0

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

func (*VatelContext) SetContentType

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

func (*VatelContext) SetHeader

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

func (*VatelContext) SetStatusCode

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

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 added in v0.7.0

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

type WebsocketContext added in v0.13.0

type WebsocketContext interface {
	BodyWriter() io.Writer
	TokenPayload() TokenPayloader
	SetTokenPayload(tp TokenPayloader)
	Set(key string, val interface{}) WebsocketContext
	Get(key string) interface{}
	VisitValues(func(key []byte, val interface{}))
	Created() time.Time
	ID() uint64
}

func NewWsContext added in v0.13.0

func NewWsContext(c *websocket.Conn) WebsocketContext

type WebsocketHandler added in v0.13.0

type WebsocketHandler interface {
	Handle(WebsocketContext) error
}

WebsocketHandler is the interface what wraps Handle method.

Handle invocates by websocket message processing func.

type WebsocketRequest added in v0.13.5

type WebsocketRequest struct {
	Path string          `json:"path"`
	Data json.RawMessage `json:"data,omitempty"`
}

type WebsocketVatel added in v0.13.5

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

func NewWebsocketVatel added in v0.13.5

func NewWebsocketVatel(optFunc ...func(*WsOption)) *WebsocketVatel

func (*WebsocketVatel) Endpoints added in v0.13.5

func (wv *WebsocketVatel) Endpoints() []Endpoint

func (*WebsocketVatel) OnClose added in v0.13.5

func (ww *WebsocketVatel) OnClose(f func(*websocket.Conn, error))

func (*WebsocketVatel) OnOpen added in v0.13.5

func (ww *WebsocketVatel) OnOpen(f func(*websocket.Conn))

OnOpen invocates by websocket server when new connection established.

func (*WebsocketVatel) RegisterEndpoint added in v0.13.5

func (ww *WebsocketVatel) RegisterEndpoint(v *Vatel, e *Endpoint, l *zerolog.Logger) error

RegisterEndpoint is invocated by Vatel.MustBuildHandler() for every endpoint having method "WS".

func (*WebsocketVatel) UpdateAccessToken added in v0.13.5

func (wv *WebsocketVatel) UpdateAccessToken(cid uint64, token string) error

func (*WebsocketVatel) Upgrade added in v0.13.5

func (ww *WebsocketVatel) Upgrade(ctx *fasthttp.RequestCtx)

func (*WebsocketVatel) UpgradeWithID added in v0.13.5

func (ww *WebsocketVatel) UpgradeWithID(ctx *fasthttp.RequestCtx, id uint64)

type WsContext added in v0.13.0

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

func (*WsContext) BodyWriter added in v0.13.0

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

func (*WsContext) Created added in v0.13.0

func (ctx *WsContext) Created() time.Time

func (*WsContext) Get added in v0.13.0

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

func (*WsContext) ID added in v0.13.0

func (ctx *WsContext) ID() uint64

func (*WsContext) Set added in v0.13.0

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

func (*WsContext) SetTokenPayload added in v0.13.0

func (ctx *WsContext) SetTokenPayload(tp TokenPayloader)

func (*WsContext) TokenPayload added in v0.13.0

func (ctx *WsContext) TokenPayload() TokenPayloader

func (*WsContext) VisitValues added in v0.13.0

func (ctx *WsContext) VisitValues(f func(key []byte, v interface{}))

type WsOption added in v0.13.2

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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