http

package
v1.2.19 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2024 License: MIT Imports: 22 Imported by: 10

Documentation

Index

Constants

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

Variables

Functions

func CheckRequestBodyPreprocessor added in v1.2.12

func CheckRequestBodyPreprocessor[request any, response any](_ *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 ErrorContextKey added in v1.2.14

func ErrorContextKey() string

func LoadNormalRequestHeadersPreprocessor added in v1.2.12

func LoadNormalRequestHeadersPreprocessor[request any, response any](_ *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 SetErrorContextKey added in v1.2.14

func SetErrorContextKey(key string)

func SetMode added in v1.2.17

func SetMode(m string)

func SetPayloadProcessor added in v1.2.9

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

func SetTraceHeaderKey added in v1.2.14

func SetTraceHeaderKey(key string)

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")
	}
}

func TraceHeaderKey added in v1.2.14

func TraceHeaderKey() string

Types

type BaseError added in v1.2.18

type BaseError struct {
	ErrorCode    int    `json:"error_code"`
	ErrorMessage string `json:"error_message"`
}

func NewBaseError added in v1.2.18

func NewBaseError(code int, message string) *BaseError

func (BaseError) Error added in v1.2.18

func (e BaseError) Error() string

type BaseResponse added in v1.2.18

type BaseResponse[T any] interface {
	BindError(err error)
	BindData(data T)
	BindContext(ctx context.Context)
}

func NewBaseResponse added in v1.2.18

func NewBaseResponse[T any](ctx context.Context, data T, err error) BaseResponse[T]

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 next handler in the chain.
	// If there are no more handlers, it stops execution.
	Next()

	// Abort stops the execution of the remaining handlers in the chain.
	Abort()

	// IsAborted checks if the execution of the remaining handlers has been aborted.
	//
	// Returns:
	//   bool: True if the execution has been aborted, otherwise false.
	IsAborted() bool

	// RawRequest returns the raw HTTP request.
	//
	// Returns:
	//   *http.Request: The raw HTTP request.
	RawRequest() *http.Request

	// QueryParams returns the query parameters.
	//
	// Returns:
	//   Params: The query parameters.
	QueryParams() Params

	// PathParams returns the path parameters.
	//
	// Returns:
	//   Params: The path parameters.
	PathParams() Params

	// HeaderParams returns the header parameters.
	//
	// Returns:
	//   Params: The header parameters.
	HeaderParams() Params

	// CookieParams returns the cookie parameters.
	//
	// Returns:
	//   Params: The cookie parameters.
	CookieParams() Params

	// NormalHeaders returns the normal request headers.
	// Includes following headers:
	//   - Accept
	//   - Accept-Encoding
	//   - Accept-Language
	//   - User-Agent
	//   - Content-Type
	//   - Content-Length
	//   - Origin
	//   - Referer
	//   - Authorization
	//   - ApiKey
	//
	// Returns:
	//   RequestHeader: The normal request headers.
	NormalHeaders() RequestHeader

	// ExtraParams returns the extra parameters.
	//
	// Returns:
	//   Params: The extra parameters.
	ExtraParams() Params

	// SetExtraParam sets a single extra parameter.
	//
	// Parameters:
	//   key (string): The key of the extra parameter.
	//   value (string): The value of the extra parameter.
	SetExtraParam(key string, value string)

	// Request returns the processed request.
	//
	// Returns:
	//   request: The processed request
	Request() request

	// Response returns the response.
	//
	// Returns:
	//   response: The response.
	Response() response

	// SetResponse sets the response.
	//
	// Parameters:
	//   resp (response): The response to be set.
	SetResponse(resp response)

	// ResponseHeaders returns the response headers.
	//
	// Returns:
	//   Params: The response headers.
	ResponseHeaders() Params

	// SetResponseHeader sets a single response header.
	//
	// Parameters:
	//   key (string): The key of the response header.
	//   value (string): The value of the response header.
	SetResponseHeader(key string, value string)

	// ResponseSetCookies returns the response set cookies.
	//
	// Returns:
	//   []Cookie: The response set cookies.
	ResponseSetCookies() []Cookie

	// SetResponseSetCookie sets a response cookie.
	//
	// Parameters:
	//   cookie (Cookie): The response cookie to be set.
	SetResponseSetCookie(cookie Cookie)

	// StatusCode returns the status code of the response.
	//
	// Returns:
	//   int: The status code of the response.
	StatusCode() int

	// SetStatusCode sets the status code of the response.
	//
	// Parameters:
	//   status (int): The status code to be set.
	SetStatusCode(status int)

	// ClientIP retrieves the client's IP address from the request context.
	// It checks various headers and the remote address in the following priority order:
	// 	1. X-Forwarded-For header (may contain multiple IPs, comma-separated)
	// 	2. X-Real-IP header
	// 	3. RemoteAddr from the raw request
	// 	4. Extra parameters passed in the context
	//
	// Returns:
	//   ip (string): The client's IP address if found and valid, otherwise an empty string.
	ClientIP() string

	// Error returns the error set in the context.
	//
	// Returns:
	//   error: The error set in the context.
	Error() error

	// SetError sets an error in the context.
	//
	// Parameters:
	//   err (error): The error to be set.
	SetError(err error)

	// SetValue sets a value in the context, equivalent to context.WithValue.
	//
	// Parameters:
	//   key (any): The key for the value.
	//   value (any): The value to be set.
	SetValue(key, value any)
	// 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]) SetGinMiddlewares added in v1.2.14

func (ep *EndPoint[request, response]) SetGinMiddlewares(middlewares ...gin.HandlerFunc)

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]) SetGinMiddlewares added in v1.2.14

func (eb *EndPointBuilder[request, response]) SetGinMiddlewares(middlewares ...gin.HandlerFunc) *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 WithGinMiddlewaresOpts added in v1.2.14

func WithGinMiddlewaresOpts[request any, response any](middlewares ...gin.HandlerFunc) EndPointOptions[request, response]

WithGinMiddlewaresOpts sets the gin middlewares for EndPoint, nil is allowed, but it will not work. example:

ep := NewEndPointWithOpts[request, response](
	WithGinMiddlewaresOpts[request, response](middlewares...),
)

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

	ErrorCodeResourceNotFound FrameworkErrorCode = 4041

	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 EchoHandler added in v1.2.14

func EchoHandler[payload any]() Handler[payload, payload]

EchoHandler return an echo handler. example:

chain := NewChain[request, request](
	EchoHandler[request](),
)

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 HeaderEnum added in v1.2.17

type HeaderEnum = string
const (
	HeaderAuthorization   HeaderEnum = "Authorization"
	HeaderContentType     HeaderEnum = "Content-Type"
	HeaderUserAgent       HeaderEnum = "User-Agent"
	HeaderAccept          HeaderEnum = "Accept"
	HeaderEncoding        HeaderEnum = "Accept-Encoding"
	HeaderAcceptLanguage  HeaderEnum = "Accept-Language"
	HeaderContentLength   HeaderEnum = "Content-Length"
	HeaderHost            HeaderEnum = "Host"
	HeaderReferer         HeaderEnum = "Referer"
	HeaderOrigin          HeaderEnum = "Origin"
	HeaderCookie          HeaderEnum = "Cookie"
	HeaderSetCookie       HeaderEnum = "Set-Cookie"
	HeaderXForwardedProto HeaderEnum = "X-Forwarded-Proto"
	HeaderXForwardedPort  HeaderEnum = "X-Forwarded-Port"
	HeaderXForwardedFor   HeaderEnum = "X-Forwarded-For"
	HeaderXForwardedHost  HeaderEnum = "X-Forwarded-Host"
	HeaderXRealIP         HeaderEnum = "X-Real-IP"
	HeaderXRequestID      HeaderEnum = "X-Request-ID"
	HeaderXAPIKey         HeaderEnum = "X-API-Key"
	HeaderXTraceID        HeaderEnum = "X-Trace-ID"
)

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 NoBody added in v1.2.17

type NoBody = struct{}

type NoResponse added in v1.2.17

type NoResponse = struct{}

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
	WithQueries(queries *url.Values) 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"
)

Directories

Path Synopsis
Package hm : http middleware functions, such as logging middleware, authentication middleware, etc.
Package hm : http middleware functions, such as logging middleware, authentication middleware, etc.

Jump to

Keyboard shortcuts

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