Documentation ¶
Index ¶
- Constants
- Variables
- type Context
- type File
- type Group
- func (g *Group) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (cm *Group) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (cm *Group) Connect(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (cm *Group) Delete(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (cm *Group) File(path, file string, m ...MiddlewareFunc)
- func (cm *Group) Get(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) Group(prefix string, middleware ...MiddlewareFunc) *Group
- func (cm *Group) Head(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (cm *Group) Match(methods []string, path string, handler HandlerFunc, ...)
- func (cm *Group) Options(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (cm *Group) Patch(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (cm *Group) Post(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (cm *Group) Put(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (cm *Group) Static(prefix, root string)
- func (cm *Group) Trace(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (g *Group) Use(middleware ...MiddlewareFunc)
- type HTTPError
- type HTTPErrorHandler
- type HTTPOKHandler
- type HandlerFunc
- type Map
- type MiddlewareFunc
- type ResponseWriter
- func (r *ResponseWriter) After(fn func())
- func (r *ResponseWriter) Before(fn func())
- func (r *ResponseWriter) Flush()
- func (r *ResponseWriter) Header() http.Header
- func (r *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (r *ResponseWriter) Write(b []byte) (n int, err error)
- func (r *ResponseWriter) WriteHeader(code int)
- type Route
- type RouteCache
- type Router
- type Server
- func (s *Server) AcquireContext() Context
- func (s *Server) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (cm *Server) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc)
- func (s *Server) Close() error
- func (cm *Server) Connect(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (s *Server) DefaultHTTPErrorHandler(err error, c Context)
- func (s *Server) DefaultHTTPOKHandler(data any, c Context) error
- func (cm *Server) Delete(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (cm *Server) File(path, file string, m ...MiddlewareFunc)
- func (cm *Server) Get(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (s *Server) Group(prefix string, m ...MiddlewareFunc) *Group
- func (cm *Server) Head(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (cm *Server) Match(methods []string, path string, handler HandlerFunc, ...)
- func (s *Server) NewContext(r *http.Request, w http.ResponseWriter) Context
- func (cm *Server) Options(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (cm *Server) Patch(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (cm *Server) Post(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (s *Server) Pre(middleware ...MiddlewareFunc)
- func (cm *Server) Put(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (s *Server) ReleaseContext(c Context)
- func (s *Server) Router() *Router
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) Shutdown(ctx stdContext.Context) error
- func (s *Server) Start(address string) error
- func (s *Server) StartServer(h *http.Server) (err error)
- func (cm *Server) Static(prefix, root string)
- func (cm *Server) Trace(path string, h HandlerFunc, m ...MiddlewareFunc)
- func (s *Server) Use(middleware ...MiddlewareFunc)
Constants ¶
const ( MIMEApplicationJSON = "application/json" MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8 MIMEApplicationJavaScript = "application/javascript" MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8 MIMEApplicationXML = "application/xml" MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + charsetUTF8 MIMETextXML = "text/xml" MIMETextXMLCharsetUTF8 = MIMETextXML + "; " + charsetUTF8 MIMEApplicationForm = "application/x-www-form-urlencoded" MIMEApplicationProtobuf = "application/protobuf" MIMEApplicationMsgpack = "application/msgpack" MIMETextHTML = "text/html" MIMETextHTMLCharsetUTF8 = MIMETextHTML + "; " + charsetUTF8 MIMETextPlain = "text/plain" MIMETextPlainCharsetUTF8 = MIMETextPlain + "; " + charsetUTF8 MIMEMultipartForm = "multipart/form-data" MIMEOctetStream = "application/octet-stream" )
MIME types
const ( // PROPFIND Method can be used on collection and property resources. PROPFIND = "PROPFIND" // REPORT Method can be used to get information about a resource, see rfc 3253 REPORT = "REPORT" )
const ( HeaderAccept = "Accept" HeaderAcceptEncoding = "Accept-Encoding" HeaderAllow = "Allow" HeaderAuthorization = "Authorization" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLength = "Content-Length" HeaderContentType = "Content-Type" HeaderCookie = "Cookie" HeaderSetCookie = "Set-Cookie" HeaderIfModifiedSince = "If-Modified-Since" HeaderLastModified = "Last-Modified" HeaderLocation = "Location" HeaderUpgrade = "Upgrade" HeaderVary = "Vary" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXForwardedProtocol = "X-Forwarded-Protocol" HeaderXForwardedSsl = "X-Forwarded-Ssl" HeaderXUrlScheme = "X-Url-Scheme" HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" HeaderXRealIP = "X-Real-IP" HeaderXRequestID = "X-Request-ID" HeaderXRequestedWith = "X-Requested-With" HeaderServer = "Server" HeaderOrigin = "Origin" // Access control HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" // Security HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXXSSProtection = "X-XSS-Protection" HeaderXFrameOptions = "X-Frame-Options" HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" HeaderXCSRFToken = "X-CSRF-Token" HeaderReferrerPolicy = "Referrer-Policy" )
Headers
Variables ¶
var ( ErrUnsupportedMediaType = NewHTTPError(http.StatusUnsupportedMediaType) ErrNotFound = NewHTTPError(http.StatusNotFound) ErrForbidden = NewHTTPError(http.StatusForbidden) ErrMethodNotAllowed = NewHTTPError(http.StatusMethodNotAllowed) ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge) ErrTooManyRequests = NewHTTPError(http.StatusTooManyRequests) ErrBadRequest = NewHTTPError(http.StatusBadRequest) ErrBadGateway = NewHTTPError(http.StatusBadGateway) ErrInternalServerError = NewHTTPError(http.StatusInternalServerError) ErrRequestTimeout = NewHTTPError(http.StatusRequestTimeout) ErrValidatorNotRegistered = errors.New("validator not registered") ErrActionNotExists = errors.New("action not exists") ErrInvalidRedirectCode = errors.New("invalid redirect status code") ErrCookieNotFound = errors.New("cookie not found") ErrInvalidListenerNetwork = errors.New("invalid listener network") )
Errors
var ( NotFoundHandler = func(c Context) error { return ErrNotFound } MethodNotAllowedHandler = func(c Context) error { return ErrMethodNotAllowed } )
Error handlers
Functions ¶
This section is empty.
Types ¶
type Context ¶
type Context interface { stdContext.Context // Request returns `*http.Request`. Request() *http.Request SetRequest(*http.Request) // ResponseWriter returns `*Response`. ResponseWriter() *ResponseWriter SetResponseWriter(*ResponseWriter) // GetRoutePath route info GetRoutePath() string Bind(any) error // Param returns path parameter by name. Param(name string) (string, bool) // ParamValues returns path parameter values. ParamValues() []string GetString(name string, defVal ...string) string GetInt(name string, defVal ...int) int GetInt64(name string, defVal ...int64) int64 GetUint(name string, defVal ...uint) uint GetUint64(name string, defVal ...uint64) uint64 PostString(name string, defVal ...string) string PostInt(name string, defVal ...int) int PostInt64(name string, defVal ...int64) int64 PostUint(name string, defVal ...uint) uint PostUint64(name string, defVal ...uint64) uint64 Cookie(name string) (string, bool) QueryParam(name string) string FormValue(name string) string FormParams() (url.Values, error) FormFile(name string) (*multipart.FileHeader, error) MultipartForm() (*multipart.Form, error) // WithValue 存入数据到当前请求的context WithValue(key string, val any) // SetResponseHeader 设置响应头 SetResponseHeader(headerOptions map[string]string) *context // RequestHeader 获取请求头 RequestHeader(name string) string // JSON sends a JSON response with status code. JSON(code int, i any) error // Blob sends a blob response with status code and content type. Blob(code int, contentType string, b []byte) error // HTML sends an HTTP response with status code. HTML(code int, html string) error // HTMLBlob sends an HTTP blob response with status code. HTMLBlob(code int, b []byte) error // Stream sends a streaming response with status code and content type. Stream(code int, contentType string, r io.Reader) error // File sends a response with the content of the file. File(file string) error // Attachment sends a response as attachment, prompting client to save the // file. Attachment(file string, name string) error // Inline sends a response as inline, opening the file in the browser. Inline(file string, name string) error // NoContent sends a response with no body and a status code. NoContent(code int) error // Redirect redirects the request to a provided URL with status code. Redirect(code int, url string) error // Error invokes the registered HTTP error handler. Generally used by middleware. Error(err error) // Handler returns the matched handler by router. Handler() HandlerFunc // IsDebug return the Server is debug. IsDebug() bool // contains filtered or unexported methods }
Context represents the context of the current HTTP request. It holds request and response objects, path, path parameters, data and registered handler.
type File ¶ added in v0.2.35
type File struct { File multipart.File FileHeader *multipart.FileHeader }
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group is a set of sub-routes for a specified route. It can be used for inner routes that share a common middleware or functionality that should be separate from the parent engine instance while still inheriting from it.
func (*Group) Add ¶
func (g *Group) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc)
Add implements `Server#Add()` for sub-routes within the Group.
func (*Group) Any ¶
func (cm *Group) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc)
Any registers a new route for all HTTP methods and path with matching handler in the router with optional route-level middleware.
func (*Group) Connect ¶
func (cm *Group) Connect(path string, h HandlerFunc, m ...MiddlewareFunc)
Connect registers a new CONNECT route for a path with matching handler in the router with optional route-level middleware.
func (*Group) Delete ¶
func (cm *Group) Delete(path string, h HandlerFunc, m ...MiddlewareFunc)
Delete registers a new DELETE route for a path with matching handler in the router with optional route-level middleware.
func (*Group) File ¶
func (cm *Group) File(path, file string, m ...MiddlewareFunc)
File registers a new route with path to serve a static file with optional route-level middleware.
func (*Group) Get ¶
func (cm *Group) Get(path string, h HandlerFunc, m ...MiddlewareFunc)
Get registers a new GET route for a path with matching handler in the router with optional route-level middleware.
func (*Group) Group ¶
func (g *Group) Group(prefix string, middleware ...MiddlewareFunc) *Group
Group creates a new sub-group with prefix and optional sub-group-level middleware.
func (*Group) Head ¶
func (cm *Group) Head(path string, h HandlerFunc, m ...MiddlewareFunc)
Head registers a new HEAD route for a path with matching handler in the router with optional route-level middleware.
func (*Group) Match ¶
func (cm *Group) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc)
Match registers a new route for multiple HTTP methods and path with matching handler in the router with optional route-level middleware.
func (*Group) Options ¶
func (cm *Group) Options(path string, h HandlerFunc, m ...MiddlewareFunc)
Options registers a new OPTIONS route for a path with matching handler in the router with optional route-level middleware.
func (*Group) Patch ¶
func (cm *Group) Patch(path string, h HandlerFunc, m ...MiddlewareFunc)
Patch registers a new PATCH route for a path with matching handler in the router with optional route-level middleware.
func (*Group) Post ¶
func (cm *Group) Post(path string, h HandlerFunc, m ...MiddlewareFunc)
Post registers a new POST route for a path with matching handler in the router with optional route-level middleware.
func (*Group) Put ¶
func (cm *Group) Put(path string, h HandlerFunc, m ...MiddlewareFunc)
Put registers a new PUT route for a path with matching handler in the router with optional route-level middleware.
func (*Group) Static ¶
func (cm *Group) Static(prefix, root string)
Static registers a new route with path prefix to serve static files from the provided root directory.
func (*Group) Trace ¶
func (cm *Group) Trace(path string, h HandlerFunc, m ...MiddlewareFunc)
Trace registers a new TRACE route for a path with matching handler in the router with optional route-level middleware.
func (*Group) Use ¶
func (g *Group) Use(middleware ...MiddlewareFunc)
Use implements `Server#Use()` for sub-routes within the Group.
type HTTPError ¶
type HTTPError struct { Code int `json:"code"` Errno int `json:"errno"` Message any `json:"message"` Internal error `json:"-"` // Stores the error returned by an external dependency }
HTTPError represents an error that occurred while handling a request.
func NewHTTPError ¶
NewHTTPError creates a new HTTPError instance.
func (HTTPError) SetInternal ¶
SetInternal copy and set error to HTTPError.Internal
type HTTPErrorHandler ¶
HTTPErrorHandler is a centralized HTTP error handler.
type HTTPOKHandler ¶ added in v0.5.1
HTTPOKHandler is a centralized HTTP ok handler.
type HandlerFunc ¶
HandlerFunc defines a function to serve HTTP requests.
func AssetHandler ¶
func AssetHandler(prefix string, assets embed.FS, root string) HandlerFunc
AssetHandler returns an http.Handler that will serve files from the Assets embed.FS. When locating a file, it will strip the given prefix from the request and prepend the root to the filesystem.
func Controller ¶
func Controller(h any, methodName ...string) HandlerFunc
Controller 转为 server.HandlerFunc
func WrapHandler ¶
func WrapHandler(h http.Handler) HandlerFunc
WrapHandler wraps `http.Handler` into `HandlerFunc`.
type MiddlewareFunc ¶
type MiddlewareFunc func(HandlerFunc) HandlerFunc
MiddlewareFunc defines a function to process middleware.
func WrapMiddleware ¶
func WrapMiddleware(m func(http.Handler) http.Handler) MiddlewareFunc
WrapMiddleware wraps `func(http.Handler) http.Handler` into `MiddlewareFunc`
type ResponseWriter ¶
type ResponseWriter struct { Writer http.ResponseWriter Status int Size int64 Committed bool // contains filtered or unexported fields }
ResponseWriter wraps an http.ResponseWriter and implements its interface to be used by an HTTP handler to construct an HTTP response.
func NewResponseWriter ¶
func NewResponseWriter(w http.ResponseWriter) (r *ResponseWriter)
NewResponseWriter creates a new instance of Response.
func (*ResponseWriter) After ¶
func (r *ResponseWriter) After(fn func())
After registers a function which is called just after the response is written. If the `Content-Length` is unknown, none of the after function is executed.
func (*ResponseWriter) Before ¶
func (r *ResponseWriter) Before(fn func())
Before registers a function which is called just before the response is written.
func (*ResponseWriter) Flush ¶
func (r *ResponseWriter) Flush()
Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client.
func (*ResponseWriter) Header ¶
func (r *ResponseWriter) Header() http.Header
Header returns the header map for the writer that will be sent by WriteHeader. Changing the header after a call to WriteHeader (or Write) has no effect unless the modified headers were declared as trailers by setting the "Trailer" header before the call to WriteHeader (see example) To suppress implicit response headers, set their value to nil.
func (*ResponseWriter) Hijack ¶
func (r *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection.
func (*ResponseWriter) Write ¶
func (r *ResponseWriter) Write(b []byte) (n int, err error)
Write writes the data to the connection as part of an HTTP reply.
func (*ResponseWriter) WriteHeader ¶
func (r *ResponseWriter) WriteHeader(code int)
WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.
type RouteCache ¶ added in v0.5.1
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router is the registry of all registered routes for an `Server` instance for request matching and URL path parameter parsing.
func (*Router) Add ¶
func (r *Router) Add(method, path string, h HandlerFunc)
Add registers a new route for method and path with matching handler.
type Server ¶
type Server struct { Http *http.Server Listener net.Listener Debug bool HTTPErrorHandler HTTPErrorHandler HTTPOKHandler HTTPOKHandler Logger *log.Logger ListenerNetwork string // contains filtered or unexported fields }
Server is the top-level framework instance.
func (*Server) AcquireContext ¶
AcquireContext returns an empty `Context` instance from the pool. You must return the context by calling `ReleaseContext()`.
func (*Server) Add ¶
func (s *Server) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc)
Add registers a new route for an HTTP method and path with matching handler in the router with optional route-level middleware.
func (*Server) Any ¶
func (cm *Server) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc)
Any registers a new route for all HTTP methods and path with matching handler in the router with optional route-level middleware.
func (*Server) Close ¶
Close immediately stops the server. It internally calls `http.Server#Close()`.
func (*Server) Connect ¶
func (cm *Server) Connect(path string, h HandlerFunc, m ...MiddlewareFunc)
Connect registers a new CONNECT route for a path with matching handler in the router with optional route-level middleware.
func (*Server) DefaultHTTPErrorHandler ¶
DefaultHTTPErrorHandler is the default HTTP error handler. It sends a JSON response with status code.
func (*Server) DefaultHTTPOKHandler ¶ added in v0.5.1
DefaultHTTPOKHandler is the default HTTP ok handler. It sends a JSON response with status code.
func (*Server) Delete ¶
func (cm *Server) Delete(path string, h HandlerFunc, m ...MiddlewareFunc)
Delete registers a new DELETE route for a path with matching handler in the router with optional route-level middleware.
func (*Server) File ¶
func (cm *Server) File(path, file string, m ...MiddlewareFunc)
File registers a new route with path to serve a static file with optional route-level middleware.
func (*Server) Get ¶
func (cm *Server) Get(path string, h HandlerFunc, m ...MiddlewareFunc)
Get registers a new GET route for a path with matching handler in the router with optional route-level middleware.
func (*Server) Group ¶
func (s *Server) Group(prefix string, m ...MiddlewareFunc) *Group
Group creates a new router group with prefix and optional group-level middleware.
func (*Server) Head ¶
func (cm *Server) Head(path string, h HandlerFunc, m ...MiddlewareFunc)
Head registers a new HEAD route for a path with matching handler in the router with optional route-level middleware.
func (*Server) Match ¶
func (cm *Server) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc)
Match registers a new route for multiple HTTP methods and path with matching handler in the router with optional route-level middleware.
func (*Server) NewContext ¶
NewContext returns a Context instance.
func (*Server) Options ¶
func (cm *Server) Options(path string, h HandlerFunc, m ...MiddlewareFunc)
Options registers a new OPTIONS route for a path with matching handler in the router with optional route-level middleware.
func (*Server) Patch ¶
func (cm *Server) Patch(path string, h HandlerFunc, m ...MiddlewareFunc)
Patch registers a new PATCH route for a path with matching handler in the router with optional route-level middleware.
func (*Server) Post ¶
func (cm *Server) Post(path string, h HandlerFunc, m ...MiddlewareFunc)
Post registers a new POST route for a path with matching handler in the router with optional route-level middleware.
func (*Server) Pre ¶
func (s *Server) Pre(middleware ...MiddlewareFunc)
Pre adds middleware to the chain which is run before router.
func (*Server) Put ¶
func (cm *Server) Put(path string, h HandlerFunc, m ...MiddlewareFunc)
Put registers a new PUT route for a path with matching handler in the router with optional route-level middleware.
func (*Server) ReleaseContext ¶
ReleaseContext returns the `Context` instance back to the pool. You must call it after `AcquireContext()`.
func (*Server) ServeHTTP ¶
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements `http.Handler` interface, which serves HTTP requests.
func (*Server) Shutdown ¶
func (s *Server) Shutdown(ctx stdContext.Context) error
Shutdown stops the server gracefully. It internally calls `http.Server#Shutdown()`.
func (*Server) StartServer ¶
StartServer starts a custom http server.
func (*Server) Static ¶
func (cm *Server) Static(prefix, root string)
Static registers a new route with path prefix to serve static files from the provided root directory.
func (*Server) Trace ¶
func (cm *Server) Trace(path string, h HandlerFunc, m ...MiddlewareFunc)
Trace registers a new TRACE route for a path with matching handler in the router with optional route-level middleware.
func (*Server) Use ¶
func (s *Server) Use(middleware ...MiddlewareFunc)
Use adds middleware to the chain which is run after router.