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 BindURLValues(ptr interface{}, data url.Values, tag string) error
- func MaxNumOfURLParams() int
- func Shutdown(ctx context.Context) error
- func ToContentTypes(contentType string) []string
- func ToHTTPHandler(s *Ship, h Handler) http.Handler
- func Traverse(f func(name string, method string, path string))
- func URL(name string, params ...interface{}) string
- func Wait()
- type BindUnmarshaler
- type Binder
- 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) BlobString(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) Context() context.Context
- func (c *Context) Cookie(name string) (*http.Cookie, error)
- func (c *Context) Cookies() []*http.Cookie
- func (c *Context) DelSession(id string) (err error)
- func (c *Context) Error(code int, err error) error
- func (c *Context) File(file string) (err error)
- func (c *Context) FindHandler(method, path string) Handler
- func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
- func (c *Context) FormFile2(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) Handle(args ...interface{}) error
- func (c *Context) Header(name string) string
- 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) IsDebug() bool
- func (c *Context) IsResponded() bool
- func (c *Context) IsTLS() bool
- func (c *Context) IsWebSocket() bool
- func (c *Context) JSON(code int, i 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, i 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) Param(name string) string
- func (c *Context) ParamNames() []string
- func (c *Context) ParamToStruct(v interface{}) error
- func (c *Context) ParamValues() []string
- func (c *Context) Params() map[string]string
- 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) ReqHeader() http.Header
- func (c *Context) Request() *http.Request
- func (c *Context) RequestURI() string
- func (c *Context) RespHeader() http.Header
- func (c *Context) Response() http.ResponseWriter
- func (c *Context) Router() Router
- func (c *Context) Scheme() (scheme string)
- func (c *Context) SetConnectionClose()
- func (c *Context) SetContentType(contentType string)
- func (c *Context) SetContentTypes(contentTypes []string)
- func (c *Context) SetCookie(cookie *http.Cookie)
- func (c *Context) SetHandler(h func(*Context, ...interface{}) error)
- func (c *Context) SetHeader(name, value string)
- func (c *Context) SetRequest(req *http.Request)
- func (c *Context) SetResponded(yes bool)
- func (c *Context) SetResponse(resp http.ResponseWriter)
- func (c *Context) SetSession(id string, value interface{}) (err error)
- func (c *Context) StatusCode() int
- func (c *Context) Stream(code int, contentType string, r io.Reader) (err error)
- func (c *Context) String(code int, format string, args ...interface{}) (err error)
- func (c *Context) URL(name string, params ...interface{}) string
- func (c *Context) UserAgent() string
- func (c *Context) Write(b []byte) (int, error)
- func (c *Context) XML(code int, i interface{}) error
- func (c *Context) XMLBlob(code int, b []byte) (err error)
- func (c *Context) XMLPretty(code int, i interface{}, indent string) error
- type Group
- func (g *Group) Group(prefix string, middlewares ...Middleware) *Group
- func (g *Group) GroupWithoutMiddleware(prefix string, middlewares ...Middleware) *Group
- func (g *Group) R(path string) *Route
- func (g *Group) Route(path string) *Route
- func (g *Group) RouteWithoutMiddleware(path string) *Route
- func (g *Group) Ship() *Ship
- func (g *Group) Use(middlewares ...Middleware) *Group
- type HTMLTemplateEngine
- type HTTPError
- type Handler
- type Logger
- type Marshaler
- type Matcher
- type Middleware
- type MuxBinder
- type MuxRenderer
- type Option
- func DisableErrorLog(disabled bool) Option
- func EnableCtxHTTPContext(enable bool) Option
- func KeepTrailingSlashPath(keep bool) Option
- func SetBindQuery(bind func(interface{}, url.Values) error) Option
- func SetBinder(b Binder) Option
- func SetBufferSize(size int) Option
- func SetCtxDataSize(size int) Option
- func SetCtxHandler(handler func(*Context, ...interface{}) error) Option
- func SetDebug(debug bool) Option
- func SetDefaultMethodMapping(m map[string]string) Option
- func SetEnableCtxHTTPContext(enable bool) Option
- func SetErrorHandler(handler func(*Context, error)) Option
- func SetKeepTrailingSlashPath(keep bool) Option
- func SetLogger(log Logger) Option
- func SetMaxMiddlewareNum(num int) Option
- func SetMethodNotAllowedHandler(h Handler) Option
- func SetName(name string) Option
- func SetNewCtxData(newCtxData func(*Context) Resetter) Option
- func SetNewRouter(newRouter func() Router) Option
- func SetNotFoundHandler(h Handler) Option
- func SetOptionsHandler(h Handler) Option
- func SetPrefix(prefix string) Option
- func SetRenderer(r Renderer) Option
- func SetRouteFilter(filter func(name, path, method string) bool) Option
- func SetRouteModifier(modifier func(name, path, method string) (string, string, string)) Option
- func SetSession(session Session) Option
- func SetSignal(sigs []os.Signal) Option
- type Renderer
- func HTMLTemplateRenderer(engine HTMLTemplateEngine) Renderer
- func JSONPrettyRenderer(indent string, marshal ...Marshaler) Renderer
- func JSONRenderer(marshal ...Marshaler) Renderer
- func RendererFunc(f func(ctx *Context, name string, code int, v interface{}) error) Renderer
- func SimpleRenderer(name string, contentType string, marshaler Marshaler) Renderer
- func XMLPrettyRenderer(indent string, marshal ...Marshaler) Renderer
- func XMLRenderer(marshal ...Marshaler) Renderer
- type Resetter
- 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() *Group
- func (r *Route) HEAD(handler Handler) *Route
- func (r *Route) HasSchemes(schemes ...string) *Route
- func (r *Route) Header(headerK string, headerV ...string) *Route
- func (r *Route) Map(method2handlers map[string]Handler) *Route
- func (r *Route) MapType(tv interface{}, mapping ...map[string]string) *Route
- func (r *Route) Match(matchers ...Matcher) *Route
- func (r *Route) MatchMiddleware(f func([]Matcher) Middleware) *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) 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 Router
- type Session
- type Ship
- func Clone(name ...string) *Ship
- func Configure(options ...Option) *Ship
- func Link(other *Ship) *Ship
- func New(options ...Option) *Ship
- func Pre(middlewares ...Middleware) *Ship
- func RegisterOnShutdown(functions ...func()) *Ship
- func SetConnStateHandler(h func(net.Conn, http.ConnState)) *Ship
- func Start(addr string, tlsFiles ...string) *Ship
- func StartServer(server *http.Server) *Ship
- func Use(middlewares ...Middleware) *Ship
- func VHost(host string) *Ship
- func (s *Ship) AcquireBuffer() *bytes.Buffer
- func (s *Ship) AcquireContext(r *http.Request, w http.ResponseWriter) *Context
- func (s *Ship) Binder() Binder
- func (s *Ship) Clone(name ...string) *Ship
- func (s *Ship) Configure(options ...Option) *Ship
- func (s *Ship) Group(prefix string, middlewares ...Middleware) *Group
- func (s *Ship) GroupWithoutMiddleware(prefix string, middlewares ...Middleware) *Group
- func (s *Ship) Link(other *Ship) *Ship
- func (s *Ship) Logger() Logger
- func (s *Ship) MaxNumOfURLParams() int
- func (s *Ship) MuxBinder() *MuxBinder
- func (s *Ship) MuxRenderer() *MuxRenderer
- func (s *Ship) NewContext(r *http.Request, w http.ResponseWriter) *Context
- func (s *Ship) Pre(middlewares ...Middleware) *Ship
- func (s *Ship) R(path string) *Route
- func (s *Ship) RegisterOnShutdown(functions ...func()) *Ship
- func (s *Ship) ReleaseBuffer(buf *bytes.Buffer)
- func (s *Ship) ReleaseContext(c *Context)
- func (s *Ship) Renderer() Renderer
- func (s *Ship) Route(path string) *Route
- func (s *Ship) RouteWithoutMiddleware(path string) *Route
- func (s *Ship) Router() Router
- func (s *Ship) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Ship) SetConnStateHandler(h func(net.Conn, http.ConnState)) *Ship
- func (s *Ship) Shutdown(ctx context.Context) error
- func (s *Ship) Start(addr string, tlsFiles ...string) *Ship
- func (s *Ship) StartServer(server *http.Server) *Ship
- func (s *Ship) Stop()
- func (s *Ship) Traverse(f func(name string, method string, path string))
- func (s *Ship) URL(name string, params ...interface{}) string
- func (s *Ship) Use(middlewares ...Middleware) *Ship
- func (s *Ship) VHost(host string) *Ship
- func (s *Ship) Wait()
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" 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 ( ErrRendererNotRegistered = errors.New("renderer not registered") ErrInvalidRedirectCode = errors.New("invalid redirect status code") ErrCookieNotFound = errors.New("cookie not found") ErrNoHandler = errors.New("no handler") ErrNoSessionSupport = errors.New("no session support") ErrInvalidSession = errors.New("invalid session") ErrSessionNotExist = errors.New("session does not exist") ErrMissingContentType = errors.New("missing the header 'Content-Type'") )
Some non-HTTP Errors
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) )
Some HTTP error.
var DefaultShip = New()
DefaultShip is the default global ship.
var ErrSkip = errors.New("skip")
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.
Notice: it is only a suggestion.
var MaxMemoryLimit int64 = 32 << 20 // 32MB
MaxMemoryLimit is the maximum memory.
Functions ¶
func AddContentTypeToSlice ¶ added in v1.0.0
AddContentTypeToSlice add a rule to convert contentType to contentTypeSlice.
When calling `Context#SetContentType(contentType)` to set the response header Content-Type, it will use contentTypeSlice to avoid to allocate the memory. See the function `ToContentTypes(contentType)`.
func BindURLValues ¶ added in v1.0.0
BindURLValues parses the data and assign to the pointer ptr to a struct.
Notice: tag is the name of the struct tag. such as "form", "query", etc.
func MaxNumOfURLParams ¶ added in v1.6.0
func MaxNumOfURLParams() int
MaxNumOfURLParams is equal to DefaultShip.MaxNumOfURLParams().
func ToContentTypes ¶ added in v1.4.0
ToContentTypes converts the Content-Type to the Content-Type slice.
func ToHTTPHandler ¶
ToHTTPHandler converts the Handler to http.Handler
Types ¶
type BindUnmarshaler ¶ added in v1.0.0
type BindUnmarshaler interface { // Unmarshal decodes the argument param and assigns to itself. UnmarshalBind(param string) error }
BindUnmarshaler is the interface used to wrap the UnmarshalParam method.
type Binder ¶
type Binder interface { // Bind parses the data from ctx and assigns to v. // // Notice: v must be a non-nil pointer. Bind(ctx *Context, v interface{}) error }
Binder is the interface to bind the value to v from ctx.
func BinderFunc ¶ added in v1.0.0
BinderFunc converts a function to Binder.
func FormBinder ¶ added in v1.0.0
FormBinder returns a Form binder to bind the Form request.
Notice: The bound value must be a pointer to a struct. You can modify the name of the field by the tag, which is "form" by default.
func JSONBinder ¶ added in v1.0.0
func JSONBinder() Binder
JSONBinder returns a JSON binder to bind the JSON request.
func QueryBinder ¶ added in v1.0.0
QueryBinder returns a query binder to bind the query parameters..
Notice: The bound value must be a pointer to a struct. You can modify the name of the field by the tag, which is "query" by default.
type Context ¶
type Context struct { // you can use it to pass the error between the handlers or the middlewares. // // Notice: when the new request is coming, it will be reset to nil. Err error // ReqCtxData is the data what each request has, the lifecycle of which is // the same as this context, that's, when creating this context, it will // call `newCtxData()`, which is set by `SetNewCtxData()` as the option of // the ship router, to creating ReqCtxData. When finishing the request, // it will be reset by the context and put into the pool with this context. ReqCtxData Resetter // 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 GetContext ¶ added in v1.0.0
GetContext gets the Context from the http Request.
Notice: you must enable it by SetEnableCtxHTTPContext(true).
func (*Context) Accept ¶ added in v1.0.0
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 ¶ added in v1.0.0
AcquireBuffer acquires a buffer.
Notice: you should call ReleaseBuffer() to release it.
func (*Context) AddHeader ¶ added in v1.5.0
AddHeader appends the value for the response header name.
func (*Context) Attachment ¶ added in v1.0.0
Attachment sends a response as attachment, prompting client to save the file.
If the file does not exist, it returns ErrNotFound.
func (*Context) BasicAuth ¶ added in v1.8.0
BasicAuth returns the username and password from the request.
func (*Context) Bind ¶ added in v1.0.0
Bind binds the request information into the provided value v.
The default binder does it based on Content-Type header.
func (*Context) BindQuery ¶ added in v1.0.0
BindQuery binds the request URL query into the provided value v.
func (*Context) Blob ¶ added in v1.0.0
Blob sends a blob response with status code and content type.
func (*Context) BlobString ¶ added in v1.0.0
func (c *Context) BlobString(code int, contentType string, format string, args ...interface{}) (err error)
BlobString sends a string blob response with status code and content type.
func (*Context) Body ¶ added in v1.7.0
func (c *Context) Body() io.ReadCloser
Body returns the reader of the request body.
func (*Context) Charset ¶ added in v1.0.0
Charset returns the charset of the request content.
Return "" if there is no charset.
func (*Context) ClearData ¶ added in v1.0.0
func (c *Context) ClearData()
ClearData clears the data.
func (*Context) ContentLength ¶ added in v1.0.0
ContentLength return the length of the request body.
func (*Context) ContentType ¶ added in v1.0.0
ContentType returns the Content-Type of the request without the charset.
func (*Context) DelSession ¶ added in v1.0.0
DelSession deletes the session from the backend store.
id must not be "".
func (*Context) Error ¶ added in v1.5.0
Error sends an error response with status code.
If the error is the type of HTTPError, it will extract the fields of code and ct from it as the status code and the content-type.
func (*Context) File ¶ added in v1.0.0
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) FindHandler ¶ added in v1.0.0
FindHandler finds the registered router handler by the method and path of the request.
Return nil if not found.
func (*Context) FormFile ¶ added in v1.0.0
func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
FormFile returns the multipart form file for the provided name.
func (*Context) FormFile2 ¶ added in v1.8.0
FormFile2 returns the multipart form file for the provided name.
func (*Context) FormParams ¶ added in v1.0.0
FormParams returns the form parameters as `url.Values`.
func (*Context) FormValue ¶ added in v1.0.0
FormValue returns the form field value for the provided name.
func (*Context) GetBody ¶ added in v1.0.0
GetBody reads all the contents from the body and returns it as string.
func (*Context) GetBodyReader ¶ added in v1.0.0
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 ¶ added in v1.0.0
GetHeader returns the first value of the request header named name.
Return "" if the header does not exist.
func (*Context) GetSession ¶ added in v1.0.0
GetSession returns the session content by id from the backend store.
If the session id does not exist, it maybe return (nil, nil).
Notice: for the same session id, the context maybe optimize GetSession by the cache, which will call the backend store only once.
func (*Context) Handle ¶ added in v1.0.0
Handle calls the context handler.
Return ErrNoHandler if the context handler or the global handler is not set.
Example ¶
responder := func(ctx *Context, args ...interface{}) error { return ctx.String(http.StatusOK, fmt.Sprintf("%s, %s", args...)) } sethandler := func(next Handler) Handler { return func(ctx *Context) error { ctx.SetHandler(responder) return next(ctx) } } router := New() router.Use(sethandler) router.Route("/path/to").GET(func(c *Context) error { return c.Handle("Hello", "World") }) // For test req := httptest.NewRequest(http.MethodGet, "/path/to", nil) resp := httptest.NewRecorder() router.ServeHTTP(resp, req) fmt.Println(resp.Code) fmt.Println(resp.Body.String())
Output: 200 Hello, World
func (*Context) Inline ¶ added in v1.0.0
Inline sends a response as inline, opening the file in the browser.
If the file does not exist, it returns ErrNotFound.
func (*Context) IsResponded ¶ added in v1.0.0
IsResponded reports whether the response is sent.
func (*Context) IsWebSocket ¶ added in v1.0.0
IsWebSocket reports whether HTTP connection is WebSocket or not.
func (*Context) JSONP ¶ added in v1.0.0
JSONP sends a JSONP response with status code. It uses `callback` to construct the JSONP payload.
func (*Context) JSONPBlob ¶ added in v1.0.0
JSONPBlob sends a JSONP blob response with status code. It uses `callback` to construct the JSONP payload.
func (*Context) JSONPretty ¶ added in v1.0.0
JSONPretty sends a pretty-print JSON with status code.
func (*Context) MultipartForm ¶ added in v1.0.0
MultipartForm returns the multipart form.
func (*Context) MultipartReader ¶ added in v1.8.0
MultipartReader returns the multipart reader from the request.
func (*Context) NoContent ¶ added in v1.0.0
NoContent sends a response with no body and a status code.
func (*Context) NotFoundHandler ¶ added in v1.0.0
NotFoundHandler returns the configured NotFound handler.
func (*Context) ParamNames ¶ added in v1.0.0
ParamNames returns all the names of the URL parameters.
func (*Context) ParamToStruct ¶ added in v1.0.0
ParamToStruct scans the url parameters to a pointer v to the struct.
For the struct, the argument name is the field name by default. But you can change it by the tag "url", such as `url:"name"`. The tag `url:"-"`, however, will ignore this field.
func (*Context) ParamValues ¶ added in v1.0.0
ParamValues returns all the names of the URL parameters.
func (*Context) Params ¶ added in v1.0.0
Params returns all the parameters as the key-value map in the url path.
func (*Context) QueryParam ¶ added in v1.0.0
QueryParam returns the query param for the provided name.
func (*Context) QueryParams ¶ added in v1.0.0
QueryParams returns the query parameters as `url.Values`.
func (*Context) QueryRawString ¶ added in v1.0.0
QueryRawString returns the URL query string.
func (*Context) RealIP ¶ added in v1.0.0
RealIP returns the client's network address based on `X-Forwarded-For` or `X-Real-IP` request header.
func (*Context) Redirect ¶ added in v1.0.0
Redirect redirects the request to a provided URL with status code.
func (*Context) ReleaseBuffer ¶ added in v1.0.0
ReleaseBuffer releases a buffer into the pool.
func (*Context) RemoteAddr ¶ added in v1.0.0
RemoteAddr returns the remote address of the http connection.
func (*Context) Render ¶ added in v1.0.0
Render renders a template named name with data and sends a text/html response with status code.
func (*Context) RequestURI ¶ added in v1.0.0
RequestURI returns the URI of the request.
func (*Context) RespHeader ¶ added in v1.7.0
RespHeader returns the header of the response.
func (*Context) Response ¶ added in v1.0.0
func (c *Context) Response() http.ResponseWriter
Response returns the inner http.ResponseWriter.
Notice: you should not cache the returned response.
func (*Context) Scheme ¶ added in v1.0.0
Scheme returns the HTTP protocol scheme, `http` or `https`.
func (*Context) SetConnectionClose ¶ added in v1.0.0
func (c *Context) SetConnectionClose()
SetConnectionClose tell the server to close the connection.
func (*Context) SetContentType ¶ added in v1.0.0
SetContentType sets the Content-Type of the response body to contentType, but does nothing if contentType is "".
Notice: In order to avoid the memory allocation to improve performance, it will look up the corresponding Content-Type slice constant firstly, or generate one by the argument contentType, then set the response header Content-Type to the Content-Type slice. Howevre, you can call SetContentTypes() to set it to avoid the memory allocation, and pass "" to the response function, for example, JSON(), String(), Blob(), etc.
For the pre-defined Content-Type slices, please see https://godoc.org/github.com/xgfone/ship/#pkg-variables.
func (*Context) SetContentTypes ¶ added in v1.0.0
SetContentTypes sets the Content-Type of the response body to more than one.
func (*Context) SetHandler ¶ added in v1.0.0
SetHandler sets a context handler in order to call it across the functions by the method Handle(), which is used to handle the various arguments.
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.String(http.StatusOK, v) } case 2: switch v0 := args[0].(type) { case int: return ctx.String(v0, "%v", args[1]) } } return ctx.NoContent(http.StatusInternalServerError) } sethandler := func(next Handler) Handler { return func(ctx *Context) error { ctx.SetHandler(responder) return next(ctx) } } router := New() router.Use(sethandler) 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") })
Example ¶
responder := func(ctx *Context, args ...interface{}) error { return ctx.String(http.StatusOK, fmt.Sprintf("%s, %s", args...)) } sethandler := func(next Handler) Handler { return func(ctx *Context) error { ctx.SetHandler(responder) return next(ctx) } } router := New() router.Use(sethandler) router.Route("/path/to").GET(func(c *Context) error { return c.Handle("Hello", "World") }) // For test req := httptest.NewRequest(http.MethodGet, "/path/to", nil) resp := httptest.NewRecorder() router.ServeHTTP(resp, req) fmt.Println(resp.Code) fmt.Println(resp.Body.String())
Output: 200 Hello, World
func (*Context) SetRequest ¶ added in v1.7.0
SetRequest resets the request to req, which will ignore nil.
func (*Context) SetResponded ¶ added in v1.0.0
SetResponded sets the response to be sent or not.
func (*Context) SetResponse ¶ added in v1.0.0
func (c *Context) SetResponse(resp http.ResponseWriter)
SetResponse resets the response to resp, which will ignore nil.
func (*Context) SetSession ¶ added in v1.0.0
SetSession sets the session to the backend store.
id must not be "".
value should not be nil. If nil, however, it will tell the context that the session id is missing, and the context should not forward the request to the underlying session store when calling GetSession.
func (*Context) StatusCode ¶ added in v1.2.0
StatusCode returns the status code of the response.
Notice: it's used by the middleware, such as Logger in general.
func (*Context) Stream ¶ added in v1.0.0
Stream sends a streaming response with status code and content type.
func (*Context) Write ¶ added in v1.0.0
Write writes the content to the peer.
it will write the header firstly if the header is not sent.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group is a router group, that's, it manages a set of routes.
func G ¶ added in v1.6.0
func G(prefix string, middlewares ...Middleware) *Group
G is equal to DefaultShip.Group(prefix, middlewares...).
func GroupWithoutMiddleware ¶ added in v1.6.0
func GroupWithoutMiddleware(prefix string, middlewares ...Middleware) *Group
GroupWithoutMiddleware is equal to DefaultShip.GroupWithoutMiddleware(prefix, middlewares...).
func (*Group) Group ¶
func (g *Group) Group(prefix string, middlewares ...Middleware) *Group
Group returns a new sub-group.
func (*Group) GroupWithoutMiddleware ¶ added in v1.0.0
func (g *Group) GroupWithoutMiddleware(prefix string, middlewares ...Middleware) *Group
GroupWithoutMiddleware is the same as Group, but not inherit the middlewares of the parent.
func (*Group) Route ¶
Route returns a new route, then you can customize and register it.
You must call Route.Method() or its short method.
func (*Group) RouteWithoutMiddleware ¶ added in v1.0.0
RouteWithoutMiddleware is the same as Group, but not inherit the middlewares of the group.
func (*Group) Use ¶
func (g *Group) Use(middlewares ...Middleware) *Group
Use adds some middlwares for the group and returns the origin group to write the chained router.
type HTMLTemplateEngine ¶ added in v1.0.0
type HTMLTemplateEngine interface { // Ext should return the final file extension which this template engine // is responsible to render. Ext() string // Load or reload all the templates. Load() error // Eexecute and render a template by its filename. Execute(w io.Writer, filename string, data interface{}, metadata map[string]interface{}) error }
HTMLTemplateEngine is the interface which all html template engines should be implemented.
type HTTPError ¶
HTTPError represents an error with HTTP Status Code.
func NewHTTPError ¶
NewHTTPError returns a new HTTPError.
func (HTTPError) GetError ¶ added in v1.3.0
GetError returns the inner error.
If Err is nil but Msg is not "", return `errors.New(e.Msg)` instead; Or return nil.
HTTPError{Err: errors.New("")}.GetError() != nil HTTPError{Msg: "xxx"}.GetError() != nil HTTPError{Code: 200}.GetError() == nil
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 { Writer() io.Writer Trace(format string, args ...interface{}) error Debug(foramt string, args ...interface{}) error Info(foramt string, args ...interface{}) error Warn(foramt string, args ...interface{}) error Error(foramt string, args ...interface{}) error }
Logger stands for a logger.
type MuxBinder ¶ added in v1.0.0
type MuxBinder struct {
// contains filtered or unexported fields
}
MuxBinder is a multiplexer for kinds of Binders.
func NewMuxBinder ¶ added in v1.0.0
func NewMuxBinder() *MuxBinder
NewMuxBinder returns a new MuxBinder.
func (*MuxBinder) Add ¶ added in v1.0.0
Add adds a binder to bind the content for the header Content-Type.
func (*MuxBinder) Bind ¶ added in v1.0.0
Bind implements the interface Binder, which will call the registered binder to bind the request to v by the request header Content-Type.
type MuxRenderer ¶ added in v1.0.0
type MuxRenderer struct {
// contains filtered or unexported fields
}
MuxRenderer is a multiplexer for kinds of Renderers.
func NewMuxRenderer ¶ added in v1.0.0
func NewMuxRenderer() *MuxRenderer
NewMuxRenderer returns a new MuxRenderer.
func (*MuxRenderer) Add ¶ added in v1.0.0
func (mr *MuxRenderer) Add(suffix string, renderer Renderer)
Add adds a renderer with a suffix identifier.
func (*MuxRenderer) Del ¶ added in v1.0.0
func (mr *MuxRenderer) Del(suffix string)
Del removes the corresponding renderer by the suffix.
func (*MuxRenderer) Get ¶ added in v1.0.0
func (mr *MuxRenderer) Get(suffix string) Renderer
Get returns the corresponding renderer by the suffix.
Return nil if not found.
type Option ¶ added in v1.0.0
type Option func(*Ship)
Option is used to configure Ship.
func DisableErrorLog ¶ added in v1.1.0
DisableErrorLog disables the default error handler to log the error.
func EnableCtxHTTPContext ¶ added in v1.1.0
EnableCtxHTTPContext sets whether to inject the Context into the HTTP request as the http context, then you can use `GetContext(httpReq)` to get the Context.
func KeepTrailingSlashPath ¶ added in v1.1.0
KeepTrailingSlashPath sets whether to remove the trailing slash from the registered url path.
func SetBindQuery ¶ added in v1.0.0
SetBindQuery sets the query binder to bind the query to a value, which is `BindURLValues(v, d, "query")` by default.
func SetBinder ¶ added in v1.0.0
SetBinder sets the Binder, which is used to bind a value from the request.
It's `MuxBinder` by default, which has added some binders, for example, "application/json", "application/xml", "text/xml", "multipart/form-data", and "application/x-www-form-urlencoded" as follow.
mb := New().MuxBinder() // or NewMuxBinder(), but you need to set it. mb.Add(MIMEApplicationJSON, JSONBinder()) mb.Add(MIMETextXML, XMLBinder()) mb.Add(MIMEApplicationXML, XMLBinder()) mb.Add(MIMEMultipartForm, FormBinder()) mb.Add(MIMEApplicationForm, FormBinder())
Then, you can add yourself binder, for example,
mb.Add("Content-Type", binder)
So you can use it by the four ways:
mb.Bind(ctx, ptr)
In the context, you can call it like this:
ctx.Bind(ptr)
func SetBufferSize ¶ added in v1.0.0
SetBufferSize sets the buffer size, which is used to initializing the buffer pool.
The default is 2048.
func SetCtxDataSize ¶ added in v1.0.0
SetCtxDataSize sets the initializing size of the context data, that's, Context.Data.
func SetCtxHandler ¶ added in v1.0.0
SetCtxHandler sets the default global context handler.
func SetDebug ¶ added in v1.0.0
SetDebug sets whether to enable the debug mode, which is false by default.
func SetDefaultMethodMapping ¶ added in v1.0.0
SetDefaultMethodMapping sets the default mapping when registering the struct route.
The default is
map[string]string{ "Create": "POST", "Delete": "DELETE", "Update": "PUT", "Get": "GET", }
func SetEnableCtxHTTPContext ¶ added in v1.0.0
SetEnableCtxHTTPContext is the alias of EnableCtxHTTPContext.
DEPRECATED! In order to keep the backward compatibility, it does not removed until the next major version.
func SetErrorHandler ¶ added in v1.0.0
SetErrorHandler sets default error handler, which will handle the error returned by the handler or the middleware at last.
The default will send the response to the peer if the error is a HTTPError. Or only send 500 if no response.
func SetKeepTrailingSlashPath ¶ added in v1.0.0
SetKeepTrailingSlashPath is the alias of KeepTrailingSlashPath.
DEPRECATED! In order to keep the backward compatibility, it does not removed until the next major version.
func SetLogger ¶ added in v1.0.0
SetLogger sets the Logger, which is `NewNoLevelLogger(os.Stderr)` by default.
func SetMaxMiddlewareNum ¶ added in v1.0.0
SetMaxMiddlewareNum sets the maximum number of the middlewares, which is 256 by default.
func SetMethodNotAllowedHandler ¶ added in v1.0.0
SetMethodNotAllowedHandler sets the handler to handle MethodNotAllowed.
It is used by the default router implemetation.
func SetNewCtxData ¶ added in v1.0.0
SetNewCtxData sets the creator of the request data to correlating to the context when newing the context.
Notice: The lifecycle of the request data is the same as its context. When the context is created, the request data is also created. When finishing to handle the request, it will be reset by the context, not destroyed.
func SetNewRouter ¶ added in v1.0.0
SetNewRouter sets the NewRouter to generate the new router.
if newRouter is nil, it will be reset to the default.
func SetNotFoundHandler ¶ added in v1.0.0
SetNotFoundHandler sets the handler to handle NotFound, which is `NotFoundHandler()` by default.
func SetOptionsHandler ¶ added in v1.0.0
SetOptionsHandler sets the handler to handle the OPTIONS request.
It is used by the default router implemetation.
func SetRenderer ¶ added in v1.0.0
SetRenderer sets the Renderer, which is used to render the response to the peer.
It's `MuxRenderer` by default, which has added some renderers, such as json, jsonpretty, xml, and xmlpretty as follow.
mr := New().MuxRenderer() // or NewMuxRenderer(), but you need to set it. mr.Add("json", JSONRenderer()) mr.Add("jsonpretty", JSONPrettyRenderer(" ")) mr.Add("xml", XMLRenderer()) mr.Add("xmlpretty", XMLPrettyRenderer(" "))
Then, you can add yourself renderer, for example,
engine := django.New(".", ".html")) mr.Add(engine.Ext(), HTMLTemplate(engine))
So you can use it by the four ways:
mr.Render(ctx, "json", 200, data) mr.Render(ctx, "jsonpretty", 200, data) mr.Render(ctx, "xml", 200, data) mr.Render(ctx, "xmlpretty", 200, data) mr.Render(ctx, "index.html", 200, data)
In the context, you can call it like this:
ctx.Render("json", 200, data) ctx.Render("jsonpretty", 200, data) ctx.Render("xml", 200, data) ctx.Render("xmlpretty", 200, data) ctx.Render("index.html", 200, data)
func SetRouteFilter ¶ added in v1.7.0
SetRouteFilter sets the route filter, which will ignore the route and not register it if the filter returns false.
For matching the group, you maybe check whether the path has the prefix, that's, the group name.
func SetRouteModifier ¶ added in v1.7.0
SetRouteModifier sets the route modifier, which will modify the route before registering it.
The modifier maybe return the new name, path and method.
Notice: the modifier will be run before filter.
func SetSession ¶ added in v1.0.0
SetSession sets the Session, which is `NewMemorySession()` by default.
func SetSignal ¶ added in v1.0.0
SetSignal sets the signals.
Notice: the signals will be wrapped and handled by the http server if running it.
The default is
[]os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGABRT, syscall.SIGINT}
In order to disable the signals, you can set it to []os.Signal{}.
type Renderer ¶
Renderer is the interface to render the response.
func HTMLTemplateRenderer ¶ added in v1.0.0
func HTMLTemplateRenderer(engine HTMLTemplateEngine) Renderer
HTMLTemplateRenderer returns HTML template renderer.
func JSONPrettyRenderer ¶ added in v1.0.0
JSONPrettyRenderer returns a pretty JSON renderer.
Example
renderer := JSONPrettyRenderer(" ") renderer.Render(ctx, "jsonpretty", code, data) # Or appoint a specific Marshaler. renderer := JSONPrettyRenderer("", func(v interface{}) ([]byte, error) { return json.MarshalIndent(v, "", " ") }) renderer.Render(ctx, "jsonpretty", code, data)
Notice: the renderer name must be "jsonpretty".
func JSONRenderer ¶ added in v1.0.0
JSONRenderer returns a JSON renderer.
Example
renderer := JSONRenderer() renderer.Render(ctx, "json", code, data)
Notice: the renderer name must be "json".
func RendererFunc ¶ added in v1.0.0
RendererFunc converts a function to Renderer.
func SimpleRenderer ¶ added in v1.0.0
SimpleRenderer returns a simple renderer, which is the same as follow:
b, err := encode(data) if err != nil { return err } return ctx.Blob(code, contentType, b)
func XMLPrettyRenderer ¶ added in v1.0.0
XMLPrettyRenderer returns a pretty XML renderer.
Example
renderer := XMLPrettyRenderer(" ") renderer.Render(ctx, "xmlpretty", code, data) # Or appoint a specific Marshaler. renderer := XMLPrettyRenderer("", func(v interface{}) ([]byte, error) { return xml.MarshalIndent(v, "", " ") }) renderer.Render(ctx, "xmlpretty", code, data)
Notice: the default marshaler won't add the XML header, and the renderer name must be "xmlpretty".
func XMLRenderer ¶ added in v1.0.0
XMLRenderer returns a XML renderer.
Example
renderer := XMLRenderer() renderer.Render(ctx, "xml", code, data)
Notice: the default marshaler won't add the XML header. and the renderer name must be "xml".
type Route ¶
type Route struct {
// contains filtered or unexported fields
}
Route represents a route information.
func RouteWithoutMiddleware ¶ added in v1.6.0
RouteWithoutMiddleware is equal to DefaultShip.RouteWithoutMiddleware(path).
func (*Route) Any ¶
Any registers all the supported methods , which is short for r.Method(handler, "GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "CONNECT", "OPTIONS", "TRACE" )
func (*Route) Group ¶ added in v1.4.0
Group returns the group that the current route belongs to.
Notice: it will return nil if the route is from ship.Route.
func (*Route) HasSchemes ¶ added in v1.0.0
HasSchemes checks whether the request is one of the schemes. If no, the request will be rejected.
Example
s := ship.New() // We only handle https and wss, others will be rejected. s.R("/path/to").HasSchemes("https", "wss").POST(handler)
Notice: it is implemented by using Matcher.
func (*Route) Header ¶ added in v1.0.0
Header 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)
Notice: it is implemented by using Matcher.
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) Match ¶ added in v1.0.0
Match adds the matchers of the request to check whether the request matches these conditions.
These matchers will be executes as the middlewares.
func (*Route) MatchMiddleware ¶ added in v1.0.0
func (r *Route) MatchMiddleware(f func([]Matcher) Middleware) *Route
MatchMiddleware sets the matcher middleware.
The default implementation will execute those matchers in turn. If a certain matcher returns an error, it will return a HTTPError with 404 and the error.
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) Redirect ¶ added in v1.1.0
Redirect is used to redirect the path to toURL.
method is GET by default.
func (*Route) Ship ¶ added in v1.4.0
Ship returns the ship that the current route is associated with.
func (*Route) Static ¶ added in v1.0.0
Static is the same as StaticFS, but listing the files for a directory.
func (*Route) StaticFS ¶ added in v1.0.0
func (r *Route) StaticFS(fs http.FileSystem) *Route
StaticFS registers a route to serve a static filesystem.
func (*Route) StaticFile ¶ added in v1.0.0
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 Router ¶
type Router interface { // Generate a URL by the url name and parameters. URL(name string, params ...interface{}) string // Add a route with name, path, method and handler, // and return the number of the parameters if there are the parameters // in the route. Or return 0. // // If the name has been added for the same path, it should be allowed. // Or it should panic. // // If the router does not support the parameter, it should panic. // // Notice: for keeping consistent, the parameter should start with ":" // or "*". ":" stands for a single parameter, and "*" stands for // a wildcard parameter. Add(name string, path string, method string, handler interface{}) (paramNum int) // Find a route handler by the method and path of the request. // // Return nil if the route does not exist. // // If the route has more than one parameter, the name and value // of the parameters should be stored `pnames` and `pvalues` respectively. Find(method string, path string, pnames []string, pvalues []string) (handler interface{}) // Traverse each route. Each(func(name string, method string, path string)) }
Router stands for a router management.
type Session ¶ added in v1.0.0
type Session interface { // If the session id does not exist, it should return (nil, nil). GetSession(id string) (value interface{}, err error) SetSession(id string, value interface{}) error DelSession(id string) error }
Session represents an interface about the session.
func NewMemorySession ¶ added in v1.0.0
func NewMemorySession() Session
NewMemorySession return a Session implementation based on the memory.
type Ship ¶
type Ship struct {
// contains filtered or unexported fields
}
Ship is an app to be used to manage the router.
func Pre ¶ added in v1.6.0
func Pre(middlewares ...Middleware) *Ship
Pre is equal to DefaultShip.Pre(middlewares...).
func RegisterOnShutdown ¶ added in v1.6.0
func RegisterOnShutdown(functions ...func()) *Ship
RegisterOnShutdown is equal to DefaultShip.RegisterOnShutdown(functions...).
func SetConnStateHandler ¶ added in v1.6.0
SetConnStateHandler is equal to DefaultShip.SetConnStateHandler(h).
func StartServer ¶ added in v1.6.0
StartServer is equal to DefaultShip.StartServer(server).
func Use ¶ added in v1.6.0
func Use(middlewares ...Middleware) *Ship
Use is equal to DefaultShip.Use(middlewares...).
func (*Ship) AcquireBuffer ¶ added in v1.0.0
AcquireBuffer gets a Buffer from the pool.
func (*Ship) AcquireContext ¶
AcquireContext gets a Context from the pool.
func (*Ship) Clone ¶ added in v1.0.0
Clone returns a new Ship router with a new name by the current configuration.
Notice: the new router will disable the signals and register the shutdown function into the parent Ship router.
func (*Ship) Configure ¶ added in v1.0.0
Configure configures the Ship.
Notice: the method must be called before starting the http server.
func (*Ship) Group ¶
func (s *Ship) Group(prefix string, middlewares ...Middleware) *Group
Group returns a new sub-group.
func (*Ship) GroupWithoutMiddleware ¶ added in v1.0.0
func (s *Ship) GroupWithoutMiddleware(prefix string, middlewares ...Middleware) *Group
GroupWithoutMiddleware is the same as Group, but not inherit the middlewares of Ship.
func (*Ship) Link ¶ added in v1.0.0
Link links other to the current router, that's, only if either of the two routers is shutdown, another is also shutdown.
Return the current router.
func (*Ship) MaxNumOfURLParams ¶ added in v1.6.0
MaxNumOfURLParams reports the maximum number of the parameters of all the URLs.
Notice: it should be only called after adding all the urls.
func (*Ship) MuxBinder ¶ added in v1.0.0
MuxBinder check whether the inner Binder is MuxBinder.
If yes, return it as "*MuxBinder"; or return nil.
func (*Ship) MuxRenderer ¶ added in v1.0.0
func (s *Ship) MuxRenderer() *MuxRenderer
MuxRenderer check whether the inner Renderer is MuxRenderer.
If yes, return it as "*MuxRenderer"; or return nil.
func (*Ship) NewContext ¶
NewContext news and returns a Context.
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) RegisterOnShutdown ¶ added in v1.0.0
RegisterOnShutdown registers some functions to run when the http server is shut down.
func (*Ship) ReleaseBuffer ¶ added in v1.0.0
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) RouteWithoutMiddleware ¶ added in v1.0.0
RouteWithoutMiddleware is the same as Route, but not inherit the middlewares of Ship.
func (*Ship) ServeHTTP ¶
func (s *Ship) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the interface http.Handler.
func (*Ship) SetConnStateHandler ¶ added in v1.0.0
SetConnStateHandler sets a handler to monitor the change of the connection state, which is used by the HTTP server.
func (*Ship) Start ¶ added in v1.0.0
Start starts a HTTP server with addr and ends when the server is closed.
If tlsFile is not nil, it must be certFile and keyFile. That's,
router := ship.New() rouetr.Start(addr, certFile, keyFile)
func (*Ship) StartServer ¶ added in v1.0.0
StartServer starts a HTTP server and ends when the server is closed.
func (*Ship) Stop ¶ added in v1.9.0
func (s *Ship) Stop()
Stop is equal to s.Shutdown(context.Background()).
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 |
---|---|
_examples
|
|
Package middleware is the collection of the middlewares.
|
Package middleware is the collection of the middlewares. |
render
|
|
django
Module
|
|
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. |
lock
Package lock makes a unsafe Router implementation to be thread-safe.
|
Package lock makes a unsafe Router implementation to be thread-safe. |
Package utils supplies some utility tools.
|
Package utils supplies some utility tools. |