Documentation ¶
Index ¶
- Constants
- Variables
- func DisableGeneralOptions(disable bool) utility.Option[Server]
- func Do(tr transport.Transporter, fn func(tr Transporter))
- func WithAddr(network, addr string) utility.Option[Server]
- func WithBaseContext(fn func(net.Listener) context.Context) utility.Option[Server]
- func WithBodyDecoder(decoder RequestDecoder) utility.Option[Server]
- func WithCodecType(codec string) utility.Option[Server]
- func WithConnContext(fn func(context.Context, net.Conn) context.Context) utility.Option[Server]
- func WithConnState(fn func(net.Conn, http.ConnState)) utility.Option[Server]
- func WithDisableHealthz() utility.Option[Server]
- func WithErrorEncoder(encoder ErrorEncoder) utility.Option[Server]
- func WithErrorLogger(logger *log.Logger) utility.Option[Server]
- func WithIdleTimeout(timeout time.Duration) utility.Option[Server]
- func WithListener(lis net.Listener) utility.Option[Server]
- func WithLogger(logger *slog.Logger) utility.Option[Server]
- func WithMaxHeaderBytes(max int) utility.Option[Server]
- func WithMethodNotAllowedHandler(handler http.Handler) utility.Option[Server]
- func WithMiddleware(middlewares ...middleware.Middleware) utility.Option[Server]
- func WithMultipartMaxSize(size int64) utility.Option[Server]
- func WithNotFoundHandler(handler http.Handler) utility.Option[Server]
- func WithQueryDecoder(decoder RequestDecoder) utility.Option[Server]
- func WithReadHeaderTimeout(timeout time.Duration) utility.Option[Server]
- func WithReadTimeout(timeout time.Duration) utility.Option[Server]
- func WithResponseEncoder(encoder ResponseEncoder) utility.Option[Server]
- func WithRouterHandler(router http.Handler) utility.Option[Server]
- func WithSkipClean(value bool) utility.Option[Server]
- func WithStrictSlash(value bool) utility.Option[Server]
- func WithTLSConfig(config *tls.Config) utility.Option[Server]
- func WithTLSNextProto(proto map[string]func(*http.Server, *tls.Conn, http.Handler)) utility.Option[Server]
- func WithUseEncodedPath() utility.Option[Server]
- func WithVarsDecoder(decoder RequestDecoder) utility.Option[Server]
- func WithWriteTimeout(timeout time.Duration) utility.Option[Server]
- type CallOption
- type Context
- func (c *Context) Bind(target any) error
- func (c *Context) BindBody(target any) error
- func (c *Context) BindForm(target any) error
- func (c *Context) BindMultipartForm(target any) error
- func (c *Context) BindQuery(target any) error
- func (c *Context) BindVars(target any) error
- func (c *Context) Blob(data []byte, contentType string, code ...int) error
- func (c *Context) Deadline() (time.Time, bool)
- func (c *Context) Done() <-chan struct{}
- func (c *Context) Err() error
- func (c *Context) JSON(v any, code ...int) error
- func (c *Context) Middleware(handler middleware.Handler) middleware.Handler
- func (c *Context) Stream(reader io.Reader, contentType string, code ...int) error
- func (c *Context) String(text string, code ...int) error
- func (c *Context) Transport() (Transporter, bool)
- func (c *Context) Value(key interface{}) interface{}
- func (c *Context) Write(v any, code ...int) error
- func (c *Context) WriteHeader(contentType string, code []int)
- func (c *Context) XML(v any, code ...int) error
- type ErorrEncoderFunc
- type ErrorEncoder
- type Filter
- type FilterFunc
- type Handler
- type RequestDecoder
- type RequestDecoderFunc
- type ResponseEncoder
- type ResponseEncoderFunc
- type RouteWalkFunc
- type Router
- func (r *Router) BodyDecoder(req *http.Request, target any) error
- func (r *Router) CONNECT(path string, handler Handler, middlewares ...middleware.Middleware)
- func (r *Router) DELETE(path string, handler Handler, middlewares ...middleware.Middleware)
- func (r *Router) ErrorEncoder(w http.ResponseWriter, req *http.Request, err error)
- func (r *Router) GET(path string, handler Handler, middlewares ...middleware.Middleware)
- func (r *Router) Group(prefix string, middlewares ...middleware.Middleware) *Router
- func (r *Router) HEAD(path string, handler Handler, middlewares ...middleware.Middleware)
- func (r *Router) Handle(method, path string, handler Handler, middlewares ...middleware.Middleware)
- func (r *Router) OPTIONS(path string, handler Handler, middlewares ...middleware.Middleware)
- func (r *Router) PATCH(path string, handler Handler, middlewares ...middleware.Middleware)
- func (r *Router) POST(path string, handler Handler, middlewares ...middleware.Middleware)
- func (r *Router) PUT(path string, handler Handler, middlewares ...middleware.Middleware)
- func (r *Router) QueryDecoder(req *http.Request, target any) error
- func (r *Router) ResponseEncoder(w http.ResponseWriter, req *http.Request, v any) error
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) SubContentType(contentType string) string
- func (r *Router) TRACE(path string, handler Handler, middlewares ...middleware.Middleware)
- func (r *Router) VarsDecoder(req *http.Request, target any) error
- func (r *Router) Walk(fn RouteWalkFunc) error
- type Server
- type Transport
- func (t *Transport) AddHeader(key, value string)
- func (t *Transport) Kind() transport.Kind
- func (t *Transport) Method() string
- func (t *Transport) Path() string
- func (t *Transport) Request() *http.Request
- func (t *Transport) RequestHeader() transport.Header
- func (t *Transport) Response() http.ResponseWriter
- func (t *Transport) ResponseHeader() transport.Header
- func (t *Transport) SetHeader(key, value string)
- func (t *Transport) Template() string
- type Transporter
Constants ¶
const HealthzURI = "/debug/healthz"
Variables ¶
var HealthzHandler = func(w http.ResponseWriter, r *http.Request) { _, _ = fmt.Fprint(w, "OK") }
HealthzHandler is a health-check handler that returns an OK status for all incoming HTTP requests. this handler only handle GET method. eg: http://127.0.0.1:8080/debug/healthz
use WithDisableHealthz to disable health handler eg: NewServer(WithDisableHealthz())
Functions ¶
func DisableGeneralOptions ¶
DisableGeneralOptions if true, passes "OPTIONS *" requests to the Handler, otherwise responds with 200 OK and Content-Length: 0.
func Do ¶
func Do(tr transport.Transporter, fn func(tr Transporter))
func WithBaseContext ¶
WithBaseContext optionally specifies a function that returns the base context for incoming requests on this server. The provided Listener is the specific Listener that's about to start accepting requests. If BaseContext is nil, the default is context.Background(). If non-nil, it must return a non-nil context.
func WithBodyDecoder ¶
func WithBodyDecoder(decoder RequestDecoder) utility.Option[Server]
WithBodyDecoder decode body data to struct
func WithCodecType ¶
WithCodecType change the default Codec type. The default type is json refer: encoding/*
func WithConnContext ¶
WithConnContext optionally specifies a function that modifies the context used for a new connection c. The provided ctx is derived from the base context and has a ServerContextKey value.
func WithConnState ¶
WithConnState specifies an optional callback function that is called when a client connection changes state. See the ConnState type and associated constants for details.
func WithDisableHealthz ¶
WithDisableHealthz disable healthz handler
func WithErrorEncoder ¶
func WithErrorEncoder(encoder ErrorEncoder) utility.Option[Server]
WithErrorEncoder write request error to ResponseWriter
func WithErrorLogger ¶
WithErrorLogger specifies an optional logger for errors accepting connections, unexpected behavior from handlers, and underlying FileSystem errors. If nil, logging is done via the log package's standard logger.
func WithIdleTimeout ¶
WithIdleTimeout is the maximum amount of time to wait for the next request when keep-alives are enabled. If IdleTimeout is zero, the value of ReadTimeout is used. If both are zero, there is no timeout.
func WithListener ¶
WithListener use this listener on Server
func WithMaxHeaderBytes ¶
WithMaxHeaderBytes controls the maximum number of bytes the server will read parsing the request header's keys and values, including the request line. It does not limit the size of the request body. If zero, http.DefaultMaxHeaderBytes is used.
func WithMethodNotAllowedHandler ¶
WithMethodNotAllowedHandler configurable Handler to be used when the request method does not match the route.
func WithMiddleware ¶
func WithMiddleware(middlewares ...middleware.Middleware) utility.Option[Server]
func WithNotFoundHandler ¶
WithNotFoundHandler onfigurable Handler to be used when no route matches.
func WithQueryDecoder ¶
func WithQueryDecoder(decoder RequestDecoder) utility.Option[Server]
WithQueryDecoder decode request query params to struct
type Greeter struct { Name string // demo }
func WithReadHeaderTimeout ¶
WithReadHeaderTimeout is the amount of time allowed to read request headers. The connection's read deadline is reset after reading the headers and the Handler can decide what is considered too slow for the body. If ReadHeaderTimeout is zero, the value of ReadTimeout is used. If both are zero, there is no timeout.
func WithReadTimeout ¶
WithReadTimeout is the maximum duration for reading the entire request, including the body. A zero or negative value means there will be no timeout.
Because ReadTimeout does not let Handlers make per-request decisions on each request body's acceptable deadline or upload rate, most users will prefer to use ReadHeaderTimeout. It is valid to use them both.
func WithResponseEncoder ¶
func WithResponseEncoder(encoder ResponseEncoder) utility.Option[Server]
WithResponseEncoder write response data to ResponseWriter
func WithRouterHandler ¶
WithRouterHandler can custom http.Server.Handler
func WithSkipClean ¶
WithSkipClean defines the path cleaning behaviour for new routes. The initial value is false. Users should be careful about which routes are not cleaned
When true, if the route path is "/path//to", it will remain with the double slash. This is helpful if you have a route like: /fetch/http://xkcd.com/534/
When false, the path will be cleaned, so /fetch/http://xkcd.com/534/ will become /fetch/http/xkcd.com/534
func WithStrictSlash ¶
WithStrictSlash defines the trailing slash behavior for new routes. The initial value is true.
When true, if the route path is "/path/", accessing "/path" will perform a redirect to the former and vice versa. In other words, your application will always see the path as specified in the route.
When false, if the route path is "/path", accessing "/path/" will not match this route and vice versa.
func WithTLSConfig ¶
WithTLSConfig optionally provides a TLS configuration for use by ServeTLS and ListenAndServeTLS. Note that this value is cloned by ServeTLS and ListenAndServeTLS, so it's not possible to modify the configuration with methods like tls.Config.SetSessionTicketKeys. To use SetSessionTicketKeys, use Server.Serve with a TLS Listener instead.
func WithTLSNextProto ¶
func WithTLSNextProto(proto map[string]func(*http.Server, *tls.Conn, http.Handler)) utility.Option[Server]
WithTLSNextProto optionally specifies a function to take over ownership of the provided TLS connection when an ALPN protocol upgrade has occurred. The map key is the protocol name negotiated. The Handler argument should be used to handle HTTP requests and will initialize the Request's TLS and RemoteAddr if not already set. The connection is automatically closed when the function returns. If TLSNextProto is not nil, HTTP/2 support is not enabled automatically.
func WithUseEncodedPath ¶
WithUseEncodedPath tells the router to match the encoded original path to the routes. For eg. "/path/foo%2Fbar/to" will match the path "/path/{var}/to".
If not called, the router will match the unencoded path to the routes. For eg. "/path/foo%2Fbar/to" will match the path "/path/foo/bar/to"
func WithVarsDecoder ¶
func WithVarsDecoder(decoder RequestDecoder) utility.Option[Server]
WithVarsDecoder custom request vars decoder this decoder decode request vars to request struct
type Greeter struct { Action string // register }
eg: http://127.0.0.1:8080/api/{action} http://127.0.0.1:8080/api/register
func WithWriteTimeout ¶
WithWriteTimeout is the maximum duration before timing out writes of the response. It is reset whenever a new request's header is read. Like ReadTimeout, it does not let Handlers make decisions on a per-request basis. A zero or negative value means there will be no timeout.
Types ¶
type CallOption ¶
type CallOption interface {
// contains filtered or unexported methods
}
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
func (*Context) BindMultipartForm ¶
func (*Context) Middleware ¶
func (c *Context) Middleware(handler middleware.Handler) middleware.Handler
func (*Context) Transport ¶
func (c *Context) Transport() (Transporter, bool)
func (*Context) WriteHeader ¶
type ErorrEncoderFunc ¶
type ErorrEncoderFunc func(w http.ResponseWriter, req *http.Request, err error)
ErrorEncoderFunc implemention ErrorEncoder
func (ErorrEncoderFunc) Encode ¶
func (encoder ErorrEncoderFunc) Encode(w http.ResponseWriter, req *http.Request, err error)
Encode encode error to ResponseWriter
type ErrorEncoder ¶
type ErrorEncoder interface {
Encode(w http.ResponseWriter, req *http.Request, err error)
}
ErrorEncoder is the handling error encoder
type Filter ¶
Filter is a HTTP Filter
func FilterChain ¶
FilterChain returns a FilterFunc that specifies the chained handler for HTTP Router.
type FilterFunc ¶
type RequestDecoder ¶
RequestDecoder encode request data to target
type RequestDecoderFunc ¶
RequestDecoderFunc implementation RequestDecoder
type ResponseEncoder ¶
ResponseEncoder encode and write value to http.ResponseWriter
type ResponseEncoderFunc ¶
ResponseEncoderFunc implementation ResponseEncoder
func (ResponseEncoderFunc) Encode ¶
func (encoder ResponseEncoderFunc) Encode(w http.ResponseWriter, req *http.Request, v any) error
Encode encode data to ResponseWriter
type RouteWalkFunc ¶
type RouteWalkFunc func(method, path string)
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
func NewRouter ¶
func NewRouter(middlewares ...middleware.Middleware) *Router
func (*Router) BodyDecoder ¶
BodyDecoder decode reqeust body data to target. Automatically decodes to target based on the Content-Type in the request header. The prerequisite is that you need to register the Codec with encoding.RegisterCodec. Otherwise, an error is returned.
This is the default BodyDecoder implementation, you can customise it when creating a Server using the Option
example:
NewServer(WithBodyDecoder(RequestDecoderFunc(func(req *http.Request, target any) error { // your logic })))
func (*Router) CONNECT ¶
func (r *Router) CONNECT(path string, handler Handler, middlewares ...middleware.Middleware)
func (*Router) DELETE ¶
func (r *Router) DELETE(path string, handler Handler, middlewares ...middleware.Middleware)
func (*Router) ErrorEncoder ¶
ErrorEncoder is the default ErrorEncoderFunc implemention
func (*Router) GET ¶
func (r *Router) GET(path string, handler Handler, middlewares ...middleware.Middleware)
func (*Router) Group ¶
func (r *Router) Group(prefix string, middlewares ...middleware.Middleware) *Router
func (*Router) HEAD ¶
func (r *Router) HEAD(path string, handler Handler, middlewares ...middleware.Middleware)
func (*Router) Handle ¶
func (r *Router) Handle(method, path string, handler Handler, middlewares ...middleware.Middleware)
func (*Router) OPTIONS ¶
func (r *Router) OPTIONS(path string, handler Handler, middlewares ...middleware.Middleware)
func (*Router) PATCH ¶
func (r *Router) PATCH(path string, handler Handler, middlewares ...middleware.Middleware)
func (*Router) POST ¶
func (r *Router) POST(path string, handler Handler, middlewares ...middleware.Middleware)
func (*Router) PUT ¶
func (r *Router) PUT(path string, handler Handler, middlewares ...middleware.Middleware)
func (*Router) QueryDecoder ¶
QueryDecoder decode request query params to target
func (*Router) ResponseEncoder ¶
ResponseEncoder is the default ResponseEncoderFunc implementation, Determine the encoding type from the Accept in the request Header. Returns error if no encoding is registered. you can customise it when creating a Server using the Option
example:
NewServer(WithResponseEncoder(ResponseEncoderFunc(w http.ResponseWriter, req *http.Request, v any) error { // your logic })))
func (*Router) SubContentType ¶
func (*Router) TRACE ¶
func (r *Router) TRACE(path string, handler Handler, middlewares ...middleware.Middleware)
func (*Router) VarsDecoder ¶
VarsDecoder decode request var to target
func (*Router) Walk ¶
func (r *Router) Walk(fn RouteWalkFunc) error
type Server ¶
type Server struct { *types.BaseServer *http.Server *Router // contains filtered or unexported fields }
Server is an HTTP server
func (*Server) RegisterService ¶
func (*Server) Walk ¶
func (h *Server) Walk(fn RouteWalkFunc) error
type Transport ¶
type Transport struct {
// contains filtered or unexported fields
}
Transport is an HTTP transport.
func (*Transport) RequestHeader ¶
func (*Transport) Response ¶
func (t *Transport) Response() http.ResponseWriter
func (*Transport) ResponseHeader ¶
type Transporter ¶
type Transporter interface { transport.Transporter // Method returns request method. // http: http.MethodConnect | http.MethodDelete | // http.MethodGet | http.MethodHead | http.MethodOptions | // http.MethodPatch | http.MethodPost | http.MethodPut | http.Method.Trace Method() string // Path returns request URL path // http.Request.URL.Path // eg: /api/v1/example Path() string // Template returns the http path template. Template() string // Request returns http request Request() *http.Request // Response returns http response writer Response() http.ResponseWriter }