web

package
v0.13.0 Latest Latest
Warning

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

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

README

Web

The web module enables the application to become a web application. When this module is used, a gin web server is started. The web module allows endpoints and middlewares to be added to the web server using dependency injection. The web module abstracts away the boilerplate code of running the web server, allowing application code to focus on writing the endpoints.

The web module achieves this by providing the following components:

NewEngine - this is a wrapped gin web server. Our wrapper allows the request to be pre-processed before being handled by gin web server. The only request pre-processor we currently provide is a CachedRequestPreProcessors. This is used during the auth process so that the auth server can replay the original request after the session is authenticated.

NewRegistrar - this registrar is used by other packages to register middlewares, endpoints, error translations etc. This registrar is provided so that any other feature that wants to add to the web server can do so via the registrar.

The web module also has a fx.Invoke. Because of it, when the web module is activated, it starts the web server and adds all the component in the registrar on it when the application starts.

Web Tests

Examples on how to write web tests can be found here.

FAQs:

  1. When running web-tests, if you ever encounter the following error:
pq: no database or schema specified

Follow the documentation here to configure local database for testing.

Documentation

Index

Constants

View Source
const (
	MinWebPrecedence = bootstrap.WebPrecedence
	MaxWebPrecedence = bootstrap.WebPrecedence + bootstrap.FrameworkModulePrecedenceBandwidth

	LowestMiddlewareOrder  = int(^uint(0) >> 1)         // max int
	HighestMiddlewareOrder = -LowestMiddlewareOrder - 1 // min int

	FxGroupControllers     = "controllers"
	FxGroupCustomizers     = "customizers"
	FxGroupErrorTranslator = "error_translators"

	ErrorTemplate = "error.tmpl"

	MethodAny = "ANY"
)
View Source
const (
	HeaderAuthorization      = "Authorization"
	HeaderOrigin             = "Origin"
	HeaderACAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderACAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderACAllowMethods     = "Access-Control-Allow-AllowedMethodsStr"
	HeaderACAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderACExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderACMaxAge           = "Access-Control-Max-Age"
	HeaderACRequestHeaders   = "Access-Control-Request-Headers"
	HeaderACRequestMethod    = "Access-Control-Request-Method"
	HeaderContentType        = "Content-Type"
	HeaderContentLength      = "Content-Length"
)
View Source
const (
	LogKeyHttp         = "http"
	LogKeyHttpStatus   = "status"
	LogKeyHttpMethod   = "method"
	LogKeyHttpClientIP = "clientIP"
	LogKeyHttpPath     = "path"
	LogKeyHttpErrorMsg = "error"
	LogKeyHttpBodySize = "bodySize"
)
View Source
const (
	DefaultGroup = "/"
)
View Source
const (
	ServerPropertiesPrefix = "server"
)

Variables

This section is empty.

Functions

func BytesResponseEncoder

func BytesResponseEncoder() httptransport.EncodeResponseFunc

func BytesWriteFunc

func BytesWriteFunc(rw http.ResponseWriter, v interface{}) error

func ContextPath

func ContextPath(ctx context.Context) string

ContextPath returns the "server.context-path" from properties with leading "/". This function returns empty string if context-path is root or not set

func CustomResponseEncoder

func CustomResponseEncoder(opts ...EncodeOptions) httptransport.EncodeResponseFunc

func DefaultErrorHandling

func DefaultErrorHandling() gin.HandlerFunc

DefaultErrorHandling implement error handling logics at last resort, in case errors are not properly handled downstream

func FxControllerProviders

func FxControllerProviders(targets ...interface{}) fx.Option

func FxCustomizerProviders

func FxCustomizerProviders(targets ...interface{}) fx.Option

func FxErrorTranslatorProviders

func FxErrorTranslatorProviders(targets ...interface{}) fx.Option

func GinContext

func GinContext(ctx context.Context) *gin.Context

GinContext returns *gin.Context which either contained in the context or is the given context itself

func GinContextMerger

func GinContextMerger() gin.HandlerFunc

GinContextMerger is a Gin middleware that merge Request.Context() with gin.Context, allowing values in gin.Context also available via Request.Context().Value(). This middleware is mandatory for all mappings. Note: as of Gin 1.8.0, if we set gin.Engine.ContextWithFallback to true. This makes gin.Context fully integrated

with its underling Request.Context(). The side effect of this is gin.Context.Value() is also calling
Request.Context().Value(), which cause stack overflow on non-existing keys.

To break this loop, we use different version of utils.ContextValuer to extract values from gin.Context(),
without using gin.Context.Value() function.

func HttpRequest

func HttpRequest(ctx context.Context) *http.Request

HttpRequest returns *http.Request associated with given context

func JsonErrorEncoder

func JsonErrorEncoder() httptransport.ErrorEncoder

func JsonResponseEncoder

func JsonResponseEncoder() httptransport.EncodeResponseFunc

func JsonWriteFunc

func JsonWriteFunc(rw http.ResponseWriter, v interface{}) error

func MakeEndpoint

func MakeEndpoint(m *mvcMetadata) endpoint.Endpoint

MakeEndpoint convert given mvcMetadata to kit/endpoint.Endpoint

func MakeFuncMetadata

func MakeFuncMetadata(endpointFunc MvcHandlerFunc, validator MvcHandlerFuncValidator) *mvcMetadata

MakeFuncMetadata uses reflect to analyze the given rest function and create a endpointFuncMetadata this function panic if given function have incorrect signature Caller can provide an optional validator to further validate function signature on top of default validation

func MakeGinBindingDecodeRequestFunc

func MakeGinBindingDecodeRequestFunc(s *mvcMetadata) httptransport.DecodeRequestFunc

MakeGinBindingDecodeRequestFunc bindable requestType can only be struct or pointer of struct

func MustGinContext

func MustGinContext(ctx context.Context) *gin.Context

MustGinContext returns *gin.Context like GinContext but panic if not found

func MustHttpRequest

func MustHttpRequest(ctx context.Context) *http.Request

MustHttpRequest returns *http.Request associated with given context, panic if not found

func NewBadRequestError

func NewBadRequestError(err error) error

func NewBindingError

func NewBindingError(e error) error

func NewDirFS

func NewDirFS(dir string, fsys fs.FS, opts ...DirFSOption) fs.FS

func NewHttpError

func NewHttpError(sc int, err error, headers ...http.Header) error

func NewHttpGinHandlerFunc

func NewHttpGinHandlerFunc(handlerFunc http.HandlerFunc) gin.HandlerFunc

NewHttpGinHandlerFunc Integrate http.HandlerFunc with GIN handler

func NewKitGinHandlerFunc

func NewKitGinHandlerFunc(s *httptransport.Server) gin.HandlerFunc

NewKitGinHandlerFunc Integrate go-kit Server with GIN handler

func NewOSDirFS

func NewOSDirFS(dir string, opts ...DirFSOption) fs.FS

func NewSimpleGinLogFormatter

func NewSimpleGinLogFormatter(logger log.ContextualLogger, defaultLevel log.LoggingLevel, levels map[RequestMatcher]log.LoggingLevel) gin.LogFormatter

NewSimpleGinLogFormatter is a convenient function that returns a simple gin.LogFormatter without request filtering Normally, LoggingCustomizer configures more complicated gin logging schema automatically. This function is provided purely for integrating with 3rd-party libraries that configures gin.Engine separately. e.g. KrakenD in API Gateway Service

func NormalizedPath

func NormalizedPath(path string) string

NormalizedPath removes path parameter name from path. path "/path/with/:param" is effectively same as "path/with/:other_param_name"

func OrderedFS

func OrderedFS(fsys fs.FS, defaultOrder int) fs.FS

OrderedFS returns a fs.FS that also implements order.Ordered if the given fs.FS is already implement the order.Ordered, "defaultOrder" is ignored

func PropertiesAware

func PropertiesAware(props *ServerProperties) gin.HandlerFunc

PropertiesAware is a Gin middleware mandatory for all mappings. It save necessary properties into request's context. e.g. context-path The saved properties can be used in many components/utilities.

func SetKV

func SetKV(ctx context.Context, key interface{}, value interface{})

SetKV set a kv pair to given context if: - The context is a utils.MutableContext - The context has utils.MutableContext as parent/ancestors - The context contains *gin.Context The value then can be obtained via context.Context.Value(key)

This function uses utils.FindMutableContext and GinContext() to find KV storage. Then store KV pair using following rule: - If utils.FindMutableContext returns non-nil, utils.MutableContext interface is used - If utils.FindMutableContext returns nil but *gin.Context is found:

  • If the key is string, KV pair is set as-is
  • Otherwise, uses fmt.Sprintf(`%v`, key) as key and set KV pair

- If none of conditions met, this function does nothing

func TextResponseEncoder

func TextResponseEncoder() httptransport.EncodeResponseFunc

func TextWriteFunc

func TextWriteFunc(rw http.ResponseWriter, v interface{}) error

Types

type BadRequestError

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

func (BadRequestError) StatusCode

func (_ BadRequestError) StatusCode() int

StatusCode implements StatusCoder

func (BadRequestError) Unwrap

func (e BadRequestError) Unwrap() error

type BindingError

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

func (BindingError) StatusCode

func (_ BindingError) StatusCode() int

StatusCode implements StatusCoder

func (BindingError) Unwrap

func (e BindingError) Unwrap() error

type BodyContainer

type BodyContainer interface {
	Body() interface{}
}

BodyContainer is a reponse body wrapping interface. this interface is majorly used internally for mapping

type ConditionalMiddleware

type ConditionalMiddleware interface {
	Condition() RequestMatcher
}

type Controller

type Controller interface {
	Mappings() []Mapping
}

type Customizer

type Customizer interface {
	Customize(ctx context.Context, r *Registrar) error
}

Customizer is invoked by Registrar at the beginning of initialization, customizers can register anything except for additional customizers If a customizer retains the given context in anyway, it should also implement PostInitCustomizer to release it

type DirFSOption

type DirFSOption int64
const (
	DirFSAllowListDirectory DirFSOption = 1 << iota
)

type EmptyRequest

type EmptyRequest struct{}

type EncodeOption

type EncodeOption struct {
	ContentType string
	Writer      http.ResponseWriter
	Response    interface{}
	WriteFunc   func(rw http.ResponseWriter, v interface{}) error
}

type EncodeOptions

type EncodeOptions func(opt *EncodeOption)

type EndpointMapping

type EndpointMapping MvcMapping

EndpointMapping defines REST API mapping. REST API is usually implemented by Controller and accept/produce JSON objects

type Engine

type Engine struct {
	*gin.Engine
	// contains filtered or unexported fields
}

func NewEngine

func NewEngine() *Engine

func (*Engine) ServeHTTP

func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request)

type EngineOptions

type EngineOptions func(*Engine)

type ErrorTranslateFunc

type ErrorTranslateFunc func(ctx context.Context, err error) error

ErrorTranslateFunc is similar to ErrorTranslator in function format. Mostly used for selective error translation registration (ErrorHandlerMapping). Same implementing rules applies

func (ErrorTranslateFunc) Translate

func (fn ErrorTranslateFunc) Translate(ctx context.Context, err error) error

type ErrorTranslateMapping

type ErrorTranslateMapping interface {
	Mapping
	Matcher() RouteMatcher
	Order() int
	Condition() RequestMatcher
	TranslateFunc() ErrorTranslateFunc
}

func NewErrorTranslateMapping

func NewErrorTranslateMapping(name string, order int, matcher RouteMatcher, cond RequestMatcher, translateFunc ErrorTranslateFunc) ErrorTranslateMapping

type ErrorTranslator

type ErrorTranslator interface {
	Translate(ctx context.Context, err error) error
}

ErrorTranslator can be registered via web.Registrar it will contribute our MvcMapping's error handling process. Note: it won't contribute Middleware's error handling

Implementing Notes:

  1. if it doesn't handle the error, return same error
  2. if custom StatusCode is required, make the returned error implement StatusCoder
  3. if custom Header is required, make the returned error implement Headerer
  4. we have HttpError to help with custom Headerer and StatusCoder implementation

type GinErrorHandlingCustomizer

type GinErrorHandlingCustomizer struct {
}

GinErrorHandlingCustomizer implements Customizer

func NewGinErrorHandlingCustomizer

func NewGinErrorHandlingCustomizer() *GinErrorHandlingCustomizer

func (GinErrorHandlingCustomizer) Customize

type HandlerFunc

type HandlerFunc http.HandlerFunc

HandlerFunc have same signature as http.HandlerFunc with additional assurance: - the http.Request used on this HandlerFunc version contains a mutable context utils.MutableContext

type Headerer

type Headerer interface {
	Headers() http.Header
}

Headerer is same interface defined in "github.com/go-kit/kit/transport/http" this interface is majorly used internally with error handling If an error value implements Headerer, the provided headers will be applied to the response writer, after the Content-Type is set.

type HttpError

type HttpError struct {
	SC int
	H  http.Header
	// contains filtered or unexported fields
}

HttpError implements error, json.Marshaler, StatusCoder, Headerer Note: Do not use HttpError as a map key, because is is not hashable (it contains http.Header which is a map)

func (HttpError) Headers

func (e HttpError) Headers() http.Header

Headers implements Headerer

func (HttpError) MarshalJSON

func (e HttpError) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (HttpError) StatusCode

func (e HttpError) StatusCode() int

StatusCode implements StatusCoder

type HttpErrorResponse

type HttpErrorResponse struct {
	StatusText string            `json:"error,omitempty"`
	Message    string            `json:"message,omitempty"`
	Details    map[string]string `json:"details,omitempty"`
}

type LazyHeaderWriter

type LazyHeaderWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

LazyHeaderWriter makes sure that status code and headers is overwritten at last second (when invoke Write([]byte) (int, error). Calling WriteHeader(int) would not actually send the header. Calling it multiple times to update status code Doing so allows response encoder and error handling to send different header and status code

func NewLazyHeaderWriter

func NewLazyHeaderWriter(w http.ResponseWriter) *LazyHeaderWriter

func (*LazyHeaderWriter) Header

func (w *LazyHeaderWriter) Header() http.Header

func (*LazyHeaderWriter) Write

func (w *LazyHeaderWriter) Write(p []byte) (int, error)

func (*LazyHeaderWriter) WriteHeader

func (w *LazyHeaderWriter) WriteHeader(code int)

func (*LazyHeaderWriter) WriteHeaderNow

func (w *LazyHeaderWriter) WriteHeaderNow()

type LoggingCustomizer

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

LoggingCustomizer implements Customizer and PostInitCustomizer

func NewLoggingCustomizer

func NewLoggingCustomizer(props ServerProperties) *LoggingCustomizer

func (LoggingCustomizer) Customize

func (c LoggingCustomizer) Customize(ctx context.Context, r *Registrar) error

func (LoggingCustomizer) PostInit

func (c LoggingCustomizer) PostInit(_ context.Context, _ *Registrar) error

type LoggingLevelProperties

type LoggingLevelProperties struct {
	Method  string           `json:"method"`
	Pattern string           `json:"pattern"`
	Level   log.LoggingLevel `json:"level"`
}

LoggingLevelProperties is used to override logging level on particular set of paths the LoggingProperties.Pattern support wildcard and should not include "context-path" the LoggingProperties.Method is space separated values. If left blank or contains "*", it matches all methods

type LoggingProperties

type LoggingProperties struct {
	Enabled      bool                              `json:"enabled"`
	DefaultLevel log.LoggingLevel                  `json:"default-level"`
	Levels       map[string]LoggingLevelProperties `json:"levels"`
}

type Mapping

type Mapping interface {
	Name() string
}

Mapping generic interface for all kind of endpoint mappings

type MergedFS

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

MergedFS implements fs.FS and fs.GlobFS

func NewMergedFS

func NewMergedFS(atLeastOne fs.FS, fs ...fs.FS) *MergedFS

func (*MergedFS) Glob

func (m *MergedFS) Glob(pattern string) (ret []string, err error)

func (*MergedFS) Open

func (m *MergedFS) Open(name string) (fs.File, error)

type Middleware

type Middleware interface {
	HandlerFunc() HandlerFunc
}

type MiddlewareGinMapping

type MiddlewareGinMapping interface {
	MiddlewareMapping
	GinHandlerFunc() gin.HandlerFunc
}

func NewMiddlewareGinMapping

func NewMiddlewareGinMapping(name string, order int, matcher RouteMatcher, cond RequestMatcher, handlerFunc gin.HandlerFunc) MiddlewareGinMapping

type MiddlewareMapping

type MiddlewareMapping interface {
	Mapping
	Matcher() RouteMatcher
	Order() int
	Condition() RequestMatcher
	HandlerFunc() HandlerFunc
}

func NewMiddlewareMapping

func NewMiddlewareMapping(name string, order int, matcher RouteMatcher, cond RequestMatcher, handlerFunc HandlerFunc) MiddlewareMapping

type MvcHandlerFunc

type MvcHandlerFunc interface{}

MvcHandlerFunc is a function with following signature

  • one or two input parameters with 1st as context.Context and 2nd as <request>
  • at least two output parameters with 2nd last as <response> and last as error

See rest.EndpointFunc, template.ModelViewHandlerFunc

type MvcHandlerFuncReturnMapper

type MvcHandlerFuncReturnMapper func(*[]reflect.Value) (interface{}, error)

type MvcHandlerFuncValidator

type MvcHandlerFuncValidator func(f *reflect.Value) error

MvcHandlerFuncValidator validate MvcHandlerFunc signature

type MvcMapping

type MvcMapping interface {
	RoutedMapping
	Endpoint() endpoint.Endpoint
	DecodeRequestFunc() httptransport.DecodeRequestFunc
	EncodeRequestFunc() httptransport.EncodeRequestFunc
	DecodeResponseFunc() httptransport.DecodeResponseFunc
	EncodeResponseFunc() httptransport.EncodeResponseFunc
	ErrorEncoder() httptransport.ErrorEncoder
}

MvcMapping defines HTTP handling that follows MVC pattern could be EndpointMapping or TemplateMapping

func NewMvcMapping

func NewMvcMapping(name, group, path, method string, condition RequestMatcher,
	endpoint endpoint.Endpoint,
	decodeRequestFunc httptransport.DecodeRequestFunc,
	encodeRequestFunc httptransport.EncodeRequestFunc,
	decodeResponseFunc httptransport.DecodeResponseFunc,
	encodeResponseFunc httptransport.EncodeResponseFunc,
	errorEncoder httptransport.ErrorEncoder) MvcMapping

NewMvcMapping exported for inter-package usage only. Use builders.

type PostInitCustomizer

type PostInitCustomizer interface {
	Customizer
	PostInit(ctx context.Context, r *Registrar) error
}

PostInitCustomizer is invoked by Registrar after initialization, register anything in PostInitCustomizer.PostInit would cause error or takes no effect

type PriorityGinContextCustomizer

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

PriorityGinContextCustomizer implements Customizer and order.PriorityOrdered

func NewPriorityGinContextCustomizer

func NewPriorityGinContextCustomizer(properties *ServerProperties) *PriorityGinContextCustomizer

func (PriorityGinContextCustomizer) Customize

func (PriorityGinContextCustomizer) PriorityOrder

func (c PriorityGinContextCustomizer) PriorityOrder() int

type RecoveryCustomizer

type RecoveryCustomizer struct {
}

RecoveryCustomizer implements Customizer

func NewRecoveryCustomizer

func NewRecoveryCustomizer() *RecoveryCustomizer

func (RecoveryCustomizer) Customize

func (c RecoveryCustomizer) Customize(ctx context.Context, r *Registrar) error

type Registrar

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

func NewRegistrar

func NewRegistrar(g *Engine, properties ServerProperties) *Registrar

func (*Registrar) AddEngineOptions

func (r *Registrar) AddEngineOptions(opts ...EngineOptions) error

AddEngineOptions customize Engine

func (*Registrar) AddGlobalMiddlewares

func (r *Registrar) AddGlobalMiddlewares(handlerFuncs ...gin.HandlerFunc) error

AddGlobalMiddlewares add middleware to all mapping

func (*Registrar) AddOption

func (r *Registrar) AddOption(opt httptransport.ServerOption) error

AddOption calls AddOptionWithOrder with 0 order value

func (*Registrar) AddOptionWithOrder

func (r *Registrar) AddOptionWithOrder(opt httptransport.ServerOption, o int) error

AddOptionWithOrder add go-kit ServerOption with order. httptransport.ServerOption are ordered using order.OrderedFirstCompare

func (*Registrar) Cleanup

func (r *Registrar) Cleanup(ctx context.Context) (err error)

Cleanup kick off post initialization cleanups Note: This function is exported for test utilities. Normal applications should use Registrar.Run which invokes this function internally.

func (*Registrar) Initialize

func (r *Registrar) Initialize(ctx context.Context) (err error)

Initialize should be called during application startup, last change to change configurations, load templates, etc Note: This function is exported for test utilities. Normal applications should use Registrar.Run which invokes this function internally.

func (*Registrar) MustRegister

func (r *Registrar) MustRegister(items ...interface{})

func (*Registrar) Register

func (r *Registrar) Register(items ...interface{}) (err error)

Register is the entry point to register Controller, Mapping and other web related objects supported items type are:

  • Customizer
  • Controller
  • EndpointMapping
  • StaticMapping
  • TemplateMapping
  • MiddlewareMapping
  • ErrorTranslateMapping
  • ErrorTranslator
  • struct that contains exported Controller fields
  • fs.FS

func (*Registrar) RegisterWithLifecycle

func (r *Registrar) RegisterWithLifecycle(lc fx.Lifecycle, items ...interface{})

RegisterWithLifecycle is a convenient function to schedule item registration in FX lifecycle

func (*Registrar) Run

func (r *Registrar) Run(ctx context.Context) (err error)

Run configure and start gin engine

func (*Registrar) ServerPort

func (r *Registrar) ServerPort() int

ServerPort returns the port of started server, returns 0 if server is not initialized

func (*Registrar) Stop

func (r *Registrar) Stop(ctx context.Context) (err error)

Stop closes http server

func (*Registrar) WarnDuplicateMiddlewares

func (r *Registrar) WarnDuplicateMiddlewares(ifWarn bool, excludedPath ...string)

type RequestMatcher

type RequestMatcher interface {
	matcher.ChainableMatcher
}

RequestMatcher is a typed ChainableMatcher that accept *http.Request or http.Request

type RequestPreProcessor

type RequestPreProcessor interface {
	Process(r *http.Request) error
	Name() RequestPreProcessorName
}

type RequestPreProcessorName

type RequestPreProcessorName string

type RequestRewriter

type RequestRewriter interface {
	// HandleRewrite take the rewritten request and put it through the entire handling cycle.
	// The http.Request.Context() is carried over
	// Note: if no error is returned, caller should stop processing the original request and discard the original request
	HandleRewrite(rewritten *http.Request) error
}

RequestRewriter handles request rewrite. e.g. rewrite http.Request.URL.Path

type Response

type Response struct {
	SC int
	H  http.Header
	B  interface{}
}

func (Response) Body

func (r Response) Body() interface{}

Body implements BodyContainer

func (Response) Headers

func (r Response) Headers() http.Header

Headers implements httptransport.Headerer and Headerer

func (Response) StatusCode

func (r Response) StatusCode() int

StatusCode implements httptransport.StatusCoder and StatusCoder

type Route

type Route struct {
	Method string
	Path   string
	Group  string
}

Route contains information needed for registering handler func in gin.Engine

type RouteMatcher

type RouteMatcher interface {
	matcher.ChainableMatcher
}

RouteMatcher is a typed ChainableMatcher that accept *Route or Route

type RoutedMapping

type RoutedMapping interface {
	Mapping
	Group() string
	Path() string
	Method() string
	Condition() RequestMatcher
}

RoutedMapping for endpoints that matches specific path, method and optionally a RequestMatcher as condition

type ServerProperties

type ServerProperties struct {
	Port        int               `json:"port"`
	ContextPath string            `json:"context-path"`
	Logging     LoggingProperties `json:"logging"`
}

func BindServerProperties

func BindServerProperties(ctx *bootstrap.ApplicationContext) ServerProperties

BindServerProperties create and bind a ServerProperties using default prefix

func NewServerProperties

func NewServerProperties() *ServerProperties

NewServerProperties create a ServerProperties with default values

type SimpleGinMapping

type SimpleGinMapping interface {
	SimpleMapping
	GinHandlerFunc() gin.HandlerFunc
}

SimpleGinMapping simple mapping of gin.HandlerFunc

func NewSimpleGinMapping

func NewSimpleGinMapping(name, group, path, method string, condition RequestMatcher, handlerFunc gin.HandlerFunc) SimpleGinMapping

type SimpleMapping

type SimpleMapping interface {
	RoutedMapping
	HandlerFunc() HandlerFunc
}

SimpleMapping endpoints that are directly implemented as HandlerFunc

func NewSimpleMapping

func NewSimpleMapping(name, group, path, method string, condition RequestMatcher, handlerFunc HandlerFunc) SimpleMapping

type StaticMapping

type StaticMapping interface {
	Mapping
	Path() string
	StaticRoot() string
	Aliases() map[string]string
	AddAlias(path, filePath string) StaticMapping
}

StaticMapping defines static assets mapping. e.g. javascripts, css, images, etc

type StatusCoder

type StatusCoder interface {
	StatusCode() int
}

StatusCoder is same interface defined in "github.com/go-kit/kit/transport/http" this interface is majorly used internally with error handling

type TemplateMapping

type TemplateMapping MvcMapping

TemplateMapping defines templated MVC mapping. e.g. html templates Templated MVC is usually implemented by Controller and produce a template and model for dynamic html generation

type Validate

type Validate struct {
	*validator.Validate
}

Validate is a thin wrapper around validator/v10, which prevent modifying TagName

func Validator

func Validator() *Validate

Validator returns the global validator for binding. Callers can register custom validators

func (*Validate) SetTagName

func (v *Validate) SetTagName(name string)

func (*Validate) SetTranslations

func (v *Validate) SetTranslations(trans ut.Translator, regFn func(*validator.Validate, ut.Translator) error) error

SetTranslations registers default translations using given regFn

func (*Validate) WithTagName

func (v *Validate) WithTagName(name string) *Validate

WithTagName create a shallow copy of internal validator.Validate with different tag name

type ValidationErrors

type ValidationErrors struct {
	validator.ValidationErrors
}

func (ValidationErrors) MarshalJSON

func (e ValidationErrors) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (ValidationErrors) StatusCode

func (_ ValidationErrors) StatusCode() int

StatusCode implements StatusCoder

func (ValidationErrors) Unwrap

func (e ValidationErrors) Unwrap() error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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