Documentation
¶
Overview ¶
Package ship has implemented a flexible, powerful, high performance and minimalist Go Web HTTP router framework, which is inspired by echo and httprouter.
Index ¶
- Constants
- Variables
- func AddContentTypeToSlice(contentType string, contentTypeSlice []string)
- func CopyNBuffer(dst io.Writer, src io.Reader, n int64, buf []byte) (written int64, err error)
- func DeleteJSON(url string, req interface{}, resp ...interface{}) (err error)
- func DisalbeRedirect(req *http.Request, via []*http.Request) error
- func GetJSON(url string, resp ...interface{}) (err error)
- func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*http.Request, error)
- func PostJSON(url string, req interface{}, resp ...interface{}) (err error)
- func PutJSON(url string, req interface{}, resp ...interface{}) (err error)
- func PutResponseIntoPool(r *Response)
- func RequestJSON(method, url string, req interface{}, resp ...interface{}) (err error)
- func RequestJSONWithContext(ctx context.Context, method, url string, reqBody interface{}, ...) (err error)
- func RequestJSONWithContextAndHeaders(ctx context.Context, method, url string, reqHeaders http.Header, ...) (err error)
- func SetContentType(res http.ResponseWriter, ct string)
- func SetHeaderContentType(header http.Header, ct string)
- func SetStructFieldToDefault(v interface{}) (err error)
- func ToHTTPHandler(s *Ship, h Handler) http.Handler
- type BufferAllocator
- type Context
- func (c *Context) Accept() []string
- func (c *Context) AcquireBuffer() *bytes.Buffer
- func (c *Context) AddHeader(name, value string)
- func (c *Context) Attachment(file string, name string) error
- func (c *Context) BasicAuth() (username, password string, ok bool)
- func (c *Context) Bind(v interface{}) (err error)
- func (c *Context) BindQuery(v interface{}) (err error)
- func (c *Context) Blob(code int, contentType string, b []byte) (err error)
- func (c *Context) BlobText(code int, contentType string, format string, args ...interface{}) (err error)
- func (c *Context) Body() io.ReadCloser
- func (c *Context) Charset() string
- func (c *Context) ClearData()
- func (c *Context) ClientIP() string
- func (c *Context) ContentLength() int64
- func (c *Context) ContentType() (ct string)
- func (c *Context) Cookie(name string) *http.Cookie
- func (c *Context) Cookies() []*http.Cookie
- func (c *Context) DelHeader(name string)
- func (c *Context) DelSession(id string) (err error)
- func (c *Context) Error(code int, err error) HTTPServerError
- func (c *Context) Execute() error
- func (c *Context) File(file string) (err error)
- func (c *Context) FindRoute() (ri RouteInfo, ok bool)
- func (c *Context) FormFile(name string) (multipart.File, *multipart.FileHeader, error)
- func (c *Context) FormParams() (url.Values, error)
- func (c *Context) FormValue(name string, defaultValue ...string) string
- func (c *Context) GetBody() (string, error)
- func (c *Context) GetBodyReader() (buf *bytes.Buffer, err error)
- func (c *Context) GetHeader(name string, defaultValue ...string) string
- func (c *Context) GetSession(id string) (v interface{}, err error)
- func (c *Context) HTML(code int, html string) error
- func (c *Context) HTMLBlob(code int, b []byte) error
- func (c *Context) HasHeader(name string) bool
- func (c *Context) HasQuery(name string) bool
- func (c *Context) Header() http.Header
- func (c *Context) Host() string
- func (c *Context) Hostname() string
- func (c *Context) Inline(file string, name string) error
- func (c *Context) IsAjax() bool
- func (c *Context) IsResponded() bool
- func (c *Context) IsTLS() bool
- func (c *Context) IsWebSocket() bool
- func (c *Context) JSON(code int, v interface{}) error
- func (c *Context) JSONBlob(code int, b []byte) error
- func (c *Context) JSONP(code int, callback string, i interface{}) error
- func (c *Context) JSONPBlob(code int, callback string, b []byte) (err error)
- func (c *Context) JSONPretty(code int, v interface{}, indent string) error
- func (c *Context) Logger() Logger
- func (c *Context) Method() string
- func (c *Context) MultipartForm() (*multipart.Form, error)
- func (c *Context) MultipartReader() (*multipart.Reader, error)
- func (c *Context) NoContent(code int) error
- func (c *Context) NotFoundHandler() Handler
- func (c *Context) Path() string
- func (c *Context) QueryParam(name string, defaultValue ...string) string
- func (c *Context) QueryParams() url.Values
- func (c *Context) QueryRawString() string
- func (c *Context) RealIP() string
- func (c *Context) Redirect(code int, toURL string) error
- func (c *Context) Referer() string
- func (c *Context) ReleaseBuffer(buf *bytes.Buffer)
- func (c *Context) RemoteAddr() string
- func (c *Context) Render(name string, code int, data interface{}) error
- func (c *Context) RenderOk(name string, data interface{}) error
- func (c *Context) ReqHeader() http.Header
- func (c *Context) Request() *http.Request
- func (c *Context) RequestURI() string
- func (c *Context) Reset()
- func (c *Context) RespHeader() http.Header
- func (c *Context) Respond(args ...interface{}) error
- func (c *Context) Response() *Response
- func (c *Context) ResponseWriter() http.ResponseWriter
- func (c *Context) Router() router.Router
- func (c *Context) Scheme() (scheme string)
- func (c *Context) SetBinder(b binder.Binder)
- func (c *Context) SetBufferAllocator(alloc BufferAllocator)
- func (c *Context) SetConnectionClose()
- func (c *Context) SetContentType(ct string)
- func (c *Context) SetCookie(cookie *http.Cookie)
- func (c *Context) SetDefault(v interface{}) error
- func (c *Context) SetDefaulter(v func(interface{}) error)
- func (c *Context) SetHeader(name, value string)
- func (c *Context) SetLogger(logger Logger)
- func (c *Context) SetNotFoundHandler(notFound Handler)
- func (c *Context) SetQueryBinder(f func(interface{}, url.Values) error)
- func (c *Context) SetRenderer(r render.Renderer)
- func (c *Context) SetReqRes(r *http.Request, w http.ResponseWriter)
- func (c *Context) SetRequest(req *http.Request)
- func (c *Context) SetResponder(h func(*Context, ...interface{}) error)
- func (c *Context) SetResponse(res http.ResponseWriter)
- func (c *Context) SetRouter(r router.Router)
- func (c *Context) SetSession(id string, value interface{}) (err error)
- func (c *Context) SetSessionManagement(s session.Session)
- func (c *Context) SetValidator(v func(interface{}) error)
- func (c *Context) StatusCode() int
- func (c *Context) Stream(code int, contentType string, r io.Reader) (err error)
- func (c *Context) Text(code int, format string, args ...interface{}) error
- func (c *Context) URL(name string, params ...interface{}) string
- func (c *Context) URLParam(name string) string
- func (c *Context) URLParamNames() []string
- func (c *Context) URLParamValues() []string
- func (c *Context) URLParams() map[string]string
- func (c *Context) UserAgent() string
- func (c *Context) Validate(v interface{}) error
- func (c *Context) Write(b []byte) (int, error)
- func (c *Context) WriteHeader(statusCode int)
- func (c *Context) XML(code int, v interface{}) error
- func (c *Context) XMLBlob(code int, b []byte) (err error)
- func (c *Context) XMLPretty(code int, v interface{}, indent string) error
- type HTTPClientError
- type HTTPError
- type HTTPServerError
- type Handler
- type Logger
- type Middleware
- type OnceRunner
- type RegexpHostRouter
- type Response
- func (r *Response) Flush()
- func (r *Response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error)
- func (r *Response) Push(target string, opts *http.PushOptions) error
- func (r *Response) Reset(w http.ResponseWriter)
- func (r *Response) SetWriter(w http.ResponseWriter)
- func (r *Response) Write(b []byte) (n int, err error)
- func (r *Response) WriteHeader(code int)
- func (r *Response) WriteString(s string) (n int, err error)
- type Route
- func (r *Route) Any(handler Handler) *Route
- func (r *Route) CONNECT(handler Handler) *Route
- func (r *Route) Clone() *Route
- func (r *Route) CtxData(data interface{}) *Route
- func (r *Route) DELETE(handler Handler) *Route
- func (r *Route) GET(handler Handler) *Route
- func (r *Route) Group() *RouteGroup
- func (r *Route) HEAD(handler Handler) *Route
- func (r *Route) HasHeader(headerK string, headerV ...string) *Route
- func (r *Route) Host(host string) *Route
- func (r *Route) Map(method2handlers map[string]Handler) *Route
- func (r *Route) MapType(tv interface{}) *Route
- func (r *Route) Method(handler Handler, methods ...string) *Route
- func (r *Route) Name(name string) *Route
- func (r *Route) New() *Route
- func (r *Route) NoMiddlewares() *Route
- func (r *Route) OPTIONS(handler Handler) *Route
- func (r *Route) PATCH(handler Handler) *Route
- func (r *Route) POST(handler Handler) *Route
- func (r *Route) PUT(handler Handler) *Route
- func (r *Route) Redirect(code int, toURL string, method ...string) *Route
- func (r *Route) Remove(method string) *Route
- func (r *Route) RemoveAny() *Route
- func (r *Route) RemoveCONNECT() *Route
- func (r *Route) RemoveDELETE() *Route
- func (r *Route) RemoveGET() *Route
- func (r *Route) RemoveHEAD() *Route
- func (r *Route) RemoveOPTIONS() *Route
- func (r *Route) RemovePATCH() *Route
- func (r *Route) RemovePOST() *Route
- func (r *Route) RemovePUT() *Route
- func (r *Route) RemoveTRACE() *Route
- func (r *Route) RouteInfo(handler Handler, methods ...string) []RouteInfo
- func (r *Route) Ship() *Ship
- func (r *Route) Static(dirpath string) *Route
- func (r *Route) StaticFS(fs http.FileSystem) *Route
- func (r *Route) StaticFile(filePath string) *Route
- func (r *Route) TRACE(handler Handler) *Route
- func (r *Route) Use(middlewares ...Middleware) *Route
- type RouteError
- type RouteGroup
- func (g *RouteGroup) AddRoutes(ris ...RouteInfo) *RouteGroup
- func (g *RouteGroup) Clone() *RouteGroup
- func (g *RouteGroup) CtxData(data interface{}) *RouteGroup
- func (g *RouteGroup) DelRoutes(ris ...RouteInfo) *RouteGroup
- func (g *RouteGroup) Group(prefix string, middlewares ...Middleware) *RouteGroup
- func (g *RouteGroup) Host(host string) *RouteGroup
- func (g *RouteGroup) NoMiddlewares() *RouteGroup
- func (g *RouteGroup) R(path string) *Route
- func (g *RouteGroup) Route(path string) *Route
- func (g *RouteGroup) Ship() *Ship
- func (g *RouteGroup) Use(middlewares ...Middleware) *RouteGroup
- type RouteInfo
- type Runner
- type Ship
- func (s *Ship) AcquireBuffer() *bytes.Buffer
- func (s *Ship) AcquireContext(r *http.Request, w http.ResponseWriter) *Context
- func (s *Ship) AddHost(host string, r router.Router) (router.Router, error)
- func (s *Ship) AddRoute(ri RouteInfo) (err error)
- func (s *Ship) AddRoutes(ris ...RouteInfo)
- func (s *Ship) Clone() *Ship
- func (s *Ship) DelHost(host string)
- func (s *Ship) DelRoute(ri RouteInfo) (err error)
- func (s *Ship) DelRoutes(ris ...RouteInfo)
- func (s *Ship) GetDefaultRouter() (host string, router router.Router)
- func (s *Ship) Group(prefix string) *RouteGroup
- func (s *Ship) Host(host string) *RouteGroup
- func (s *Ship) NewContext() *Context
- func (s *Ship) Pre(middlewares ...Middleware) *Ship
- func (s *Ship) R(path string) *Route
- func (s *Ship) ReleaseBuffer(buf *bytes.Buffer)
- func (s *Ship) ReleaseContext(c *Context)
- func (s *Ship) ResetMiddlewares(mdws ...Middleware) *Ship
- func (s *Ship) ResetPreMiddlewares(mdws ...Middleware) *Ship
- func (s *Ship) Route(path string) *Route
- func (s *Ship) Router(host string) (r router.Router)
- func (s *Ship) Routers() (routers map[string]router.Router)
- func (s *Ship) Routes() (routes []RouteInfo)
- func (s *Ship) ServeHTTP(resp http.ResponseWriter, req *http.Request)
- func (s *Ship) SetBufferSize(size int) *Ship
- func (s *Ship) SetDefaultRouter(host string, router router.Router)
- func (s *Ship) SetLogger(logger Logger) *Ship
- func (s *Ship) SetNewRegexpHostRouter(f func() RegexpHostRouter) *Ship
- func (s *Ship) SetNewRouter(f func() router.Router) *Ship
- func (s *Ship) URLParamsMaxNum() int
- func (s *Ship) Use(middlewares ...Middleware) *Ship
Examples ¶
Constants ¶
const ( CharsetUTF8 = "charset=UTF-8" PROPFIND = "PROPFIND" )
Predefine some variables
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 ( HeaderAccept = "Accept" HeaderAcceptedLanguage = "Accept-Language" HeaderAcceptEncoding = "Accept-Encoding" HeaderAllow = "Allow" HeaderAuthorization = "Authorization" HeaderConnection = "Connection" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLength = "Content-Length" HeaderContentType = "Content-Type" HeaderCookie = "Cookie" HeaderSetCookie = "Set-Cookie" HeaderIfModifiedSince = "If-Modified-Since" HeaderLastModified = "Last-Modified" HeaderEtag = "Etag" 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" HeaderXServerID = "X-Server-Id" HeaderXRequestID = "X-Request-Id" HeaderXRequestedWith = "X-Requested-With" HeaderServer = "Server" HeaderOrigin = "Origin" HeaderReferer = "Referer" HeaderUserAgent = "User-Agent" // 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" HeaderXCSRFToken = "X-CSRF-Token" )
Headers
Variables ¶
var ( MIMEApplicationJSONs = []string{MIMEApplicationJSON} MIMEApplicationJSONCharsetUTF8s = []string{MIMEApplicationJSONCharsetUTF8} MIMEApplicationJavaScripts = []string{MIMEApplicationJavaScript} MIMEApplicationJavaScriptCharsetUTF8s = []string{MIMEApplicationJavaScriptCharsetUTF8} MIMEApplicationXMLs = []string{MIMEApplicationXML} MIMEApplicationXMLCharsetUTF8s = []string{MIMEApplicationXMLCharsetUTF8} MIMETextXMLs = []string{MIMETextXML} MIMETextXMLCharsetUTF8s = []string{MIMETextXMLCharsetUTF8} MIMEApplicationForms = []string{MIMEApplicationForm} MIMEApplicationProtobufs = []string{MIMEApplicationProtobuf} MIMEApplicationMsgpacks = []string{MIMEApplicationMsgpack} MIMETextHTMLs = []string{MIMETextHTML} MIMETextHTMLCharsetUTF8s = []string{MIMETextHTMLCharsetUTF8} MIMETextPlains = []string{MIMETextPlain} MIMETextPlainCharsetUTF8s = []string{MIMETextPlainCharsetUTF8} MIMEMultipartForms = []string{MIMEMultipartForm} MIMEOctetStreams = []string{MIMEOctetStream} )
MIME slice types
var ( // Some non-HTTP errors ErrMissingContentType = herror.ErrMissingContentType ErrRendererNotRegistered = herror.ErrRendererNotRegistered ErrInvalidRedirectCode = herror.ErrInvalidRedirectCode ErrInvalidSession = herror.ErrInvalidSession ErrSessionNotExist = herror.ErrSessionNotExist ErrNoSessionSupport = herror.ErrNoSessionSupport ErrNoResponder = herror.ErrNoResponder // Some HTTP error. ErrBadRequest = herror.ErrBadRequest ErrForbidden = herror.ErrForbidden ErrNotFound = herror.ErrNotFound ErrMethodNotAllowed = herror.ErrMethodNotAllowed ErrStatusNotAcceptable = herror.ErrStatusNotAcceptable ErrRequestTimeout = herror.ErrRequestTimeout ErrStatusConflict = herror.ErrStatusConflict ErrStatusGone = herror.ErrStatusGone ErrStatusRequestEntityTooLarge = herror.ErrStatusRequestEntityTooLarge ErrUnsupportedMediaType = herror.ErrUnsupportedMediaType ErrTooManyRequests = herror.ErrTooManyRequests ErrInternalServerError = herror.ErrInternalServerError ErrStatusNotImplemented = herror.ErrStatusNotImplemented ErrBadGateway = herror.ErrBadGateway ErrStatusGatewayTimeout = herror.ErrStatusGatewayTimeout ErrStatusHTTPVersionNotSupported = herror.ErrStatusHTTPVersionNotSupported // ErrSkip is not an error, which is used to suggest that the middeware // should skip and return it back to the outer middleware to handle. ErrSkip = herror.ErrSkip )
Re-export some errors.
var DefaultMethodMapping = map[string]string{
"Create": "POST",
"Delete": "DELETE",
"Update": "PUT",
"Get": "GET",
}
DefaultMethodMapping is the default method mapping of the route.
var DefaultShip = Default()
DefaultShip is the default global ship.
var DefaultSignals = []os.Signal{ os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGABRT, syscall.SIGINT, }
DefaultSignals is a set of default signals.
var MaxMemoryLimit int64 = 32 << 20 // 32MB
MaxMemoryLimit is the maximum memory.
var NewHTTPError = NewHTTPServerError
NewHTTPError is the alias of herror.NewHTTPServerError.
DEPRECATED!!! Please use NewHTTPServerError instead.
var NewHTTPServerError = herror.NewHTTPServerError
NewHTTPServerError is the alias of herror.NewHTTPServerError.
Functions ¶
func AddContentTypeToSlice ¶
AddContentTypeToSlice add a rule to convert contentType to contentTypeSlice. So you can call SetContentType to set the Content-Type to contentTypeSlice by contentType to avoid to allocate the memory.
func CopyNBuffer ¶
CopyNBuffer is the same as io.CopyN, but uses the given buf as the buffer.
If buf is nil or empty, it will make a new one with 2048.
func DeleteJSON ¶ added in v3.5.0
DeleteJSON is equal to RequestJSON(http.MethodDelete, url, req, resp...).
func DisalbeRedirect ¶
DisalbeRedirect is used to disalbe the default redirect behavior of http.Client, that's, http.Client won't handle the redirect response and just return it to the caller.
func NewRequestWithContext ¶ added in v3.5.0
func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*http.Request, error)
NewRequestWithContext is the compatibility of http.NewRequestWithContext.
func PostJSON ¶ added in v3.5.0
PostJSON is equal to RequestJSON(http.MethodPost, url, req, resp...).
func PutResponseIntoPool ¶
func PutResponseIntoPool(r *Response)
PutResponseIntoPool puts a Response into the pool.
func RequestJSON ¶ added in v3.5.0
RequestJSON is equal to RequestJSONWithContext(context.Background(), ...).
func RequestJSONWithContext ¶ added in v3.5.0
func RequestJSONWithContext(ctx context.Context, method, url string, reqBody interface{}, respBody ...interface{}) (err error)
RequestJSONWithContext is equal to RequestJSONWithContextAndHeaders(ctx, method, url, nil, reqBody, respBody...).
func RequestJSONWithContextAndHeaders ¶ added in v3.8.0
func RequestJSONWithContextAndHeaders(ctx context.Context, method, url string, reqHeaders http.Header, reqBody interface{}, respBody ...interface{}) (err error)
RequestJSONWithContextAndHeaders sends the http request with JSON and puts the response body into respBody as JSON.
reqBody may be one of types: nil, []byte, string, io.Reader, and otehr types. For other types, it will be serialized by json.NewEncoder.
If respBody is nil, it will ignore the response body.
If respBody[1] is a function and its type is func(*http.Request)*http.Request, it will call it to fix the new request and use the returned request.
func SetContentType ¶
func SetContentType(res http.ResponseWriter, ct string)
SetContentType is equal to SetHeaderContentType(res.Header(), ct).
func SetHeaderContentType ¶
SetHeaderContentType sets the Content-Type header to ct.
func SetStructFieldToDefault ¶ added in v3.2.0
func SetStructFieldToDefault(v interface{}) (err error)
SetStructFieldToDefault sets the default value of the fields of the struct v to the value of the tag "default" of the fields when the field value is ZERO.
If v is not a struct, it does nothing; and not a pointer to struct, panic.
For the type of the field, it only supports some base types as follow:
string float32 float64 int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 struct struct slice interface{ SetDefault(_default interface{}) error }
Notice: If the tag value starts with ".", it represents a field name and the default value of current field is set to the value of that field. But their types must be consistent, or panic.
Example ¶
type Struct struct { InnerInt int `default:"123"` _ int `default:"-"` } type S struct { Ignore bool `default:"true"` Int int `default:"123"` Int8 int8 `default:"123"` Int16 int16 `default:"123"` Int32 int32 `default:"123"` Int64 int64 `default:"123"` Uint uint `default:"123"` Uint8 uint8 `default:"123"` Uint16 uint16 `default:"123"` Uint32 uint32 `default:"123"` Uint64 uint64 `default:"123"` Uintptr uintptr `default:"123"` Float32 float32 `default:"1.2"` Float64 float64 `default:"1.2"` FloatN float64 `default:".Float64"` // Set the default value to other field String string `default:"abc"` Struct Struct Structs []Struct _ int `default:"-"` } s := S{Structs: make([]Struct, 2)} err := SetStructFieldToDefault(&s) fmt.Println(err) fmt.Println(s.Ignore) fmt.Println(s.Int) fmt.Println(s.Int8) fmt.Println(s.Int16) fmt.Println(s.Int32) fmt.Println(s.Int64) fmt.Println(s.Uint) fmt.Println(s.Uint8) fmt.Println(s.Uint16) fmt.Println(s.Uint32) fmt.Println(s.Uint64) fmt.Println(s.Uintptr) fmt.Println(s.Float32) fmt.Println(s.Float64) fmt.Println(s.FloatN) fmt.Println(s.String) fmt.Println(s.Struct.InnerInt) fmt.Println(s.Structs[0].InnerInt) fmt.Println(s.Structs[1].InnerInt)
Output: <nil> false 123 123 123 123 123 123 123 123 123 123 123 1.2 1.2 1.2 abc 123 123 123
Types ¶
type BufferAllocator ¶
BufferAllocator is used to acquire and release a buffer.
type Context ¶
type Context struct { // RouteInfo is the route information associated with the route. RouteInfo RouteInfo // RouteCtxData is the context data associated with the route. // // DEPRECATED!!! Please use RouteInfo.CtxData instead. RouteCtxData interface{} // Data is used to store many key-value pairs about the context. // // Data maybe asks the system to allocate many memories. // If the interim context value is too few and you don't want the system // to allocate many memories, the three context variables is for you // and you can consider them as the context register to use. // // Notice: when the new request is coming, they will be reset to nil. Key1 interface{} Key2 interface{} Key3 interface{} Data map[string]interface{} // contains filtered or unexported fields }
Context represetns a request and response context.
func NewContext ¶
NewContext returns a new Context.
func (*Context) Accept ¶
Accept returns the content of the header Accept.
If there is no the header Accept , it return nil.
Notice:
- It will sort the content by the q-factor weighting.
- If the value is "<MIME_type>/*", it will be amended as "<MIME_type>/". So you can use it to match the prefix.
- If the value is "*/*", it will be amended as "".
func (*Context) AcquireBuffer ¶
AcquireBuffer acquires a buffer.
Notice: you should call ReleaseBuffer() to release it.
func (*Context) Attachment ¶
Attachment sends a response as attachment, prompting client to save the file.
If the file does not exist, it returns ErrNotFound.
func (*Context) Bind ¶
Bind binds the request information into the provided value v.
The default binder does it based on Content-Type header.
Notice: it will call the interfaces or functions in turn as follow:
- Binder
- SetDefault
- Validator
func (*Context) BindQuery ¶
BindQuery binds the request URL query into the provided value v.
Notice: it will call the interfaces or functions in turn as follow:
- QueryBinder
- SetDefault
- Validator
func (*Context) BlobText ¶
func (c *Context) BlobText(code int, contentType string, format string, args ...interface{}) (err error)
BlobText sends a string blob response with status code and content type.
func (*Context) Body ¶
func (c *Context) Body() io.ReadCloser
Body returns the reader of the request body.
func (*Context) Charset ¶
Charset returns the charset of the request content.
Return "" if there is no charset.
func (*Context) ClientIP ¶ added in v3.12.0
ClientIP returns the real client's network address based on `X-Forwarded-For` or `X-Real-IP` request header. Or returns the remote address.
func (*Context) ContentLength ¶
ContentLength return the length of the request body.
func (*Context) ContentType ¶
ContentType returns the Content-Type of the request without the charset.
func (*Context) Cookie ¶
Cookie returns the named cookie provided in the request.
Return nil if no the cookie named name.
func (*Context) DelSession ¶
DelSession deletes the session from the backend store.
func (*Context) Error ¶
func (c *Context) Error(code int, err error) HTTPServerError
Error sends an error response with status code.
func (*Context) Execute ¶
Execute finds the route and calls the handler.
SetRouter must be called before calling Execute, which be done by the framework.
func (*Context) File ¶
File sends a response with the content of the file.
If the file does not exist, it returns ErrNotFound.
If not set the Content-Type, it will deduce it from the extension of the file name.
func (*Context) FindRoute ¶ added in v3.9.0
FindRoute finds the route from the router and returns the route info.
func (*Context) FormParams ¶
FormParams returns the form parameters as `url.Values`.
func (*Context) GetBodyReader ¶
GetBodyReader reads all the contents from the body to buffer and returns it.
Notice: You should call ReleaseBuffer(buf) to release the buffer at last.
func (*Context) GetHeader ¶
GetHeader returns the first value of the request header named name.
Return "" if the header does not exist.
func (*Context) GetSession ¶
GetSession returns the session content by id from the backend store.
If the session id does not exist, it returns ErrSessionNotExist.
func (*Context) HasHeader ¶ added in v3.7.0
HasHeader reports whether the request header named name exists or not.
func (*Context) HasQuery ¶ added in v3.7.0
HasQuery reports whether the query argument named name exists or not.
func (*Context) Inline ¶
Inline sends a response as inline, opening the file in the browser.
If the file does not exist, it returns ErrNotFound.
func (*Context) IsResponded ¶
IsResponded reports whether the response is sent.
func (*Context) IsWebSocket ¶
IsWebSocket reports whether HTTP connection is WebSocket or not.
func (*Context) JSONP ¶
JSONP sends a JSONP response with status code. It uses `callback` to construct the JSONP payload.
func (*Context) JSONPBlob ¶
JSONPBlob sends a JSONP blob response with status code. It uses `callback` to construct the JSONP payload.
func (*Context) JSONPretty ¶
JSONPretty sends a pretty-print JSON with status code.
func (*Context) MultipartForm ¶
MultipartForm returns the multipart form.
func (*Context) MultipartReader ¶
MultipartReader returns the multipart reader from the request.
func (*Context) NotFoundHandler ¶
NotFoundHandler returns the NotFound Handler, but returns nil instead if not set.
func (*Context) QueryParam ¶
QueryParam returns the query param for the provided name.
func (*Context) QueryParams ¶
QueryParams returns the query parameters as `url.Values`.
func (*Context) QueryRawString ¶
QueryRawString returns the URL query string.
func (*Context) ReleaseBuffer ¶
ReleaseBuffer releases a buffer into the pool.
func (*Context) RemoteAddr ¶
RemoteAddr returns the remote address of the http connection.
func (*Context) Render ¶
Render renders a template named name with data and sends a text/html response with status code.
func (*Context) RequestURI ¶
RequestURI returns the URI of the request.
func (*Context) Reset ¶
func (c *Context) Reset()
Reset resets the context to the initalizing state.
func (*Context) RespHeader ¶
RespHeader returns the header of the response.
func (*Context) Respond ¶
Respond calls the context handler set by SetHandler.
Return ErrNoResponder if the context handler or the global handler is not set.
func (*Context) ResponseWriter ¶
func (c *Context) ResponseWriter() http.ResponseWriter
ResponseWriter returns the underlying http.ResponseWriter.
func (*Context) SetBinder ¶
SetBinder sets the binder to b to bind the request information to an object.
func (*Context) SetBufferAllocator ¶
func (c *Context) SetBufferAllocator(alloc BufferAllocator)
SetBufferAllocator sets the buffer allocator to alloc.
func (*Context) SetConnectionClose ¶
func (c *Context) SetConnectionClose()
SetConnectionClose tell the server to close the connection.
func (*Context) SetContentType ¶
SetContentType sets the Content-Type header of the response body to ct, but does nothing if contentType is "".
func (*Context) SetDefault ¶ added in v3.2.0
SetDefault calls the default setter to set the default value of v.
func (*Context) SetDefaulter ¶ added in v3.2.0
SetDefaulter sets the default setter to v set the default value.
func (*Context) SetNotFoundHandler ¶
SetNotFoundHandler sets the NotFound handler.
func (*Context) SetQueryBinder ¶
SetQueryBinder sets the query binder to f to bind the url query to an object.
func (*Context) SetRenderer ¶
SetRenderer sets the renderer to r to render the response to the peer.
func (*Context) SetReqRes ¶
func (c *Context) SetReqRes(r *http.Request, w http.ResponseWriter)
SetReqRes is the same as Reset, but only reset the request and response, not all things.
func (*Context) SetRequest ¶
SetRequest resets the request to req.
func (*Context) SetResponder ¶
SetResponder sets the responder to handle the complicated response.
For example,
responder := func(ctx *Context, args ...interface{}) error { switch len(args) { case 0: return ctx.NoContent(http.StatusOK) case 1: switch v := args[0].(type) { case int: return ctx.NoContent(v) case string: return ctx.Text(http.StatusOK, v) } case 2: switch v0 := args[0].(type) { case int: return ctx.Text(v0, "%v", args[1]) } } return ctx.NoContent(http.StatusInternalServerError) } router := New() router.Responder =responder router.Route("/path1").GET(func(c *Context) error { return c.Handle() }) router.Route("/path2").GET(func(c *Context) error { return c.Handle(200) }) router.Route("/path3").GET(func(c *Context) error { return c.Handle("Hello, World") }) router.Route("/path4").GET(func(c *Context) error { return c.Handle(200, "Hello, World") })
func (*Context) SetResponse ¶
func (c *Context) SetResponse(res http.ResponseWriter)
SetResponse resets the response to resp, which will ignore nil.
func (*Context) SetSession ¶
SetSession sets the session to the backend store.
func (*Context) SetSessionManagement ¶
SetSessionManagement sets the session management to s.
func (*Context) SetValidator ¶ added in v3.2.0
SetValidator sets the validator to v to validate the argument when Binding.
func (*Context) StatusCode ¶
StatusCode returns the status code of the response.
func (*Context) URL ¶
URL generates an URL by route name and provided parameters.
Return "" if there is no the route named name.
func (*Context) URLParamNames ¶
URLParamNames returns the names of all the URL parameters.
func (*Context) URLParamValues ¶
URLParamValues returns the values of all the URL parameters.
func (*Context) URLParams ¶
URLParams returns all the parameters as the key-value map in the url path.
func (*Context) Write ¶
Write writes the content to the peer.
it will write the header firstly with 200 if the header is not sent.
func (*Context) WriteHeader ¶
WriteHeader sends an HTTP response header with the provided status code.
type HTTPClientError ¶ added in v3.5.0
type HTTPClientError struct { Code int `json:"code" xml:"code"` Method string `json:"method" xml:"method"` URL string `json:"url" xml:"url"` Data string `json:"data" xml:"data"` Err error `json:"err" xml:"err"` }
HTTPClientError represents an error about the http client response.
func NewHTTPClientError ¶ added in v3.5.0
func NewHTTPClientError(method, url string, code int, err error, data ...string) HTTPClientError
NewHTTPClientError returns a new HTTPClientError.
func (HTTPClientError) Error ¶ added in v3.5.0
func (e HTTPClientError) Error() string
func (HTTPClientError) String ¶ added in v3.5.0
func (e HTTPClientError) String() string
func (HTTPClientError) Unwrap ¶ added in v3.5.0
func (e HTTPClientError) Unwrap() error
type HTTPError ¶
type HTTPError = HTTPServerError
HTTPError is the alias of herror.HTTPServerError.
DEPRECATED!!! Please use HTTPServerError instead.
type HTTPServerError ¶ added in v3.5.0
type HTTPServerError = herror.HTTPServerError
HTTPServerError is the alias of herror.HTTPServerError.
type Handler ¶
Handler is a handler of the HTTP request.
func FromHTTPHandler ¶
FromHTTPHandler converts http.Handler to Handler.
func FromHTTPHandlerFunc ¶
func FromHTTPHandlerFunc(h http.HandlerFunc) Handler
FromHTTPHandlerFunc converts http.HandlerFunc to Handler.
func MethodNotAllowedHandler ¶
func MethodNotAllowedHandler() Handler
MethodNotAllowedHandler returns a MethodNotAllowed handler.
type Logger ¶
type Logger interface { Tracef(format string, args ...interface{}) Debugf(format string, args ...interface{}) Infof(format string, args ...interface{}) Warnf(format string, args ...interface{}) Errorf(format string, args ...interface{}) }
Logger is logger interface.
Notice: The implementation maybe also has the method { Writer() io.Writer } to get the underlynig writer.
func NewLoggerFromStdlog ¶
NewLoggerFromStdlog converts stdlib log to Logger.
Notice: the returned logger has also implemented the interface { Writer() io.Writer }.
type OnceRunner ¶
type OnceRunner struct {
// contains filtered or unexported fields
}
OnceRunner is used to run the task only once, which is different from sync.Once, the second calling does not wait until the first calling finishes.
func NewOnceRunner ¶
func NewOnceRunner(task func()) *OnceRunner
NewOnceRunner returns a new OnceRunner.
type RegexpHostRouter ¶ added in v3.11.0
type RegexpHostRouter interface { // Len returns the number of the regexp host routers. Len() int // Each is used to traverse all the regexp host routers. Each(func(regexpHost string, router router.Router)) // Add adds and returns the regexp host router. // // If the regexp host has been added, do nothing and return the added router. Add(regexpHost string, router router.Router) (router.Router, error) // Del deletes and returns the regexp host router. // // If the regexp host router does not exist, return nil. Del(regexpHost string) router.Router // Router accurately returns the router by the regexp host. // // If the regexp host router does not exist, return nil. Router(regexpHost string) router.Router // Match matches the host and returns the corresponding router information. // // If there is no regexp host router to match it, return ("", nil). Match(host string) (matchedRegexpHost string, matchedRouter router.Router) }
RegexpHostRouter is the manager to match the host by the regular expression.
func NewRegexpHostRouter ¶ added in v3.11.0
func NewRegexpHostRouter() RegexpHostRouter
NewRegexpHostRouter returns a new RegexpHostRouter, which uses the stdlib "regexp" to implement the regular expression syntax of Golang, but you can customize it to implement yourself regular expression syntax.
For the golang regexp syntax, see https://pkg.go.dev/regexp/syntax.
type Response ¶
type Response struct { http.ResponseWriter Size int64 Wrote bool Status int }
Response implements http.ResponseWriter.
func GetResponseFromPool ¶
func GetResponseFromPool(w http.ResponseWriter) *Response
GetResponseFromPool returns a Response from the pool.
func NewResponse ¶
func NewResponse(w http.ResponseWriter) *Response
NewResponse returns a new instance of Response.
func (*Response) Flush ¶
func (r *Response) Flush()
Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client.
func (*Response) Hijack ¶
Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection.
See http.Hijacker(https://golang.org/pkg/net/http/#Hijacker)
func (*Response) Push ¶
func (r *Response) Push(target string, opts *http.PushOptions) error
Push implements the http.Pusher interface to support HTTP/2 server push.
func (*Response) Reset ¶
func (r *Response) Reset(w http.ResponseWriter)
Reset resets the response to the initialized and returns itself.
func (*Response) SetWriter ¶
func (r *Response) SetWriter(w http.ResponseWriter)
SetWriter resets the writer to w and return itself.
func (*Response) WriteHeader ¶
WriteHeader implements http.ResponseWriter#WriteHeader().
type Route ¶
type Route struct {
// contains filtered or unexported fields
}
Route represents a route information.
func (*Route) Any ¶
Any registers all the supported methods , which is short for r.Method(handler, "")
func (*Route) Group ¶
func (r *Route) Group() *RouteGroup
Group returns the group that the current route belongs to.
Notice: it will return nil if the route is from ship.Route.
func (*Route) HasHeader ¶
HasHeader checks whether the request contains the request header. If no, the request will be rejected.
If the header value is given, it will be tested to match.
Example
s := ship.New() // The request must contains the header "Content-Type: application/json". s.R("/path/to").HasHeader("Content-Type", "application/json").POST(handler)
func (*Route) Map ¶
Map registers a group of methods with handlers, which is equal to
for method, handler := range method2handlers { r.Method(handler, method) }
func (*Route) MapType ¶
MapType registers the methods of a type as the routes.
By default, mapping is Ship.Config.DefaultMethodMapping if not given.
Example
type TestType struct{} func (t TestType) Create(ctx *ship.Context) error { return nil } func (t TestType) Delete(ctx *ship.Context) error { return nil } func (t TestType) Update(ctx *ship.Context) error { return nil } func (t TestType) Get(ctx *ship.Context) error { return nil } func (t TestType) Has(ctx *ship.Context) error { return nil } func (t TestType) NotHandler() {} router := ship.New() router.Route("/path/to").MapType(TestType{})
It's equal to the operation as follow:
router.Route("/v1/testtype/get").Name("testtype_get").GET(ts.Get) router.Route("/v1/testtype/update").Name("testtype_update").PUT(ts.Update) router.Route("/v1/testtype/create").Name("testtype_create").POST(ts.Create) router.Route("/v1/testtype/delete").Name("testtype_delete").DELETE(ts.Delete)
If you don't like the default mapping policy, you can give the customized mapping by the last argument, the key of which is the name of the method of the type, and the value of that is the request method, such as GET, POST, etc. Notice that the method type must be compatible with
func (*Context) error
Notice: the name of type and method will be converted to the lower.
func (*Route) Method ¶
Method sets the methods and registers the route.
If methods is nil, it will register all the supported methods for the route.
Notice: The method must be called at last.
func (*Route) NoMiddlewares ¶
NoMiddlewares clears all the middlewares and returns itself.
func (*Route) Remove ¶
Remove removes the route.
If the method is "", it will remove all the routes associated with the path.
func (*Route) RemoveCONNECT ¶
RemoveCONNECT is equal to r.Remove(http.MethodConnect).
func (*Route) RemoveDELETE ¶
RemoveDELETE is equal to r.Remove(http.MethodDelete).
func (*Route) RemoveHEAD ¶
RemoveHEAD is equal to r.Remove(http.MethodHead).
func (*Route) RemoveOPTIONS ¶
RemoveOPTIONS is equal to r.Remove(http.MethodOptions).
func (*Route) RemovePATCH ¶
RemovePATCH is equal to r.Remove(http.MethodPatch).
func (*Route) RemovePOST ¶
RemovePOST is equal to r.Remove(http.MethodPost).
func (*Route) RemoveTRACE ¶
RemoveTRACE is equal to r.Remove(http.MethodTrace).
func (*Route) StaticFS ¶
func (r *Route) StaticFS(fs http.FileSystem) *Route
StaticFS registers a route to serve a static filesystem.
func (*Route) StaticFile ¶
StaticFile registers a route for a static file, which supports the HEAD method to get the its length and the GET method to download it.
func (*Route) Use ¶
func (r *Route) Use(middlewares ...Middleware) *Route
Use adds some middlwares for the route.
type RouteError ¶
RouteError represents a route error when adding a route.
func (RouteError) Error ¶
func (re RouteError) Error() string
type RouteGroup ¶
type RouteGroup struct {
// contains filtered or unexported fields
}
RouteGroup is a route group, that's, it manages a set of routes.
func (*RouteGroup) AddRoutes ¶
func (g *RouteGroup) AddRoutes(ris ...RouteInfo) *RouteGroup
AddRoutes adds the routes by RouteInfo.
func (*RouteGroup) Clone ¶
func (g *RouteGroup) Clone() *RouteGroup
Clone clones itself and returns a new one.
func (*RouteGroup) CtxData ¶ added in v3.2.0
func (g *RouteGroup) CtxData(data interface{}) *RouteGroup
CtxData sets the context data on the route group.
func (*RouteGroup) DelRoutes ¶
func (g *RouteGroup) DelRoutes(ris ...RouteInfo) *RouteGroup
DelRoutes deletes the routes by RouteInfo.
func (*RouteGroup) Group ¶
func (g *RouteGroup) Group(prefix string, middlewares ...Middleware) *RouteGroup
Group returns a new sub-group.
func (*RouteGroup) Host ¶
func (g *RouteGroup) Host(host string) *RouteGroup
Host sets the host of the route group to host.
func (*RouteGroup) NoMiddlewares ¶
func (g *RouteGroup) NoMiddlewares() *RouteGroup
NoMiddlewares clears all the middlewares and returns itself.
func (*RouteGroup) Route ¶
func (g *RouteGroup) Route(path string) *Route
Route returns a new route, then you can customize and register it.
You must call Route.Method() or its short method.
func (*RouteGroup) Ship ¶
func (g *RouteGroup) Ship() *Ship
Ship returns the ship that the current group belongs to.
func (*RouteGroup) Use ¶
func (g *RouteGroup) Use(middlewares ...Middleware) *RouteGroup
Use adds some middlwares for the group and returns the origin group to write the chained router.
type RouteInfo ¶
type RouteInfo struct { // If Host is empty, it is the route of the default host router. Host string `json:"host,omitempty" xml:"host,omitempty"` Name string `json:"name,omitempty" xml:"name,omitempty"` Path string `json:"path,omitempty" xml:"path,omitempty"` Method string `json:"method,omitempty" xml:"method,omitempty"` Handler Handler `json:"-" xml:"-"` CtxData interface{} `json:"ctxdata,omitempty" xml:"ctxdata,omitempty"` }
RouteInfo is used to represent the information of the registered route.
func HTTPPprofToRouteInfo ¶
func HTTPPprofToRouteInfo() []RouteInfo
HTTPPprofToRouteInfo converts http pprof handler to RouteInfo, so that you can register them and get runtime profiling data by HTTP server.
type Runner ¶
type Runner struct { Name string Logger Logger Server *http.Server Handler http.Handler Signals []os.Signal ConnState func(net.Conn, http.ConnState) // contains filtered or unexported fields }
Runner is a HTTP Server runner.
func (*Runner) Link ¶
Link registers the shutdown function between itself and other, then returns itself.
func (*Runner) RegisterOnShutdown ¶
RegisterOnShutdown registers some functions to run when the http server is shut down.
type Ship ¶
type Ship struct { *Runner // If not nil, it will be locked and unlocked during access the routers. // So you can modify the routes concurrently and safely during running. // // Notice: if using the lock, you should also use the locked Router. // // Default: nil Lock *sync.RWMutex // The initialization capacity of Context.Data. // // Default: 0 CtxDataSize int // The maximum size of the request body. And 0 represents no limit. // // Default: 0 MaxBodySize int // The maximum number of the url paramters of the route. // // Default: 4 MaxURLParamNum int // The maximum number of the middlewares. // // Default: 256 MiddlewareMaxNum int // The prefix of the paths of all the routes. // // Default: "" Prefix string // The default handler when not finding the route. // // Default: NotFoundHandler() NotFound Handler // MethodMapping is used to map the struct method to register the routes. // // Default: DefaultMethodMapping. MethodMapping map[string]string // Filter the route when registering and unregistering it. // // Default: nil RouteFilter func(RouteInfo) bool // Modify the route before registering and unregistering it. // Default: nil RouteModifier func(RouteInfo) RouteInfo // RouteExecutor is the route executor, which is called after matching // the host and before finding the route. By default, it only calls // Context.Execute(). // // For the context, the executor can only use the field RouteInfo.Host. RouteExecutor Handler // HandleError is used to handle the error at last // if the handler or middleware returns an error. // // Default: respond the error to the client if not responding. HandleError func(c *Context, err error) // Others is used to set the context. Logger Logger // Default: NewLoggerFromWriter(os.Stderr, "") Session session.Session // Default: NewMemorySession() Binder binder.Binder // Default: nil Renderer render.Renderer // Default: nil Responder func(c *Context, args ...interface{}) error // Default: nil BindQuery func(interface{}, url.Values) error // Default: binder.BindURLValues(v, vs, "query") SetDefault func(v interface{}) error // Default: SetStructFieldToDefault Validator func(v interface{}) error // Default: nil // contains filtered or unexported fields }
Ship is an app to be used to manage the router.
func Default ¶
func Default() *Ship
Default returns a new ship with MuxBinder and MuxRenderer as the binder and renderer.
func (*Ship) AcquireBuffer ¶
AcquireBuffer gets a Buffer from the pool.
func (*Ship) AcquireContext ¶
AcquireContext gets a Context from the pool.
func (*Ship) AddHost ¶ added in v3.1.0
AddHost adds and returns the new host router.
If existed, return it and do nothing. If router is nil, new one firstly.
func (*Ship) AddRoute ¶
AddRoute registers the route.
Only "Path", "Method" and "Handler" are mandatory, and others are optional.
func (*Ship) Clone ¶
Clone clones itself to a new one without routes, middlewares and the server. Meanwhile, it will reset the signals of the new Ship to nil.
func (*Ship) DelRoute ¶
DelRoute deletes the registered route, which only needs "Host", "Name", "Path" and "Method", and others are ignored.
If Name is not empty, lookup the path by it instead of Path. If Method is empty, deletes all the routes associated with the path.
func (*Ship) GetDefaultRouter ¶ added in v3.12.0
GetDefaultRouter returns the default host domain and router.
For the default default router, the host is "".
func (*Ship) Host ¶
func (s *Ship) Host(host string) *RouteGroup
Host returns a new sub-group with the virtual host.
func (*Ship) Pre ¶
func (s *Ship) Pre(middlewares ...Middleware) *Ship
Pre registers the Pre-middlewares, which are executed before finding the route. then returns the origin ship router to write the chained router.
func (*Ship) ReleaseBuffer ¶
ReleaseBuffer puts a Buffer into the pool.
func (*Ship) ReleaseContext ¶
ReleaseContext puts a Context into the pool.
func (*Ship) ResetMiddlewares ¶ added in v3.4.0
func (s *Ship) ResetMiddlewares(mdws ...Middleware) *Ship
ResetMiddlewares resets the global middlewares to mdws.
func (*Ship) ResetPreMiddlewares ¶ added in v3.4.0
func (s *Ship) ResetPreMiddlewares(mdws ...Middleware) *Ship
ResetPreMiddlewares resets the global pre-middlewares to mdws.
func (*Ship) Route ¶
Route returns a new route, then you can customize and register it.
You must call Route.Method() or its short method.
func (*Ship) Router ¶
Router returns the Router implementation by the host name.
If host is empty, return the default router.
func (*Ship) ServeHTTP ¶
func (s *Ship) ServeHTTP(resp http.ResponseWriter, req *http.Request)
ServeHTTP implements the interface http.Handler.
func (*Ship) SetBufferSize ¶
SetBufferSize resets the size of the buffer.
func (*Ship) SetDefaultRouter ¶ added in v3.12.0
SetDefaultRouter resets the default router with the host domain.
If no host router matches the request host, use the default router to find the route handler to handle the request.
func (*Ship) SetNewRegexpHostRouter ¶ added in v3.11.0
func (s *Ship) SetNewRegexpHostRouter(f func() RegexpHostRouter) *Ship
SetNewRegexpHostRouter is used to customize RegexpHostRouter.
func (*Ship) SetNewRouter ¶
SetNewRouter resets the NewRouter to create the new router.
It must be called before adding any route.
func (*Ship) URLParamsMaxNum ¶
URLParamsMaxNum reports the maximum number of the parameters of all the URLs.
Notice: it should be only called after adding all the urls.
DEPRECATED!!! Please use MaxURLParamNum instead.
func (*Ship) Use ¶
func (s *Ship) Use(middlewares ...Middleware) *Ship
Use registers the global middlewares and returns the origin ship router to write the chained router.
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
Package herror is deprecated!
|
Package herror is deprecated! |
Package middleware is the collection of the middlewares.
|
Package middleware is the collection of the middlewares. |
Package router supplies a router interface ane some implementations.
|
Package router supplies a router interface ane some implementations. |
echo
Package echo supplies a customized Router implementation by referring to github.com/labstack/echo.
|
Package echo supplies a customized Router implementation by referring to github.com/labstack/echo. |
general
Package general supplies a general Router implementation based on Radix Tree.
|
Package general supplies a general Router implementation based on Radix Tree. |