runtime

package
v0.5.0-rc1 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2024 License: Apache-2.0 Imports: 48 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetOpenAPISchemas added in v0.5.0

func GetOpenAPISchemas() *openapi3.T

func IsBidiStreamRequest

func IsBidiStreamRequest(c *gin.Context) bool

IsBidiStreamRequest returns true if the incoming request is a websocket request.

func IsUnidiStreamRequest

func IsUnidiStreamRequest(c *gin.Context) bool

IsUnidiStreamRequest returns true if the incoming request is a watching request.

func NewStatsCollector

func NewStatsCollector() prometheus.Collector

func Translate

func Translate(ctx context.Context, s string) string

Types

type Attributes

type Attributes uint64

func (*Attributes) HasAll

func (t *Attributes) HasAll(u Attributes) bool

func (*Attributes) HasAny

func (t *Attributes) HasAny(u Attributes) bool

func (*Attributes) With

func (t *Attributes) With(u Attributes)

type ErrorHandle

type ErrorHandle = func(c *gin.Context) error

type ErrorHandler

type ErrorHandler interface {
	Handle(c *gin.Context) error
}

type ErrorResponse

type ErrorResponse struct {
	Message    string `json:"message"`
	Status     int    `json:"status"`
	StatusText string `json:"statusText"`
	// contains filtered or unexported fields
}

type HTTPHandle

type HTTPHandle = http.HandlerFunc

type HTTPHandler

type HTTPHandler = http.Handler

type Handle

type Handle = func(*gin.Context)

func I18n

func I18n() Handle

func If

func If(match func(*gin.Context) bool, then Handle) Handle

If is a gin middleware, which is used for judging the incoming request, execute given handle if matched.

func Only

func Only(match func(*gin.Context) bool) Handle

Only is a gin middleware, which is used for judging the incoming request, aborts with 403 if not match.

func OnlyLocalIP

func OnlyLocalIP() Handle

OnlyLocalIP judges the incoming request whether is from localhost, aborts with 403 if not match.

func Per

func Per(hashRequest func(*gin.Context) string, provideHandler func() Handle) Handle

Per is a gin middleware, which is used for providing new handler for different incoming request.

func PerIP

func PerIP(provideHandler func() Handle) Handle

PerIP provides new handler according to incoming request IP.

func RequestCounting

func RequestCounting(max int, wait time.Duration) Handle

RequestCounting limits the request count in the given maximum, returns 429 if the new request has waited with the given duration.

func RequestShaping

func RequestShaping(qps, slack int, latency time.Duration) Handle

RequestShaping arranges all requests to be received on the given qps, returns 429 if the new request can be allowed within the given latency, if the given latency is not positive, RequestShaping will never return 429.

func RequestThrottling

func RequestThrottling(qps, burst int) Handle

RequestThrottling controls the request count per second and allows bursting, returns 429 if the new request is not allowed.

type Handler

type Handler interface {
	Handle(c *gin.Context)
}

type IHandler

type IHandler any

type IResourceHandler

type IResourceHandler interface {
	IHandler

	Kind() string
}

func Alias

func Alias(handler IResourceHandler, withKind string) IResourceHandler

Alias wraps the given resource handler with a new alias kind.

type IRouter

type IRouter interface {
	http.Handler

	// Use attaches a global middleware to the router.
	Use(...IHandler) IRouter
	// Group creates a new router group with the given string,
	// and returns the new router group.
	Group(string) IRouter
	// GroupIn creates a new router group with the given string,
	// but returns the original router group,
	// the new router group is passed to the given function.
	GroupIn(string, func(groupRouter IRouter)) IRouter
	// GroupRelativePath returns the relative path of router group.
	GroupRelativePath() string

	// Static registers GET/HEAD routers to serve the handler.
	Static(string, http.FileSystem) IRouter
	// Get registers GET router to serve the handler.
	Get(string, IHandler) IRouter
	// Post registers POST router to serve the handler.
	Post(string, IHandler) IRouter
	// Delete registers DELETE router to serve the handler.
	Delete(string, IHandler) IRouter
	// Patch registers PATCH router to serve the handler.
	Patch(string, IHandler) IRouter
	// Put registers PUT router to serve the handler.
	Put(string, IHandler) IRouter

	// Routes registers the reflected routes of a IHandler.
	//
	// Routes reflects the function descriptors as the below rules,
	// if the handler implements IResourceHandler as well.
	//
	//	Input : struct type.
	//	Output: any types.
	//
	//	* Basic APIs
	//
	//	func Create(<Input>) (<Output>, error)
	//	 ->   POST /<plural>
	//	func Get(<Input>) (<Output>, error)
	//	 ->    GET /<plural>/:id(?watch=true)
	//	func Update(<Input>) error
	//	 ->    PUT /<plural>/:id
	//	func Delete(<Input>) error
	//	 -> DELETE /<plural>/:id
	//	func Patch(<Input>) error
	//	 ->  Patch /<plural>/:id
	//	func CollectionCreate(<Input>) (<Output>, error)
	//	 ->   POST /<plural>/_/batch
	//	func CollectionGet(<Input>) (<Output>, (int,) error)
	//	 ->    GET /<plural>(?watch=true)
	//	func CollectionUpdate(<Input>) error
	//	 ->    PUT /<plural>
	//	func CollectionDelete(<Input>) error
	//	 -> DELETE /<plural>
	//
	//	* Extensional APIs
	//
	//	func Route<Something>(<Input(route:method=subpath)>) ((<Output>), (int,) error)
	//	 -> method /<plural>/:id/<subpath>(?watch=true)
	//	func CollectionRoute<Something>(<Input(route:method=subpath)>) ((<Output>), (int,) error)
	//	 -> method /<plural>/_/<subpath>(?watch=true)
	//
	// Otherwise, Routes tries to reflect the function descriptors as the below rules.
	//
	//	Input : struct type.
	//	Output: any types.
	//
	//	func <Anything>(<Input(route:method=path)>) ((<Output>), (int,) error)
	//	 -> method /<path>(?watch=true)
	//
	Routes(IHandler) IRouter
}

func NewRouter

func NewRouter(options ...RouterOption) IRouter

type RequestAttributesType

type RequestAttributesType = Attributes
const (
	RequestWithValidate RequestAttributesType = 1 << iota
	RequestWithGinContext

	RequestWithUnidiStream
	RequestWithBidiStream

	RequestWithBindingForm
	RequestWithBindingJSON
	RequestWithBindingHeader
	RequestWithBindingQuery
	RequestWithBindingPath
)

type RequestBidiStream

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

RequestBidiStream holds the request for dual-directions stream.

func (RequestBidiStream) Cancel

func (r RequestBidiStream) Cancel()

Cancel cancels the underlay context.Context.

func (RequestBidiStream) Deadline

func (r RequestBidiStream) Deadline() (deadline time.Time, ok bool)

Deadline implements context.Context.

func (RequestBidiStream) Done

func (r RequestBidiStream) Done() <-chan struct{}

Done implements context.Context.

func (RequestBidiStream) Err

func (r RequestBidiStream) Err() error

Err implements context.Context.

func (RequestBidiStream) Read

func (r RequestBidiStream) Read(p []byte) (n int, err error)

Read implements io.Reader.

func (RequestBidiStream) RecvJSON

func (r RequestBidiStream) RecvJSON(i any) error

RecvJSON receives JSON message from client and unmarshals into the given object.

func (RequestBidiStream) RecvMsg

func (r RequestBidiStream) RecvMsg() ([]byte, error)

RecvMsg receives message from client.

func (RequestBidiStream) SendJSON

func (r RequestBidiStream) SendJSON(i any) error

SendJSON marshals the given object as JSON and sends to client.

func (RequestBidiStream) SendMsg

func (r RequestBidiStream) SendMsg(data []byte) error

SendMsg sends the given data to client.

func (RequestBidiStream) Value

func (r RequestBidiStream) Value(key any) any

Value implements context.Context.

func (RequestBidiStream) Write

func (r RequestBidiStream) Write(p []byte) (n int, err error)

Write implements io.Writer.

type RequestCollection

type RequestCollection[Q, S ~func(*sql.Selector)] struct {
	RequestQuerying[Q] `query:",inline"`
	RequestSorting[S]  `query:",inline"`
	RequestExtracting  `query:",inline"`
	RequestPagination  `query:",inline"`
}

RequestCollection holds the requesting data of collection, including querying, sorting, extracting and pagination.

type RequestExtracting

type RequestExtracting struct {
	// Extracts specifies the fields for querying,
	// i.e. /v1/repositories?extract=-id&extract=name.
	Extracts []string `query:"extract,omitempty"`
}

RequestExtracting holds the requesting extraction data.

func (RequestExtracting) Extracting

func (r RequestExtracting) Extracting(allowFields []string, defaultFields ...string) ([]string, bool)

Extracting returns the field list with the given allow list, returns false if there are not any extracting key requesting and default list.

func (RequestExtracting) With

func (r RequestExtracting) With(fields ...string) RequestExtracting

With appends the included field list to the extracting list.

func (RequestExtracting) Without

func (r RequestExtracting) Without(fields ...string) RequestExtracting

Without appends the excluded field list to the extracting list.

type RequestPagination

type RequestPagination struct {
	// Page specifies the page number for querying,
	// i.e. /v1/repositories?page=1&perPage=10.
	Page int `query:"page,default=1"`

	// PerPage specifies the page size for querying,
	// i.e. /v1/repositories?page=1&perPage=10.
	PerPage int `query:"perPage,default=100"`
}

RequestPagination holds the requesting pagination data.

func (RequestPagination) Limit

func (r RequestPagination) Limit() int

Limit returns the limit of paging.

func (RequestPagination) Offset

func (r RequestPagination) Offset() int

Offset returns the offset of paging.

func (RequestPagination) Paging

func (r RequestPagination) Paging() (limit, offset int, request bool)

Paging returns the limit and offset of paging, returns false if there is no pagination requesting.

type RequestQuerying

type RequestQuerying[T ~func(s *sql.Selector)] struct {
	// Query specifies the content to search some preset fields,
	// it's a case-insensitive fuzzy filter,
	// i.e. /v1/repositories?query=repo%2Fname.
	Query *string `query:"query,omitempty"`
}

RequestQuerying holds the requesting query data.

func (RequestQuerying[T]) Querying

func (r RequestQuerying[T]) Querying(searchFields []string) (T, bool)

Querying returns an OR predicate with the given search fields, returns false if there is no query requesting.

type RequestSorting

type RequestSorting[T ~func(*sql.Selector)] struct {
	// Sorts specifies the fields for sorting,
	// i.e. /v1/repositories?sort=-createTime&sort=name.
	Sorts []string `query:"sort,omitempty"`
}

RequestSorting holds the requesting sort data.

func (RequestSorting[T]) Sorting

func (r RequestSorting[T]) Sorting(allowKeys []string, defaultOrders ...T) ([]T, bool)

Sorting returns the order list with the given allow list, returns false if there are not any sorting key requesting and default list.

func (RequestSorting[T]) WithAsc

func (r RequestSorting[T]) WithAsc(fields ...string) RequestSorting[T]

WithAsc appends the asc sorting field list to the sorting list.

func (RequestSorting[T]) WithDesc

func (r RequestSorting[T]) WithDesc(fields ...string) RequestSorting[T]

WithDesc appends the desc sorting list to the sorting list.

type RequestUnidiStream

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

RequestUnidiStream holds the request for single-direction stream.

func (RequestUnidiStream) Cancel

func (r RequestUnidiStream) Cancel()

Cancel cancels the underlay context.Context.

func (RequestUnidiStream) Deadline

func (r RequestUnidiStream) Deadline() (deadline time.Time, ok bool)

Deadline implements context.Context.

func (RequestUnidiStream) Done

func (r RequestUnidiStream) Done() <-chan struct{}

Done implements context.Context.

func (RequestUnidiStream) Err

func (r RequestUnidiStream) Err() error

Err implements context.Context.

func (RequestUnidiStream) SendJSON

func (r RequestUnidiStream) SendJSON(i any) error

SendJSON marshals the given object as JSON and sends to client.

func (RequestUnidiStream) SendMsg

func (r RequestUnidiStream) SendMsg(data []byte) error

SendMsg sends the given data to client.

func (RequestUnidiStream) Value

func (r RequestUnidiStream) Value(key any) any

Value implements context.Context.

func (RequestUnidiStream) Write

func (r RequestUnidiStream) Write(p []byte) (n int, err error)

Write implements io.Writer.

type ResourceProfile

type ResourceProfile struct {
	// Kinds holds the hierarchical kinds of the given route.
	Kinds []string
	// Resources holds the hierarchical resources of the given route.
	Resources []string
	// ResourcePaths holds the hierarchical resource paths of the given route.
	ResourcePaths []string
	// ResourcePathRefers holds the hierarchical resource path IDs of the given route.
	ResourcePathRefers []string
}

ResourceProfile holds the profile of a resource.

func (*ResourceProfile) DeepCopy

func (p *ResourceProfile) DeepCopy() (o ResourceProfile)

DeepCopy returns a deep copy of the resource profile.

func (*ResourceProfile) PluralPath

func (p *ResourceProfile) PluralPath() string

PluralPath returns the plural path of the resource.

func (*ResourceProfile) Prepend

func (p *ResourceProfile) Prepend(rp ResourceProfile)

Prepend prepends the given resource profile.

func (*ResourceProfile) SingularPath

func (p *ResourceProfile) SingularPath() string

SingularPath returns the singular path of the resource.

type ResponseAttributesType

type ResponseAttributesType = Attributes
const (
	ResponseWithPage ResponseAttributesType = 1 << iota
)

type ResponseCollection

type ResponseCollection struct {
	Type       string              `json:"type,omitempty"`
	Items      any                 `json:"items"`
	Pagination *ResponsePagination `json:"pagination,omitempty"`
}

ResponseCollection holds the response data of collection with a pagination.

func FullPageResponse

func FullPageResponse(data any, dataTotalSize int) *ResponseCollection

FullPageResponse returns the given data in a pagination, which treats the given data as a full page.

func NoPageResponse

func NoPageResponse(data any) *ResponseCollection

NoPageResponse returns the given data without pagination.

func PageResponse

func PageResponse(page, perPage int, data any, dataTotalSize int) *ResponseCollection

PageResponse returns the given data in a pagination, which calculates the pagination info with the given request page and perPage.

func TypedResponse

func TypedResponse(typ string, data any) *ResponseCollection

TypedResponse returns the given data in typed.

type ResponseFile

type ResponseFile struct {
	ContentType   string
	ContentLength int64
	Headers       map[string]string
	Reader        io.ReadCloser
}

ResponseFile is similar to render.Reader, but be able to close the file reader out of the handler processing.

func (ResponseFile) Close

func (r ResponseFile) Close() error

func (ResponseFile) Render

func (r ResponseFile) Render(w http.ResponseWriter) (err error)

func (ResponseFile) WriteContentType

func (r ResponseFile) WriteContentType(w http.ResponseWriter)

type ResponsePagination

type ResponsePagination struct {
	Page      int  `json:"page"`
	PerPage   int  `json:"perPage"`
	Total     int  `json:"total"`
	TotalPage int  `json:"totalPage"`
	Partial   bool `json:"partial"`
	NextPage  int  `json:"nextPage,omitempty"`
}

ResponsePagination holds the pagination data.

type Route

type Route struct {
	// RouteProfile holds the profile of a route.
	RouteProfile

	// GoCaller holds the reflect.Value of the method to call.
	GoCaller reflect.Value
	// GoPackage observes the package of the GoType.
	GoPackage string
	// GoType observes the type of the GoFunc.
	GoType string
	// GoFunc observes the name of the GoCaller.
	GoFunc string

	// RequestType observes the reflect.Type of the method to input.
	RequestType reflect.Type
	// RequestAttributes observes the attributes of the request.
	RequestAttributes RequestAttributesType
	// ResponseType observes the reflect.Type of the method to return.
	ResponseType reflect.Type
	// ResponseAttributes observes the attributes of the response.
	ResponseAttributes ResponseAttributesType
	// contains filtered or unexported fields
}

Route holds the information of a resource route.

type RouteAdviceProvider

type RouteAdviceProvider interface {
	// CanSet validates the given RouteAdviceReceiver can be set or not in prepare phase,
	// returns true if the given RouteAdviceReceiver can be injected.
	// The given RouteAdviceReceiver is stateless,
	// please do not perform additional operations on it.
	CanSet(RouteAdviceReceiver) bool

	// Set injects the valid RouteAdviceReceiver by this provider before validating,
	// the provider should set the corresponding advice to the target.
	Set(RouteAdviceReceiver)
}

RouteAdviceProvider is a provider to provide advice to the request of the reflected routes of a IHandler.

type RouteAdviceReceiver

type RouteAdviceReceiver any

RouteAdviceReceiver represents the type that can receive advice.

type RouteAuthorizeFunc

type RouteAuthorizeFunc func(*gin.Context, RouteProfile) int

RouteAuthorizeFunc is the function type of RouteAuthorizer.

func (RouteAuthorizeFunc) Authorize

func (fn RouteAuthorizeFunc) Authorize(c *gin.Context, p RouteProfile) int

Authorize implements the RouteAuthorizer interface.

type RouteAuthorizer

type RouteAuthorizer interface {
	// Authorize returns the status code of authorization result,
	// 200 if success, 401 if unauthorized, 403 if forbidden.
	Authorize(*gin.Context, RouteProfile) int
}

RouteAuthorizer holds the operation of authorization.

type RouteProfile

type RouteProfile struct {
	// ResourceProfile holds the resource profile of a route,
	// if the route is no belong to a IResourceHandler,
	// the ResourceProfile will be zero.
	ResourceProfile

	// Summary holds the brief of the route.
	Summary string
	// Description holds the detail of the route.
	Description string
	// Method holds the method of the route.
	Method string
	// Path holds the path of the route.
	Path string
	// Collection indicates the route that works for a collection of resources.
	Collection bool
	// Sub indicates the route is a sub route or not.
	Sub bool
	// Custom indicates the route is a custom route or not.
	Custom bool
	// CustomName indicates the real name of the custom route if Custom is true.
	CustomName string
}

RouteProfile holds the profile of a route.

func (RouteProfile) DeepCopy

func (p RouteProfile) DeepCopy() (o RouteProfile)

DeepCopy returns a deep copy of the resource route profile.

type Router

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

func (*Router) Delete

func (rt *Router) Delete(path string, handler IHandler) IRouter

func (*Router) Get

func (rt *Router) Get(path string, handler IHandler) IRouter

func (*Router) Group

func (rt *Router) Group(relativePath string) IRouter

func (*Router) GroupIn

func (rt *Router) GroupIn(relativePath string, doGroupRoute func(IRouter)) IRouter

func (*Router) GroupRelativePath

func (rt *Router) GroupRelativePath() string

func (*Router) Patch

func (rt *Router) Patch(path string, handler IHandler) IRouter

func (*Router) Post

func (rt *Router) Post(path string, handler IHandler) IRouter

func (*Router) Put

func (rt *Router) Put(path string, handler IHandler) IRouter

func (*Router) Routes

func (rt *Router) Routes(handler IHandler) IRouter

func (*Router) ServeHTTP

func (rt *Router) ServeHTTP(resp http.ResponseWriter, req *http.Request)

func (*Router) Static

func (rt *Router) Static(p string, fs http.FileSystem) IRouter

func (*Router) Use

func (rt *Router) Use(handlers ...IHandler) IRouter

type RouterOption

type RouterOption interface {
	// contains filtered or unexported methods
}

func ExposeOpenAPI

func ExposeOpenAPI() RouterOption

ExposeOpenAPI is a RouterOption to add route to serve the OpenAPI schema spec, and provide the SwaggerUI as well.

func SkipLoggingPaths

func SkipLoggingPaths(paths ...string) RouterOption

SkipLoggingPaths is a RouterOption to ignore logging for the given paths.

func WithDefaultHandler

func WithDefaultHandler(handler IHandler) RouterOption

WithDefaultHandler is a RouterOption to configure the default handler for gin.

func WithDefaultWriter

func WithDefaultWriter(w io.Writer) RouterOption

WithDefaultWriter is a RouterOption to configure the default writer for gin.

func WithResourceAuthorizer

func WithResourceAuthorizer(authorizer RouteAuthorizer) RouterOption

WithResourceAuthorizer if a RouterOption to configure the authorizer for the routes of IResourceHandler.

func WithRouteAdviceProviders

func WithRouteAdviceProviders(providers ...RouteAdviceProvider) RouterOption

WithRouteAdviceProviders is a RouterOption to configure the advice providers for the reflected routes of a IHandler.

type RouterOptions

type RouterOptions []RouterOption

func (RouterOptions) Apply

func (opts RouterOptions) Apply(fn func(o RouterOption) bool) (rOpts RouterOptions)

Apply applies the options one by one, and returns the residual options.

type StaticHttpFile

type StaticHttpFile struct {
	http.File

	Listable bool
	Embedded bool
}

func (StaticHttpFile) Readdir

func (f StaticHttpFile) Readdir(count int) ([]os.FileInfo, error)

func (StaticHttpFile) Stat

func (f StaticHttpFile) Stat() (fs.FileInfo, error)

type StaticHttpFileSystem

type StaticHttpFileSystem struct {
	http.FileSystem

	Listable bool
	Embedded bool
}

func (StaticHttpFileSystem) Open

func (fs StaticHttpFileSystem) Open(name string) (http.File, error)

type Validator

type Validator interface {
	// Validate returns error if the given request is invalid.
	Validate() error
}

Validator holds the operation of validation.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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