web

package
v0.15.1 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2024 License: Apache-2.0 Imports: 33 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 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 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 JsonWriteFunc

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

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 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 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 an additional interface that a user response object or error could implement. This interface is majorly used internally for mapping

type ConditionalMiddleware

type ConditionalMiddleware interface {
	Condition() RequestMatcher
}

ConditionalMiddleware is an additional interface that a Middleware can implement to control when the middleware is applied. e.g. a middleware want to be applied if request's header contains "Authorization"

type Controller

type Controller interface {
	Mappings() []Mapping
}

Controller is usually implemented by user-domain types to provide a group of HTTP handling logics. Each Controller provides a list of Mapping that defines how HTTP requests should be handled. See 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 DecodeRequestFunc added in v0.14.0

type DecodeRequestFunc func(ctx context.Context, httpReq *http.Request) (req interface{}, err error)

DecodeRequestFunc extracts a payload from a http.Request. It's designed to be used by MvcMapping. Example of common implementation includes JSON decoder or form data extractor

func GinBindingRequestDecoder added in v0.14.0

func GinBindingRequestDecoder(instantiateFunc func() interface{}) DecodeRequestFunc

GinBindingRequestDecoder is a DecodeRequestFunc utilizing gin.Context's binding capabilities. The decoder uses the provided function to instantiate the object. If the instantiateFunc returns a non-pointer value, the decoder uses reflect to find its pointer

type DirFSOption

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

type EmptyRequest

type EmptyRequest struct{}

type EncodeErrorFunc added in v0.14.0

type EncodeErrorFunc func(ctx context.Context, err error, w http.ResponseWriter)

EncodeErrorFunc is responsible for encoding an error to the ResponseWriter. It's designed to be used by MvcMapping. Example of common implementation includes JSON encoder or template based HTML generator.

func JsonErrorEncoder

func JsonErrorEncoder() EncodeErrorFunc

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

type EncodeResponseFunc func(ctx context.Context, rw http.ResponseWriter, resp interface{}) error

EncodeResponseFunc encodes a user response object into http.ResponseWriter. It's designed to be used by MvcMapping. Example of common implementation includes JSON encoder or template based HTML generator.

func BytesResponseEncoder

func BytesResponseEncoder() EncodeResponseFunc

func CustomResponseEncoder

func CustomResponseEncoder(opts ...EncodeOptions) EncodeResponseFunc

func JsonResponseEncoder

func JsonResponseEncoder() EncodeResponseFunc

func TextResponseEncoder

func TextResponseEncoder() EncodeResponseFunc

type EndpointMapping

type EndpointMapping MvcMapping

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

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
}

ErrorTranslateMapping defines how errors should be handled before it's rendered into http.ResponseWriter. See weberror.MappingBuilder

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 Headerer

type Headerer interface {
	Headers() http.Header
}

Headerer is an additional interface that a user response object or error could implement. EncodeResponseFunc and EncodeErrorFunc should typically check for this interface and manipulate response headers accordingly

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 is generic interface for all kind of HTTP mappings. User-domain do not typically to implement this interface. Instead, predefined implementation and their builders should be used. See StaticMapping, RoutedMapping, MvcMapping, SimpleMapping, etc.

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() http.HandlerFunc
}

Middleware defines a http.HandlerFunc to be used by MiddlewareMapping and middleware.MappingBuilder

type MiddlewareGinMapping

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

MiddlewareGinMapping is a MiddlewareMapping that supported by gin.HandlerFunc See middleware.MappingBuilder

func NewMiddlewareGinMapping

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

NewMiddlewareGinMapping create a MiddlewareGinMapping with gin.HandlerFunc It's recommended to use middleware.MappingBuilder instead of this function: e.g. <code> middleware.NewBuilder("my-auth").Order(-10).Use(func...).Build() </code>

type MiddlewareMapping

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

MiddlewareMapping defines middlewares that applies to all or selected set (via Matcher and Condition) of requests. Middlewares are often used for task like security, pre/post processing request or response, metrics measurements, etc. See middleware.MappingBuilder

func NewMiddlewareMapping

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

NewMiddlewareMapping create a MiddlewareMapping with http.HandlerFunc It's recommended to use middleware.MappingBuilder instead of this function: e.g. <code> middleware.NewBuilder("my-auth").Order(-10).Use(func...).Build() </code>

type MvcHandlerFunc

type MvcHandlerFunc func(c context.Context, request interface{}) (response interface{}, err error)

MvcHandlerFunc is the generic function to be used for MvcMapping. See MvcMapping, rest.EndpointFunc, template.ModelViewHandlerFunc

type MvcMapping

type MvcMapping interface {
	RoutedMapping
	DecodeRequestFunc() DecodeRequestFunc
	EncodeResponseFunc() EncodeResponseFunc
	EncodeErrorFunc() EncodeErrorFunc
	HandlerFunc() MvcHandlerFunc
}

MvcMapping defines HTTP handling that follows MVC pattern: 1. The http.Request is decoded in to a request model object using MvcMapping.DecodeRequestFunc(). 2. The request model object is processed by MvcMapping.HandlerFunc() and a response model object is returned. 3. The response model object is rendered into http.ResponseWriter using MvcMapping.EncodeResponseFunc(). 4. If any steps yield error, the error is rendered into http.ResponseWriter using MvcMapping.EncodeErrorFunc()

Note: Functions here are all weakly typed signature. User-domain developers typically should use mapping builders (rest.MappingBuilder, template.MappingBuilder, etc) to create concrete MvcMapping instances. See EndpointMapping or TemplateMapping

func NewMvcMapping

func NewMvcMapping(name, group, path, method string, condition RequestMatcher,
	mvcHandlerFunc MvcHandlerFunc,
	decodeRequestFunc DecodeRequestFunc,
	encodeResponseFunc EncodeResponseFunc,
	errorEncoder EncodeErrorFunc) MvcMapping

NewMvcMapping create a MvcMapping It's recommended to use rest.MappingBuilder or template.MappingBuilder instead of this function: e.g. <code> rest.Put("/path/to/api").EndpointFunc(func...).Build() template.Post("/path/to/page").HandlerFunc(func...).Build() </code>

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) 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) 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 Headerer

func (Response) StatusCode

func (r Response) StatusCode() int

StatusCode implements 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 defines dynamic HTTP handling with specific HTTP Route (path and method) and optionally a RequestMatcher as condition. RoutedMapping includes SimpleMapping, MvcMapping, etc.

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 is a SimpleMapping that supported by gin.HandlerFunc See mapping.MappingBuilder

func NewSimpleGinMapping

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

NewSimpleGinMapping create a SimpleGinMapping. It's recommended to use mapping.MappingBuilder instead of this function: e.g. <code> mapping.Post("/path/to/api").HandlerFunc(func...).Build() </code>

type SimpleMapping

type SimpleMapping interface {
	RoutedMapping
	HandlerFunc() http.HandlerFunc
}

SimpleMapping endpoints that are directly implemented as HandlerFunc. See mapping.MappingBuilder

func NewSimpleMapping

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

NewSimpleMapping create a SimpleMapping. It's recommended to use mapping.MappingBuilder instead of this function: e.g. <code> mapping.Post("/path/to/api").HandlerFunc(func...).Build() </code>

type StaticMapping

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

StaticMapping defines static assets handling. e.g. javascripts, css, images, etc. See assets.New()

type StatusCoder

type StatusCoder interface {
	StatusCode() int
}

StatusCoder is an additional interface that a user response object or error could implement. EncodeResponseFunc and EncodeErrorFunc should typically check for this interface and manipulate response status code accordingly

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. See template.MappingBuilder

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
internal
mvc

Jump to

Keyboard shortcuts

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