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 PutResponseIntoPool(r *Response)
- func ReadNWriter(w io.Writer, r io.Reader, n int64) (err error)
- func SetContentType(res http.ResponseWriter, ct string)
- func SetHeaderContentType(header http.Header, ct string)
- 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{}) error
- func (c *Context) BindQuery(v interface{}) 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) 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) HTTPError
- func (c *Context) Execute(notFound Handler) error
- func (c *Context) File(file string) (err error)
- func (c *Context) FormFile(name string) (multipart.File, *multipart.FileHeader, error)
- func (c *Context) FormParams() (url.Values, error)
- func (c *Context) FormValue(name string) string
- func (c *Context) GetBody() (string, error)
- func (c *Context) GetBodyReader() (buf *bytes.Buffer, err error)
- func (c *Context) GetHeader(name 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) 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) 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) SetGetURL(getURL func(name string, params ...interface{}) string)
- 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) 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) 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 HTTPError
- type Handler
- type Logger
- type Middleware
- type OnceRunner
- 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) 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) 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 RouteFilter
- type RouteGroup
- func (g *RouteGroup) AddRoutes(ris ...RouteInfo)
- 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 RouteModifier
- type Runner
- type Ship
- func (s *Ship) AcquireBuffer() *bytes.Buffer
- func (s *Ship) AcquireContext(r *http.Request, w http.ResponseWriter) *Context
- func (s *Ship) AddRoute(ri RouteInfo)
- func (s *Ship) AddRoutes(ris ...RouteInfo)
- func (s *Ship) Clone() *Ship
- 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) Route(path string) *Route
- func (s *Ship) Routers() map[string]router.Router
- func (s *Ship) Routes() []RouteInfo
- func (s *Ship) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Ship) SetBufferSize(size int) *Ship
- func (s *Ship) SetLogger(logger Logger) *Ship
- func (s *Ship) SetNewRouter(f func() router.Router) *Ship
- func (s *Ship) URL(name string, params ...interface{}) string
- func (s *Ship) URLParamsMaxNum() int
- func (s *Ship) Use(middlewares ...Middleware) *Ship
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" 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 AllMethods = []string{ http.MethodConnect, http.MethodHead, http.MethodOptions, http.MethodTrace, http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch, }
AllMethods represents all HTTP methods.
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 = herror.NewHTTPError
NewHTTPError is the alias of herror.NewHTTPError.
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 PutResponseIntoPool ¶
func PutResponseIntoPool(r *Response)
PutResponseIntoPool puts a Response into the pool.
func ReadNWriter ¶
ReadNWriter reads n bytes to the writer w from the reader r.
It will return io.EOF if the length of the data from r is less than n. But the data has been read into w.
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.
Types ¶
type BufferAllocator ¶
BufferAllocator is used to acquire and release a buffer.
type Context ¶
type Context struct { // 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.
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) 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) 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) 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) 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) RealIP ¶
RealIP returns the client's network address based on `X-Forwarded-For` or `X-Real-IP` request header.
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) RenderOk ¶ added in v2.5.0
RenderOk is short for c.Render(name, http.StatusOK, data).
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) 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) 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 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(foramt string, args ...interface{}) Infof(foramt string, args ...interface{}) Warnf(foramt string, args ...interface{}) Errorf(foramt 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 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 ¶ added in v2.1.0
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 ¶ added in v2.1.0
Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection.
func (*Response) Push ¶ added in v2.1.0
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, AllMethods...)
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) 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 RouteFilter ¶
RouteFilter is used to filter the registering route if it returns true.
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 ¶ added in v2.4.0
func (g *RouteGroup) AddRoutes(ris ...RouteInfo)
AddRoutes adds 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 { Name string `json:"name" xml:"name"` Host string `json:"host" xml:"host"` Path string `json:"path" xml:"path"` Method string `json:"method" xml:"method"` Handler Handler `json:"-" xml:"-"` Router router.Router `json:"-" xml:"-"` }
RouteInfo is used to represent the information of the registered route.
func HTTPPprofToRouteInfo ¶ added in v2.3.0
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 RouteModifier ¶
RouteModifier is used to modify the registering route.
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 /// Context CtxDataSize int // The initialization size of Context.Data. /// Route, Handler and Middleware Prefix string NotFound Handler RouteFilter RouteFilter RouteModifier RouteModifier MethodMapping map[string]string // The default is DefaultMethodMapping. MiddlewareMaxNum int // Default is 256 // Others Logger Logger Binder binder.Binder Session session.Session Renderer render.Renderer BindQuery func(interface{}, url.Values) error Responder func(c *Context, args ...interface{}) error HandleError func(c *Context, err error) // 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 default configuration, which will set Binder, Renderer and BindQuery to MuxBinder, MuxRenderer and BindURLValues based on New().
func (*Ship) AcquireBuffer ¶
AcquireBuffer gets a Buffer from the pool.
func (*Ship) AcquireContext ¶
AcquireContext gets a Context from the pool.
func (*Ship) AddRoute ¶ added in v2.3.0
AddRoute registers the route, which uses the global middlewares to wrap the handler. If you don't want to use any middleware, you can do it by
s.Group("").NoMiddlewares().AddRoutes(ri)
Notice: "Name" and "Host" are optional, "Router" will be ignored. and others are mandatory.
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) 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) Route ¶
Route returns a new route, then you can customize and register it.
You must call Route.Method() or its short method.
func (*Ship) Routers ¶
Routers returns the routers with their host.
For the main router, the host is "".
func (*Ship) ServeHTTP ¶
func (s *Ship) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the interface http.Handler.
func (*Ship) SetBufferSize ¶
SetBufferSize resets the size of the buffer.
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.
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 middleware is the collection of the middlewares.
|
Package middleware is the collection of the middlewares. |
Package router supplies some the builtin implementation about Router.
|
Package router supplies some the builtin implementation about Router. |
echo
Package echo supplies a Router implementation based on github.com/labstack/echo.
|
Package echo supplies a Router implementation based on github.com/labstack/echo. |