httpx

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2024 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const HealthzURI = "/debug/healthz"

Variables

View Source
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

func DisableGeneralOptions(disable bool) utility.Option[Server]

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 WithAddr

func WithAddr(network, addr string) utility.Option[Server]

WithAddr optionally specifies the TCP address for the server to listen on

func WithBaseContext

func WithBaseContext(fn func(net.Listener) context.Context) utility.Option[Server]

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

func WithCodecType(codec string) utility.Option[Server]

WithCodecType change the default Codec type. The default type is json refer: encoding/*

func WithConnContext

func WithConnContext(fn func(context.Context, net.Conn) context.Context) utility.Option[Server]

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

func WithConnState(fn func(net.Conn, http.ConnState)) utility.Option[Server]

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

func WithDisableHealthz() utility.Option[Server]

WithDisableHealthz disable healthz handler

func WithErrorEncoder

func WithErrorEncoder(encoder ErrorEncoder) utility.Option[Server]

WithErrorEncoder write request error to ResponseWriter

func WithErrorLogger

func WithErrorLogger(logger *log.Logger) utility.Option[Server]

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

func WithIdleTimeout(timeout time.Duration) utility.Option[Server]

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

func WithListener(lis net.Listener) utility.Option[Server]

WithListener use this listener on Server

func WithLogger

func WithLogger(logger *slog.Logger) utility.Option[Server]

func WithMaxHeaderBytes

func WithMaxHeaderBytes(max int) utility.Option[Server]

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

func WithMethodNotAllowedHandler(handler http.Handler) utility.Option[Server]

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 WithMultipartMaxSize

func WithMultipartMaxSize(size int64) utility.Option[Server]

func WithNotFoundHandler

func WithNotFoundHandler(handler http.Handler) utility.Option[Server]

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
}

eg: http://127.0.0.1:8080/api?name=demo

func WithReadHeaderTimeout

func WithReadHeaderTimeout(timeout time.Duration) utility.Option[Server]

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

func WithReadTimeout(timeout time.Duration) utility.Option[Server]

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

func WithRouterHandler(router http.Handler) utility.Option[Server]

WithRouterHandler can custom http.Server.Handler

func WithSkipClean

func WithSkipClean(value bool) utility.Option[Server]

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

func WithStrictSlash(value bool) utility.Option[Server]

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

func WithTLSConfig(config *tls.Config) utility.Option[Server]

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

func WithUseEncodedPath() utility.Option[Server]

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

func WithWriteTimeout(timeout time.Duration) utility.Option[Server]

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

func (c *Context) Bind(target any) error

func (*Context) BindBody

func (c *Context) BindBody(target any) error

func (*Context) BindForm

func (c *Context) BindForm(target any) error

func (*Context) BindMultipartForm

func (c *Context) BindMultipartForm(target any) error

func (*Context) BindQuery

func (c *Context) BindQuery(target any) error

func (*Context) BindVars

func (c *Context) BindVars(target any) error

func (*Context) Blob

func (c *Context) Blob(data []byte, contentType string, code ...int) error

func (*Context) Deadline

func (c *Context) Deadline() (time.Time, bool)

func (*Context) Done

func (c *Context) Done() <-chan struct{}

func (*Context) Err

func (c *Context) Err() error

func (*Context) JSON

func (c *Context) JSON(v any, code ...int) error

func (*Context) Middleware

func (c *Context) Middleware(handler middleware.Handler) middleware.Handler

func (*Context) Stream

func (c *Context) Stream(reader io.Reader, contentType string, code ...int) error

func (*Context) String

func (c *Context) String(text string, code ...int) error

func (*Context) Transport

func (c *Context) Transport() (Transporter, bool)

func (*Context) Value

func (c *Context) Value(key interface{}) interface{}

func (*Context) Write

func (c *Context) Write(v any, code ...int) error

func (*Context) WriteHeader

func (c *Context) WriteHeader(contentType string, code []int)

func (*Context) XML

func (c *Context) XML(v any, code ...int) error

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

type Filter interface {
	Filt(http.Handler) http.Handler
}

Filter is a HTTP Filter

func FilterChain

func FilterChain(filters ...Filter) Filter

FilterChain returns a FilterFunc that specifies the chained handler for HTTP Router.

type FilterFunc

type FilterFunc func(http.Handler) http.Handler

func (FilterFunc) Filt

func (f FilterFunc) Filt(next http.Handler) http.Handler

type Handler

type Handler func(*Context) error

func MakeHandler

func MakeHandler[T, R any](fn func(ctx context.Context, in *T) (*R, error)) Handler

type RequestDecoder

type RequestDecoder interface {
	Decode(r *http.Request, target any) error
}

RequestDecoder encode request data to target

type RequestDecoderFunc

type RequestDecoderFunc func(r *http.Request, target any) error

RequestDecoderFunc implementation RequestDecoder

func (RequestDecoderFunc) Decode

func (decoder RequestDecoderFunc) Decode(r *http.Request, target any) error

Decode deocde request data to target

type ResponseEncoder

type ResponseEncoder interface {
	Encode(w http.ResponseWriter, req *http.Request, v any) error
}

ResponseEncoder encode and write value to http.ResponseWriter

type ResponseEncoderFunc

type ResponseEncoderFunc func(w http.ResponseWriter, req *http.Request, v any) error

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

func (r *Router) BodyDecoder(req *http.Request, target any) error

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

func (r *Router) ErrorEncoder(w http.ResponseWriter, req *http.Request, err error)

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

func (r *Router) QueryDecoder(req *http.Request, target any) error

QueryDecoder decode request query params to target

func (*Router) ResponseEncoder

func (r *Router) ResponseEncoder(w http.ResponseWriter, req *http.Request, v any) error

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

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Router) SubContentType

func (r *Router) SubContentType(contentType string) string

func (*Router) TRACE

func (r *Router) TRACE(path string, handler Handler, middlewares ...middleware.Middleware)

func (*Router) VarsDecoder

func (r *Router) VarsDecoder(req *http.Request, target any) error

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 NewServer

func NewServer(opts ...utility.Option[Server]) *Server

NewServer returns HTTP server instance by options

func (*Server) RegisterService

func (h *Server) RegisterService(service ...types.Service)

func (*Server) Run

func (h *Server) Run(ctx context.Context) error

func (*Server) Shutdown

func (h *Server) Shutdown(ctx context.Context) error

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

func (t *Transport) AddHeader(key, value string)

func (*Transport) Kind

func (t *Transport) Kind() transport.Kind

func (*Transport) Method

func (t *Transport) Method() string

func (*Transport) Path

func (t *Transport) Path() string

func (*Transport) Request

func (t *Transport) Request() *http.Request

func (*Transport) RequestHeader

func (t *Transport) RequestHeader() transport.Header

func (*Transport) Response

func (t *Transport) Response() http.ResponseWriter

func (*Transport) ResponseHeader

func (t *Transport) ResponseHeader() transport.Header

func (*Transport) SetHeader

func (t *Transport) SetHeader(key, value string)

func (*Transport) Template

func (t *Transport) Template() string

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
}

Jump to

Keyboard shortcuts

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