Documentation ¶
Index ¶
- Constants
- func LogEntryRecorder(next http.Handler) http.Handler
- func ReadJSON(r io.Reader, data any) error
- func ResolveError(err error) error
- func WriteJSON(w http.ResponseWriter, data any, code int) error
- type GracefulRunner
- type Handler
- type HandlerFunc
- type LastResortErrorHandler
- type LogBodyReader
- type LogEntry
- type MuxConfig
- type MuxMiddleware
- type MuxOption
- type NetMiddleware
- type Param
- type Params
- type ResolvedError
- type Route
- type RunConfig
- type RunEvent
- type RunOption
- type Runner
- type ServeMux
Constants ¶
const DefaultHandler defaultHandlerNamespace = 0
DefaultHandler is a namespace for accessing default handlers.
const Opts muxOptionNamespace = 0
Opts is a namespace for accessing options.
const RunOpts runOptionNamespace = 0
RunOpts is the namespace for accessing the Option for customizing the GracefulRunner.
Variables ¶
This section is empty.
Functions ¶
func LogEntryRecorder ¶
LogEntryRecorder is a middleware that records the request and response on demand. The request body is not recorded until it is read by the handler. And the response body is not recorded until it is written by the handler.
The recorded entry can be retrieved by calling GetLogEntry(w http.ResponseWriter).
Types ¶
type GracefulRunner ¶
type GracefulRunner struct { Runner // contains filtered or unexported fields }
GracefulRunner is a wrapper of http.Server that can be shutdown gracefully.
func NewGracefulRunner ¶
func NewGracefulRunner(server Runner, opts ...RunOption) *GracefulRunner
NewGracefulRunner wraps a Server with graceful shutdown capability. It will listen to SIGINT and SIGTERM signals to initiate shutdown and wait for all active connections to be closed. If still active connections after wait timeout exceeded, it will force close the server. The default wait timeout is 5 seconds.
func (*GracefulRunner) ListenAndServe ¶
func (s *GracefulRunner) ListenAndServe() error
ListenAndServe starts listening and serving the server gracefully.
type Handler ¶
type Handler interface { // ServeHTTP is just like http.Handler.ServeHTTP, but it returns an error. ServeHTTP(http.ResponseWriter, *http.Request) error }
Handler is modified version of http.Handler.
type HandlerFunc ¶
type HandlerFunc func(http.ResponseWriter, *http.Request) error
HandlerFunc is a function that implements Handler. It is used to create a Handler from an ordinary function.
func (HandlerFunc) ServeHTTP ¶
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) error
ServeHTTP implements Handler.
type LastResortErrorHandler ¶
type LastResortErrorHandler func(http.ResponseWriter, *http.Request, error)
LastResortErrorHandler is the error handler that is called if after all middlewares, there is still an error occurs.
type LogBodyReader ¶
type LogBodyReader interface { io.ReaderFrom Len() int Bytes() []byte }
LogBodyReader knows how to read the request or response body.
type LogEntry ¶
type LogEntry struct { StatusCode int RespondedAt int64 RequestedAt int64 // DiscardReqBody and DiscardResBody are used to indicate whether the request // or response body should be discarded. By default, both are false. DiscardReqBody bool DiscardResBody bool // contains filtered or unexported fields }
LogEntry contains recorded request and response information.
func GetLogEntry ¶
func GetLogEntry(w http.ResponseWriter) (*LogEntry, bool)
GetLogEntry gets the recorded LogEntry from the given http.ResponseWriter by unwrapping the http.ResponseWriter, if not found, it returns false.
func (*LogEntry) ReqBody ¶
func (l *LogEntry) ReqBody() LogBodyReader
ReqBody returns the request body.
func (*LogEntry) ResBody ¶
func (l *LogEntry) ResBody() LogBodyReader
ResBody returns the response body.
type MuxConfig ¶
type MuxConfig struct { // Enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // If enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterward the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // If enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool // If enabled, the router automatically replies to OPTIONS requests. // Custom OPTIONS handlers take priority over automatic replies. HandleOPTIONS bool // An optional http.Handler that is called on automatic OPTIONS requests. // The handler is only called if HandleOPTIONS is true and no OPTIONS // handler for the specific path was set. // The "Allowed" header is set before calling the handler. GlobalOPTIONS http.Handler // Configurable http.Handler which is called when no matching route is // found. NotFound http.Handler // Configurable http.Handler which is called when a request // cannot be routed and HandleMethodNotAllowed is true. // The "Allow" header with allowed request methods is set before the handler // is called. MethodNotAllowed http.Handler // Function to handle panics recovered from http handlers. // It should be used to generate an error page and return the http error code // 500 (Internal Server Error). // The handler can be used to keep your server from crashing because of // unrecoverable panics. PanicHandler func(http.ResponseWriter, *http.Request, any) // LastResortErrorHandler is the error handler that is called if after all middlewares, // there is still an error occurs. This handler is used to catch errors that are not handled by the middlewares. // // This handler is not part of the httprouter.Router, it is used by the ServeMux. LastResortErrorHandler LastResortErrorHandler }
MuxConfig is the configuration for the underlying httprouter.Router.
type MuxMiddleware ¶
MuxMiddleware is a middleware that applies to route handler. It is used to create a middleware that is compatible with httpkit.Handler.
func ReduceMuxMiddleware ¶
func ReduceMuxMiddleware(middlewares ...MuxMiddleware) MuxMiddleware
ReduceMuxMiddleware reduces a set of mux middlewares into a single mux middleware. For example:
ReduceMuxMiddleware(m1, m2, m3).Then(h) will be equivalent to: m1(m2(m3(h)))
func (MuxMiddleware) Then ¶
func (m MuxMiddleware) Then(h Handler) Handler
Then is a syntactic sugar for applying the middleware to the handler. Instead of: m(h), you can write: m.Then(h).
type MuxOption ¶
type MuxOption func(mux *ServeMux)
MuxOption is an option for customizing the ServeMux.
type NetMiddleware ¶
NetMiddleware is a middleware that applies to the root handler. It is used to create a middleware that is compatible with net/http.
func ReduceNetMiddleware ¶
func ReduceNetMiddleware(middlewares ...NetMiddleware) NetMiddleware
ReduceNetMiddleware reduces a set of net middlewares into a single net middleware. For example:
ReduceNetMiddleware(m1, m2, m3).Then(h) will be equivalent to: m1(m2(m3(h)))
type Params ¶
type Params = httprouter.Params
Params is alias of httprouter.Params.
func PathParams ¶
PathParams gets the path variables from the request.
type ResolvedError ¶
type ResolvedError struct {
Err error // the original error.
}
ResolvedError is an error that has been resolved. When an error is resolved, it means that the error has been mapped to an HTTP response and the no error will be handled by the LastResortErrorHandler.
func (*ResolvedError) Error ¶
func (e *ResolvedError) Error() string
Error implements error interface.
type Route ¶
type Route struct { Method string Path string Handler HandlerFunc }
Route is used to register a new handler to the ServeMux.
type RunConfig ¶
type RunConfig struct { Port int // Port to listen to. ShutdownTimeout time.Duration // Maximum duration for waiting all active connections to be closed before force close. // RequestReadTimeout and RequestWriteTimeout are timeouts for http.Server. // These timeouts are used to limit the time spent reading or writing the request body. // see: https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts. RequestReadTimeout time.Duration // Maximum duration for reading the entire request, including the body. RequestWriteTimeout time.Duration // Maximum duration before timing out writes of the response. }
RunConfig is a configuration for creating a http Runner.
type RunEvent ¶
type RunEvent uint8
RunEvent is a flag to differentiate run events.
type RunOption ¶
type RunOption func(*GracefulRunner)
RunOption is the option for customizing the GracefulRunner.
type Runner ¶
type Runner interface { // ListenAndServe starts listening and serving the server. // This method should block until shutdown signal received or failed to start. ListenAndServe() error // Shutdown gracefully shuts down the server, it will wait for all active connections to be closed. Shutdown(ctx context.Context) error // Close force closes the server. // Close is called when Shutdown timeout exceeded. Close() error }
Runner is contract for server that can be started, shutdown gracefully and force closed if shutdown timeout exceeded.
type ServeMux ¶
type ServeMux struct {
// contains filtered or unexported fields
}
ServeMux is a wrapper of httprouter.Router with modified Handler. Instead of http.Handler, it uses Handler, which returns an error. This modification is used to simplify logic for creating a centralized error handler and logging.
The ServeMux also supports MuxMiddleware, which is a middleware that wraps the Handler for all routes. Since the ServeMux also implements http.Handler, the NetMiddleware can be used to create middleware that will be executed before the ServeMux middleware.
The ServeMux only exposes 3 methods: Route, Handle, and ServeHTTP, which are more simple than the original.
func NewServeMux ¶
NewServeMux creates a new ServeMux with given options. If no option is given, the Default option is applied.
func (*ServeMux) Route ¶
func (mux *ServeMux) Route(r Route, mid ...MuxMiddleware)
Route is a syntactic sugar for Handle(method, path, handler) by using Route struct. This route also accepts variadic MuxMiddleware, which is applied to the route handler.