http

package
v1.2.13 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2024 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TraceIDKey     = "trace-id"
	RemoteIPKey    = "remote-ip"
	RequestTimeKey = "request-time"
)

Variables

Functions

func CheckRequestBodyPreprocessor added in v1.2.12

func CheckRequestBodyPreprocessor[request any, response any](endpoint *EndPoint[request, response], origin *gin.Context, dest PreprocessedContext[request, response])

func CheckRequestCookiesPreprocessor added in v1.2.12

func CheckRequestCookiesPreprocessor[request any, response any](endpoint *EndPoint[request, response], origin *gin.Context, dest PreprocessedContext[request, response])

func CheckRequestHeadersPreprocessor added in v1.2.12

func CheckRequestHeadersPreprocessor[request any, response any](endpoint *EndPoint[request, response], origin *gin.Context, dest PreprocessedContext[request, response])

func CheckRequestMethodPreprocessor added in v1.2.12

func CheckRequestMethodPreprocessor[request any, response any](endpoint *EndPoint[request, response], origin *gin.Context, dest PreprocessedContext[request, response])

func CheckRequestParamsPreprocessor added in v1.2.12

func CheckRequestParamsPreprocessor[request any, response any](endpoint *EndPoint[request, response], origin *gin.Context, dest PreprocessedContext[request, response])

func CheckRequestQueriesPreprocessor added in v1.2.12

func CheckRequestQueriesPreprocessor[request any, response any](endpoint *EndPoint[request, response], origin *gin.Context, dest PreprocessedContext[request, response])

func CheckStatusCode added in v1.2.13

func CheckStatusCode(resp ResponseParser, want ...Status) bool

CheckStatusCode check if the status code of the response is in the given status code list

example:

func main() {
	client := NewClient()
	response, executeErr := client.ExecuteRequest(
		NewRequest().WithPath("https://example.com/api/user").WithMethod(GET),
	)
	if executeErr != nil {
		panic(executeErr)
	}
	if !CheckStatusCode(response, 200, 201, 202) {
		panic("status code is not 200, 201 or 202")
	}
}

func LoadNormalRequestHeadersPreprocessor added in v1.2.12

func LoadNormalRequestHeadersPreprocessor[request any, response any](endpoint *EndPoint[request, response], origin *gin.Context, dest PreprocessedContext[request, response])

func ParseJsonResponse

func ParseJsonResponse[T any](resp ResponseParser, executeErr error) (data T, err error)

ParseJsonResponse parse json response from http response

example:

type User struct {
	Name string `json:"name"`
}

func main() {
	client := NewClient()
	response, executeErr := client.ExecuteRequest[User](
		NewRequest().WithPath("https://example.com/api/user").WithMethod(GET),
	)
	if executeErr != nil {
		panic(executeErr)
	}
}

then it will return a User object

func SetPayloadProcessor added in v1.2.9

func SetPayloadProcessor(contentType string, marshaller func(in []byte, receiver any) error)

func StatusCodeIs2XX added in v1.2.13

func StatusCodeIs2XX(resp ResponseParser) bool

StatusCodeIs2XX check if the status code of the response is 2XX

example:

func main() {
	client := NewClient()
	response, executeErr := client.ExecuteRequest(
		NewRequest().WithPath("https://example.com/api/user").WithMethod(GET),
	)
	if executeErr != nil {
		panic(executeErr)
	}
	if !StatusCodeIs2XX(response) {
		panic("status code is not 2XX")
	}
}

func StatusCodeIs4XX added in v1.2.13

func StatusCodeIs4XX(resp ResponseParser) bool

StatusCodeIs4XX check if the status code of the response is 4XX

example:

func main() {
	client := NewClient()
	response, executeErr := client.ExecuteRequest(
		NewRequest().WithPath("https://example.com/api/user").WithMethod(GET),
	)
	if executeErr != nil {
		panic(executeErr)
	}
	if !StatusCodeIs4XX(response) {
		panic("status code is not 4XX")
	}
}

func StatusCodeIs5XX added in v1.2.13

func StatusCodeIs5XX(resp ResponseParser) bool

StatusCodeIs5XX check if the status code of the response is 5XX

example:

func main() {
	client := NewClient()
	response, executeErr := client.ExecuteRequest(
		NewRequest().WithPath("https://example.com/api/user").WithMethod(GET),
	)
	if executeErr != nil {
		panic(executeErr)
	}
	if !StatusCodeIs5XX(response) {
		panic("status code is not 5XX")
	}
}

Types

type Chain added in v1.2.9

type Chain[request any, response any] []Handler[request, response]

func NewChain added in v1.2.9

func NewChain[request any, response any](handlers ...Handler[request, response]) Chain[request, response]

NewChain creates a new handler chain. example:

chain := NewChain[request, response](
	func(ctx Context[request, response]) {
		// do something
		ctx.Next()
	},
	func(ctx Context[request, response]) {
		// do something
		ctx.Next()
	},
)

func (Chain[request, response]) AddHandlerBack added in v1.2.9

func (c Chain[request, response]) AddHandlerBack(h ...Handler[request, response]) Chain[request, response]

AddHandlerBack adds handlers to the back of the handler chain. example:

chain.AddHandlerBack(
	func(ctx Context[request, response]) {
		// do something
		ctx.Next()
	},
	func(ctx Context[request, response]) {
		// do something
		ctx.Next()
	},
)

func (Chain[request, response]) AddHandlerFront added in v1.2.9

func (c Chain[request, response]) AddHandlerFront(h ...Handler[request, response]) Chain[request, response]

AddHandlerFront adds handlers to the front of the handler chain. example:

chain.AddHandlerFront(
	func(ctx Context[request, response]) {
		// do something
		ctx.Next()
	},
	func(ctx Context[request, response]) {
		// do something
		ctx.Next()
	},
)

func (Chain[request, response]) Execute added in v1.2.9

func (c Chain[request, response]) Execute(ctx Context[request, response])

Execute executes the handler chain.

type Client

type Client interface {
	ExecuteRequest(request RequestBuilder) (response ResponseParser, err error)
	ExecuteRawRequest(request *http.Request) (response *http.Response, err error)
}

func NewLoggerClient added in v1.2.12

func NewLoggerClient(log logger.Logger) Client

func NewMockClient added in v1.2.12

func NewMockClient(opts ...*MockOptions) Client

NewMockClient create a mock http client. example:

client := NewMockClient(
	&MockOptions{
		Trigger: func(req *http.Request) bool {
			return true
		},
		Handler: func(req *http.Request) *http.Response {
			return &http.Response{
				StatusCode: 200,
				Body:       io.NopCloser(strings.NewReader("mock response")),
			}
		},
	},
)

then

response, err := client.ExecuteRawRequest(&http.Request{})

will return a mock response.

func NewMockClientWithLogger added in v1.2.12

func NewMockClientWithLogger(log logger.Logger, opts ...*MockOptions) Client

NewMockClientWithLogger create a mock http client with logger. example:

client := NewMockClientWithLogger(logger.NewLogger())

then

response, err := client.ExecuteRawRequest(&http.Request{})

will return a mock response.

func NewSimpleClient added in v1.2.12

func NewSimpleClient() Client

type ContentType

type ContentType = string
const (
	ContentTypeJson       ContentType = "application/json"
	ContentTypeXml        ContentType = "application/xml"
	ContentTypeYaml       ContentType = "application/yaml"
	ContentTypeForm       ContentType = "application/x-www-form-urlencoded"
	ContentTypeFileStream ContentType = "application/octet-stream"
	ContentTypeMultipart  ContentType = "multipart/form-data"
	ContentTypeTextPlain  ContentType = "text/plain"
	ContentTypeTextHtml   ContentType = "text/html"
	ContentTypeTextJson   ContentType = "text/json"
	ContentTypeTextXml    ContentType = "text/xml"
	ContentTypeTextYaml   ContentType = "text/yaml"
	ContentTypeTextCsv    ContentType = "text/csv"
	ContentTypeImagePng   ContentType = "image/png"
	ContentTypeImageJpeg  ContentType = "image/jpeg"
	ContentTypeImageGif   ContentType = "image/gif"
)

type ContentTypeMismatchError added in v1.2.9

type ContentTypeMismatchError struct {
	Expected string
	Actual   string
}

func (ContentTypeMismatchError) Error added in v1.2.9

func (e ContentTypeMismatchError) Error() string

type Context added in v1.2.9

type Context[request any, response any] interface {
	context.Context

	// Next calls the following handlers until abort or the end of the chain.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		ctx.Next()
	//		// do something after returned from the following handlers
	//	}
	Next()

	// Abort aborts the following handlers.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		ctx.Abort()
	//		// do something after aborted
	//	}
	Abort()

	// IsAborted returns true if the following handlers are aborted.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		if ctx.IsAborted() {
	//			// do something if aborted
	//		}
	//		// do something after aborted
	//	}
	IsAborted() bool

	// RawRequest returns the raw request.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		raw := ctx.RawRequest()
	//		// do something with raw
	//	}
	RawRequest() *http.Request

	// QueryParams returns the query params.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		params := ctx.QueryParams()
	//		// do something with params
	//	}
	QueryParams() Params

	// PathParams returns the path params.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		params := ctx.PathParams()
	//		// do something with params
	//	}
	PathParams() Params

	// HeaderParams returns the header params.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		params := ctx.HeaderParams()
	//		// do something with params
	//	}
	HeaderParams() Params

	// NormalHeaders returns the normal headers.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		headers := ctx.NormalHeaders()
	//		// do something with headers
	//	}
	NormalHeaders() RequestHeader

	// ExtraParams returns the extra params.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		params := ctx.ExtraParams()
	//		// do something with params
	//	}
	ExtraParams() Params

	// SetExtraParam sets the extra param.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		ctx.SetExtraParam("key", "value")
	//		// do something with params
	//	}
	SetExtraParam(key string, value string)

	// Request returns the processed request.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		req := ctx.Request()
	//		// do something with req
	//	}
	Request() request

	// Response returns the response.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		resp := ctx.Response()
	//		// do something with resp
	//	}
	Response() response

	// SetResponse sets the response.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		ctx.SetResponse(resp)
	//		// do something with resp
	//	}
	SetResponse(resp response)

	// ResponseHeaders returns the response headers.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		headers := ctx.ResponseHeaders()
	//		// do something with headers
	//	}
	ResponseHeaders() Params

	// SetResponseHeader sets the response header.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		ctx.SetResponseHeader("key", "value")
	//		// do something with resp
	//	}
	SetResponseHeader(key string, value string)

	// ResponseSetCookies returns the response cookies.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		cookies := ctx.ResponseSetCookies()
	//		// do something with cookies
	//	}
	ResponseSetCookies() []Cookie

	// SetResponseSetCookie sets the response cookie.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		ctx.SetResponseSetCookie(cookie)
	//		// do something with resp
	//	}
	SetResponseSetCookie(cookie Cookie)

	// StatusCode returns the status code.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		status := ctx.StatusCode()
	//		// do something with status
	//	}
	StatusCode() int

	// SetStatusCode sets the status code.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		ctx.SetStatusCode(StatusOK)
	//		// do something with status
	//	}
	SetStatusCode(status int)

	// Error returns the error.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		err := ctx.Error()
	//		// do something with err
	//	}
	Error() error

	// SetError sets the error.
	// example:
	//
	//	func handler(ctx Context[request, response]) {
	//		// do something
	//		ctx.SetError(err)
	//		// do something with err
	//	}
	SetError(err error)
	// contains filtered or unexported methods
}

func NewContext added in v1.2.9

func NewContext[request any, response any](opts ...ContextOpts[request, response]) Context[request, response]

type ContextOpts added in v1.2.9

type ContextOpts[request any, response any] func(ctx *acContext[request, response])

func WithContext added in v1.2.9

func WithContext[request any, response any](rawCtx context.Context) ContextOpts[request, response]

func WithCookieParams added in v1.2.9

func WithCookieParams[request any, response any](params Params) ContextOpts[request, response]

func WithError added in v1.2.9

func WithError[request any, response any](err error) ContextOpts[request, response]

func WithExtraParams added in v1.2.9

func WithExtraParams[request any, response any](params Params) ContextOpts[request, response]

func WithHeaderParams added in v1.2.9

func WithHeaderParams[request any, response any](params Params) ContextOpts[request, response]

func WithPathParams added in v1.2.9

func WithPathParams[request any, response any](params Params) ContextOpts[request, response]

func WithQueryParams added in v1.2.9

func WithQueryParams[request any, response any](params Params) ContextOpts[request, response]

func WithRawRequest added in v1.2.9

func WithRawRequest[request any, response any](raw *http.Request) ContextOpts[request, response]

func WithRequest added in v1.2.9

func WithRequest[request any, response any](req request) ContextOpts[request, response]

func WithRequestHeader added in v1.2.9

func WithRequestHeader[request any, response any](headers RequestHeader) ContextOpts[request, response]

func WithResponse added in v1.2.9

func WithResponse[request any, response any](resp response) ContextOpts[request, response]

func WithResponseHeaders added in v1.2.9

func WithResponseHeaders[request any, response any](headers Params) ContextOpts[request, response]

func WithSetCookies added in v1.2.9

func WithSetCookies[request any, response any](cookies []Cookie) ContextOpts[request, response]

func WithSetHeaders added in v1.2.9

func WithSetHeaders[request any, response any](headers Params) ContextOpts[request, response]

func WithStatusCode added in v1.2.9

func WithStatusCode[request any, response any](status int) ContextOpts[request, response]
type Cookie struct {
	Name     string
	Value    string
	Path     string
	Domain   string
	Expires  string
	MaxAge   int
	Secure   bool
	HttpOnly bool
}

func NewBasicCookie added in v1.2.9

func NewBasicCookie(name, value string) *Cookie

type EndPoint added in v1.2.9

type EndPoint[request any, response any] struct {
	// contains filtered or unexported fields
}

EndPoint is the interface for http endpoint.

example:

ep := NewBasicEndPoint[request, response](http.GET, router, chain)
ep.AddParsingHeaders("Content-Type", true)
ep.AddParsingQueries("id", true)
ep.AddParsingParams("name", true)

then

GET /api/v1/user/:name?id=1
Content-Type: application/json

then in your handler

func handler(ctx Context[request, response]) {
	ctx.HeaderParams().GetString("Content-Type") // application/json
	ctx.QueryParams().GetInt("id") // 1
	ctx.PathParams().GetString("name") // name

	// do something
}

or using the builder like:

ep := NewEndPointBuilder[request, response]().
	SetAllowMethods(http.GET, http.POST).
	SetNecessaryParams("name").
	SetAdditionalQueries("id").
	SetAdditionalHeaders("Content-Type").
	SetAdditionalCookies("session").
	Build()

func NewBasicEndPoint added in v1.2.9

func NewBasicEndPoint[request any, response any](method Method, router Router, chain Chain[request, response]) *EndPoint[request, response]

NewBasicEndPoint creates a new EndPoint with basic options. It's a shortcut for NewEndPointWithOpts. example:

ep := NewBasicEndPoint[request, response](http.GET, router, chain)

func NewEndPointWithOpts added in v1.2.9

func NewEndPointWithOpts[request any, response any](opts ...EndPointOptions[request, response]) *EndPoint[request, response]

NewEndPointWithOpts creates a new EndPoint with options. example:

ep := NewEndPointWithOpts[request, response](
	WithRouterOpts[request, response](router),
	WithChainOpts[request, response](chain),
	WithHeaderOpts[request, response](headers),
	WithQueryOpts[request, response](queries),
	WithParamOpts[request, response](params),
	WithRequestProcessorOpts[request, response](processor),
	WithResponseProcessorOpts[request, response](processor),
	WithAllowedMethodsOpts[request, response](methods...),
)

func (*EndPoint[request, response]) AddParsingCookies added in v1.2.9

func (ep *EndPoint[request, response]) AddParsingCookies(key string, necessary bool)

func (*EndPoint[request, response]) AddParsingHeaders added in v1.2.9

func (ep *EndPoint[request, response]) AddParsingHeaders(key string, necessary bool)

func (*EndPoint[request, response]) AddParsingParams added in v1.2.9

func (ep *EndPoint[request, response]) AddParsingParams(key string, necessary bool)

func (*EndPoint[request, response]) AddParsingQueries added in v1.2.9

func (ep *EndPoint[request, response]) AddParsingQueries(key string, necessary bool)

func (*EndPoint[request, response]) Serve added in v1.2.9

func (ep *EndPoint[request, response]) Serve(ctx *gin.Context)

func (*EndPoint[request, response]) SetAllowedMethods added in v1.2.9

func (ep *EndPoint[request, response]) SetAllowedMethods(methods ...Method)

func (*EndPoint[request, response]) SetHandlerChain added in v1.2.9

func (ep *EndPoint[request, response]) SetHandlerChain(chain Chain[request, response])

type EndPointBuilder added in v1.2.13

type EndPointBuilder[request, response any] struct {
	// contains filtered or unexported fields
}

func NewEndPointBuilder added in v1.2.13

func NewEndPointBuilder[request, response any]() *EndPointBuilder[request, response]

func (*EndPointBuilder[request, response]) Build added in v1.2.13

func (eb *EndPointBuilder[request, response]) Build() *EndPoint[request, response]

func (*EndPointBuilder[request, response]) SetAdditionalCookies added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetAdditionalCookies(cookies ...string) *EndPointBuilder[request, response]

func (*EndPointBuilder[request, response]) SetAdditionalHeaders added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetAdditionalHeaders(headers ...string) *EndPointBuilder[request, response]

func (*EndPointBuilder[request, response]) SetAdditionalParams added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetAdditionalParams(params ...string) *EndPointBuilder[request, response]

SetAdditionalParams sets the additional params for EndPoint.

example:

ep := NewEndPointBuilder[request, response]().
	SetAdditionalParams("name").
	Build()

func (*EndPointBuilder[request, response]) SetAdditionalQueries added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetAdditionalQueries(queries ...string) *EndPointBuilder[request, response]

func (*EndPointBuilder[request, response]) SetAllowMethods added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetAllowMethods(methods ...Method) *EndPointBuilder[request, response]

SetAllowMethods sets the allowed methods for EndPoint.

example:

ep := NewEndPointBuilder[request, response]().
	SetAllowMethods(http.GET, http.POST, http.PUT, http.DELETE, http.PATCH).
	Build()

func (*EndPointBuilder[request, response]) SetCookies added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetCookies(cookies map[string]bool) *EndPointBuilder[request, response]

func (*EndPointBuilder[request, response]) SetCustomPreprocessors added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetCustomPreprocessors(preprocessors ...EndpointPreprocessor[request, response]) *EndPointBuilder[request, response]

func (*EndPointBuilder[request, response]) SetHandlerChain added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetHandlerChain(chain Chain[request, response]) *EndPointBuilder[request, response]

func (*EndPointBuilder[request, response]) SetHeaders added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetHeaders(headers map[string]bool) *EndPointBuilder[request, response]

func (*EndPointBuilder[request, response]) SetNecessaryCookies added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetNecessaryCookies(cookies ...string) *EndPointBuilder[request, response]

func (*EndPointBuilder[request, response]) SetNecessaryHeaders added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetNecessaryHeaders(headers ...string) *EndPointBuilder[request, response]

func (*EndPointBuilder[request, response]) SetNecessaryParams added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetNecessaryParams(params ...string) *EndPointBuilder[request, response]

SetNecessaryParams sets the necessary params for EndPoint.

example:

ep := NewEndPointBuilder[request, response]().
	SetNecessaryParams("name").
	Build()

func (*EndPointBuilder[request, response]) SetNecessaryQueries added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetNecessaryQueries(queries ...string) *EndPointBuilder[request, response]

func (*EndPointBuilder[request, response]) SetParams added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetParams(params map[string]bool) *EndPointBuilder[request, response]

SetParams sets the params for EndPoint.

example:

ep := NewEndPointBuilder[request, response]().
	SetParams(map[string]bool{"name": true}).
	Build()

func (*EndPointBuilder[request, response]) SetQueries added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetQueries(queries map[string]bool) *EndPointBuilder[request, response]

func (*EndPointBuilder[request, response]) SetRouter added in v1.2.13

func (eb *EndPointBuilder[request, response]) SetRouter(router Router) *EndPointBuilder[request, response]

type EndPointInterface added in v1.2.9

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

type EndPointOptions added in v1.2.9

type EndPointOptions[request any, response any] func(ep *EndPoint[request, response])

EndPointOptions is the options for EndPoint. example:

ep := NewEndPointWithOpts[request, response](
	WithRouterOpts[request, response](router),
	WithChainOpts[request, response](chain),
	WithHeaderOpts[request, response](headers),
	WithQueryOpts[request, response](queries),
	WithParamOpts[request, response](params),
	WithRequestProcessorOpts[request, response](processor),
	WithResponseProcessorOpts[request, response](processor),
	WithAllowedMethodsOpts[request, response](methods...),
)

func WithAllowedMethodsOpts added in v1.2.9

func WithAllowedMethodsOpts[request any, response any](methods ...Method) EndPointOptions[request, response]

WithAllowedMethodsOpts sets the allowed methods for EndPoint, nil is allowed, but it will not work. example:

ep := NewEndPointWithOpts[request, response](
	WithAllowedMethodsOpts[request, response](http.GET, http.POST, http.PUT, http.DELETE, http.PATCH),
)

func WithChainOpts added in v1.2.9

func WithChainOpts[request any, response any](chain Chain[request, response]) EndPointOptions[request, response]

WithChainOpts sets the chain for EndPoint, nil is allowed, but it will not work. example:

ep := NewEndPointWithOpts[request, response](
	WithChainOpts[request, response](chain),
)

func WithCookieOpts added in v1.2.9

func WithCookieOpts[request any, response any](cookies map[string]bool) EndPointOptions[request, response]

WithCookieOpts sets the cookies for EndPoint, nil is allowed, but it will not work. example:

ep := NewEndPointWithOpts[request, response](
	WithCookieOpts[request, response](cookies),
)

func WithCustomPreprocessors added in v1.2.12

func WithCustomPreprocessors[request any, response any](preprocessors ...EndpointPreprocessor[request, response]) EndPointOptions[request, response]

func WithHeaderOpts added in v1.2.9

func WithHeaderOpts[request any, response any](headers map[string]bool) EndPointOptions[request, response]

WithHeaderOpts sets the headers for EndPoint, nil is allowed, but it will not work. example:

ep := NewEndPointWithOpts[request, response](
	WithHeaderOpts[request, response](headers),
)

func WithParamOpts added in v1.2.9

func WithParamOpts[request any, response any](params map[string]bool) EndPointOptions[request, response]

WithParamOpts sets the params for EndPoint, nil is allowed, but it will not work. example:

ep := NewEndPointWithOpts[request, response](
	WithParamOpts[request, response](params),
)

func WithQueryOpts added in v1.2.9

func WithQueryOpts[request any, response any](queries map[string]bool) EndPointOptions[request, response]

WithQueryOpts sets the queries for EndPoint, nil is allowed, but it will not work. example:

ep := NewEndPointWithOpts[request, response](
	WithQueryOpts[request, response](queries),
)

func WithRouterOpts added in v1.2.9

func WithRouterOpts[request any, response any](router Router) EndPointOptions[request, response]

WithRouterOpts sets the router for EndPoint, nil is allowed, but it will not work. example:

ep := NewEndPointWithOpts[request, response](
	WithRouterOpts[request, response](router),
)

type EndpointGroup added in v1.2.13

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

func NewEndPointGroup added in v1.2.13

func NewEndPointGroup(group string, endpoints ...EndPointInterface) *EndpointGroup

func (*EndpointGroup) AddEndPoints added in v1.2.13

func (e *EndpointGroup) AddEndPoints(endpoints ...EndPointInterface)

type EndpointPreprocessor added in v1.2.12

type EndpointPreprocessor[request any, response any] func(endpoint *EndPoint[request, response], origin *gin.Context, dest PreprocessedContext[request, response])

func DefaultPreprocessors added in v1.2.12

func DefaultPreprocessors[request any, response any](processors ...EndpointPreprocessor[request, response]) []EndpointPreprocessor[request, response]

func NewPreprocessors added in v1.2.12

func NewPreprocessors[request any, response any](processors ...EndpointPreprocessor[request, response]) []EndpointPreprocessor[request, response]

type Engine added in v1.2.9

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

func NewEngine added in v1.2.9

func NewEngine(base string) *Engine

func (*Engine) AddEndPoints added in v1.2.9

func (e *Engine) AddEndPoints(eps ...EndPointInterface)

func (*Engine) AddMiddlewares added in v1.2.9

func (e *Engine) AddMiddlewares(middleware ...gin.HandlerFunc)

func (*Engine) BaseRouter added in v1.2.9

func (e *Engine) BaseRouter() Router

func (*Engine) Serve added in v1.2.9

func (e *Engine) Serve(bindAddress string) error

func (*Engine) ServeAsync added in v1.2.9

func (e *Engine) ServeAsync(bindAddress string, exitChan chan struct{}) (errChan chan error)

type FrameworkErrorCode added in v1.2.12

type FrameworkErrorCode = int
const (
	ErrorCodeMissingRequiredQuery  FrameworkErrorCode = 4001
	ErrorCodeMissingRequiredParam  FrameworkErrorCode = 4002
	ErrorCodeMissingRequiredHeader FrameworkErrorCode = 4003
	ErrorCodeMissingRequiredCookie FrameworkErrorCode = 4004
	ErrorCodeInvalidRequestBody    FrameworkErrorCode = 4005
	ErrorCodeBadRequestBody        FrameworkErrorCode = 4006

	ErrorCodeMethodNotSupported FrameworkErrorCode = 4051
	ErrorCodeMethodNotAllowed   FrameworkErrorCode = 4052

	ErrorCodeInternalErrorOccurred FrameworkErrorCode = 5001
	ErrorCodePanicErrorRecovered   FrameworkErrorCode = 5002
)

type FrameworkResponse added in v1.2.12

type FrameworkResponse struct {
	ErrorCode    int    `json:"error_code"`
	ErrorMessage string `json:"error_message"`
	RequestID    string `json:"request_id"`
	Data         any    `json:"data,omitempty"`
}

type Handler added in v1.2.9

type Handler[request any, response any] func(ctx Context[request, response])

func EmptyHandler added in v1.2.9

func EmptyHandler[request any, response any]() Handler[request, response]

EmptyHandler return an empty handler. example:

chain := NewChain[request, response](
	EmptyHandler[request, response](),
	func(ctx Context[request, response]) {
		// do something
		ctx.Next()
	},
)

type Method

type Method = string
const (
	GET     Method = "GET"
	POST    Method = "POST"
	OPTIONS Method = "OPTIONS"
	HEAD    Method = "HEAD"
	PUT     Method = "PUT"
	DELETE  Method = "DELETE"
	TRACE   Method = "TRACE"
	CONNECT Method = "CONNECT"
	PATCH   Method = "PATCH"
)

type MethodCode added in v1.2.9

type MethodCode = int32
const (
	CodeGet MethodCode = 1 << iota
	CodePost
	CodeOptions
	CodeHead
	CodePut
	CodeDelete
	CodeTrace
	CodeConnect
	CodePatch
)

type MethodNotAllowedError added in v1.2.9

type MethodNotAllowedError struct {
	Method string
}

func (MethodNotAllowedError) Error added in v1.2.9

func (e MethodNotAllowedError) Error() string

type MockOptions added in v1.2.12

type MockOptions struct {
	Trigger func(req *http.Request) bool
	Handler func(req *http.Request) *http.Response
}

type MultipartBodyBuilder added in v1.2.12

type MultipartBodyBuilder interface {
	WithFile(fileKey, fileName string, payload io.Reader) MultipartBodyBuilder
	WithForm(key, value string) MultipartBodyBuilder
	Build() (body io.Reader, contentType string, err error)
}

MultipartBodyBuilder is used to build a multipart body for a request

func NewMultipartBodyBuilder added in v1.2.12

func NewMultipartBodyBuilder() MultipartBodyBuilder

NewMultipartBodyBuilder returns a new MultipartBodyBuilder, which is used to build a multipart body for a request example:

builder := NewMultipartBodyBuilder().WithFile("file", "file.txt", fileReader).WithForm("key", "value")
body, contentType, err := builder.Build()
if err != nil {
	panic(err)
}

request := NewRequest().WithBody(body).WithHeader("Content-Type", contentType)

then you can use the request to send a multipart request

type NecessaryCookieMissingError added in v1.2.9

type NecessaryCookieMissingError struct {
	Cookie string
}

func (NecessaryCookieMissingError) Error added in v1.2.9

type NecessaryHeaderMissingError added in v1.2.9

type NecessaryHeaderMissingError struct {
	Header string
}

func (NecessaryHeaderMissingError) Error added in v1.2.9

type NecessaryQueryMissingError added in v1.2.9

type NecessaryQueryMissingError struct {
	Query string
}

func (NecessaryQueryMissingError) Error added in v1.2.9

type Params added in v1.2.9

type Params map[string]string

func (Params) GetBool added in v1.2.9

func (p Params) GetBool(key string) bool

func (Params) GetFloat added in v1.2.9

func (p Params) GetFloat(key string) float64

func (Params) GetInt added in v1.2.9

func (p Params) GetInt(key string) int

func (Params) GetString added in v1.2.9

func (p Params) GetString(key string) string

func (Params) GetUint added in v1.2.9

func (p Params) GetUint(key string) uint

type PreprocessedContext added in v1.2.12

type PreprocessedContext[request any, response any] interface {
	context.Context
	SetQueryParams(params Params)
	SetPathParams(params Params)
	SetHeaderParams(params Params)
	SetCookieParams(params Params)
	SetExtraParams(params Params)
	SetRawRequest(raw *http.Request)
	SetRequest(req request)
	SetRequestHeader(headers RequestHeader)
}

type RequestBuilder added in v1.2.12

type RequestBuilder interface {
	WithContext(ctx context.Context) RequestBuilder
	WithMethod(method Method) RequestBuilder
	WithPath(path string) RequestBuilder
	WithPathFormat(format string, args ...any) RequestBuilder
	WithPathTemplate(template string, args map[string]string) RequestBuilder
	WithQuery(key, value string) RequestBuilder
	WithQueryIgnoreEmptyValue(key, value string) RequestBuilder
	WithHeader(key, value string) RequestBuilder
	WithCookie(key, value string) RequestBuilder
	WithBody(body io.Reader) RequestBuilder
	WithJsonBody(body any) RequestBuilder
	WithUserAgent(userAgent UserAgent) RequestBuilder
	WithBearerToken(token string) RequestBuilder
	WithAccept(accept ContentType) RequestBuilder
	WithContentType(contentType ContentType) RequestBuilder
	Clone() RequestBuilder
	Build() (request *http.Request, err error)
}

RequestBuilder is used to build a http request.

func NewRequestBuilder added in v1.2.12

func NewRequestBuilder() RequestBuilder

NewRequestBuilder returns a new RequestBuilder, which is used to build a http request. example:

builder := NewRequestBuilder().
	WithMethod(http.MethodGet).
	WithScheme("https").
	WithHostname("www.baidu.com").
	WithPath("/").
	WithQuery("key", "value").
	WithHeader("Content-Type", "application/json").
	WithCookie("key", "value")
request, err := builder.Build()

then you can use the request to send a http request

type RequestHeader added in v1.2.9

type RequestHeader struct {
	Accept         string
	AcceptEncoding string
	AcceptLanguage string
	UserAgent      string
	ContentType    string
	ContentLength  int
	Origin         string
	Referer        string
	Authorization  string
	ApiKey         string
}

type RequestLoggingFields added in v1.2.12

type RequestLoggingFields struct {
	Url         string `json:"url"`
	Method      string `json:"method"`
	ContentType string `json:"content_type"`
	Body        any    `json:"body"`
}

type ResponseLoggingFields added in v1.2.12

type ResponseLoggingFields struct {
	StatusCode  int    `json:"status_code"`
	ContentType string `json:"content_type"`
	Body        any    `json:"body"`
}

type ResponseParser added in v1.2.12

type ResponseParser interface {
	RawResponse() *http.Response
	RawRequest() *http.Request
	RawBody() []byte
	Context() context.Context
	Status() (code int, message string)
	BindJson(receiver any) (bindErr error)
	BindXml(receiver any) (bindErr error)
	BindCustom(receiver any, decoder func(reader io.Reader, receiver any) error) (bindErr error)
	BindHeader(fields ...string) (header map[string][]string)
	BindCookie(fields ...string) (cookies map[string]*http.Cookie)
}

ResponseParser is used to parse a http response.

func NewSimpleResponseParser added in v1.2.12

func NewSimpleResponseParser(r *http.Response) ResponseParser

type Router added in v1.2.9

type Router interface {
	// Group returns a new router with the given sub path. sub path must begin with a slash and end without a slash.
	//
	// example:
	//	router := NewRouter("/api")
	//	subRouter := router.Group("/v1") // subRouter.FullRouterPath() == "/api/v1"
	//	subRouter2 := subRouter.Group("user") // subRouter2.FullRouterPath() == "/api/v1/user"
	//	subRouter3 := subRouter2.Group("info/") // subRouter3.FullRouterPath() == "/api/v1/user/info"
	Group(sub string) Router

	// Extend returns a new router with the given father router.
	//
	// example:
	//	router := NewRouter("/api")
	//	subRouter := NewRouter("/v1")
	//	subRouter.Extend(router) // subRouter2.FullRouterPath() == "/api/v1"
	Extend(father Router) Router

	// FullRouterPath returns the full path of the router.
	//
	// example:
	//	router := NewRouter("/api")
	//	subRouter := router.Group("/v1") // subRouter.FullRouterPath() == "/api/v1"
	FullRouterPath() string

	// BaseRouterPath returns the base path of the router.
	//
	// example:
	//	router := NewRouter("/api")
	//	subRouter := router.Group("/v1") // subRouter.BaseRouterPath() == "/v1"
	BaseRouterPath() string
}

Router is the interface that wraps the basic methods of a router.

func NewRouter added in v1.2.9

func NewRouter(base string) Router

type ServerAlreadyServingError added in v1.2.9

type ServerAlreadyServingError struct {
	Address string
}

func (ServerAlreadyServingError) Error added in v1.2.9

type Status added in v1.2.3

type Status = int
const (
	StatusContinue              Status = 100
	StatusSwitchingProtocols    Status = 101
	StatusProcessing            Status = 102
	StatusEarlyHints            Status = 103
	StatusOK                    Status = 200
	StatusCreated               Status = 201
	StatusAccepted              Status = 202
	StatusNonAuthoritative      Status = 203
	StatusNoContent             Status = 204
	StatusResetContent          Status = 205
	StatusPartialContent        Status = 206
	StatusMultiStatus           Status = 207
	StatusAlreadyReported       Status = 208
	StatusIMUsed                Status = 226
	StatusMultipleChoices       Status = 300
	StatusMovedPermanently      Status = 301
	StatusFound                 Status = 302
	StatusSeeOther              Status = 303
	StatusNotModified           Status = 304
	StatusUseProxy              Status = 305
	StatusTemporaryRedirect     Status = 307
	StatusPermanentRedirect     Status = 308
	StatusBadRequest            Status = 400
	StatusUnauthorized          Status = 401
	StatusPaymentRequired       Status = 402
	StatusForbidden             Status = 403
	StatusNotFound              Status = 404
	StatusMethodNotAllowed      Status = 405
	StatusNotAcceptable         Status = 406
	StatusProxyAuthRequired     Status = 407
	StatusRequestTimeout        Status = 408
	StatusConflict              Status = 409
	StatusGone                  Status = 410
	StatusLengthRequired        Status = 411
	StatusPreconditionFailed    Status = 412
	StatusRequestEntityToo      Status = 413
	StatusRequestURITooLong     Status = 414
	StatusUnsupportedMedia      Status = 415
	StatusRequestedRangeNot     Status = 416
	StatusExpectationFailed     Status = 417
	StatusTeapot                Status = 418
	StatusMisdirectedRequest    Status = 421
	StatusUnprocessable         Status = 422
	StatusLocked                Status = 423
	StatusFailedDependency      Status = 424
	StatusTooEarly              Status = 425
	StatusUpgradeRequired       Status = 426
	StatusPreconditionRequired  Status = 428
	StatusTooManyRequests       Status = 429
	StatusRequestHeaderFields   Status = 431
	StatusUnavailableForLegal   Status = 451
	StatusInternalServerError   Status = 500
	StatusNotImplemented        Status = 501
	StatusBadGateway            Status = 502
	StatusServiceUnavailable    Status = 503
	StatusGatewayTimeout        Status = 504
	StatusHTTPVersionNot        Status = 505
	StatusVariantAlsoNegotiates Status = 506
	StatusInsufficientStorage   Status = 507
	StatusLoopDetected          Status = 508
	StatusNotExtended           Status = 510
	StatusNetworkAuthentication Status = 511
)

type UnsupportedAcceptError added in v1.2.9

type UnsupportedAcceptError struct {
	Accept string
}

func (UnsupportedAcceptError) Error added in v1.2.9

func (e UnsupportedAcceptError) Error() string

type UnsupportedContentTypeError added in v1.2.9

type UnsupportedContentTypeError struct {
	ContentType string
}

func (UnsupportedContentTypeError) Error added in v1.2.9

type UnsupportedMethodError added in v1.2.9

type UnsupportedMethodError struct {
	Method string
}

func (UnsupportedMethodError) Error added in v1.2.9

func (e UnsupportedMethodError) Error() string

type UserAgent

type UserAgent = string
const (
	Curl         UserAgent = "curl/7.64.1"
	Postman      UserAgent = "PostmanRuntime/7.26.8"
	ChromeOSX    UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
	Safari       UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15"
	Firefox      UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/119.0"
	AliothClient UserAgent = "alioth-http-client/1.0.0"
)

Jump to

Keyboard shortcuts

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