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 AddContentTypeMapping(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 GetText(url string) (body string, err error)
- func HeadJSON(url string) (respHeader http.Header, err error)
- func InStrings(s string, ss []string) bool
- func IsInteger(s string) bool
- func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*http.Request, error)
- func OptionsJSON(url string, resp interface{}) (err error)
- func PatchJSON(url string, req interface{}, resp interface{}) (err error)
- func PostJSON(url string, req interface{}, resp interface{}) (err error)
- func PutJSON(url string, req interface{}) (err error)
- func PutResponseIntoPool(r *Response)
- func Request(ctx context.Context, method, url string, reqHeader http.Header, ...) (err error)
- func RequestJSON(ctx context.Context, method, url string, reqHeader http.Header, ...) error
- func SetContentType(res http.ResponseWriter, ct string)
- func SetHeaderContentType(header http.Header, ct string)
- func SetStructFieldToDefault(v interface{}) (err error)
- func SplitHostPort(hostport string) (host, port string)
- func ToHTTPHandler(s *Ship, h Handler) http.Handler
- type Binder
- 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() (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) 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
- func (c *Context) Scheme() (scheme string)
- func (c *Context) SetBinder(b 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 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)
- func (c *Context) SetSession(id string, value interface{}) (err error)
- func (c *Context) SetSessionManagement(s 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) URLParam(name string) string
- func (c *Context) URLParamNames() []string
- func (c *Context) URLParamValues() []string
- func (c *Context) URLParams() map[string]string
- func (c *Context) URLPath(name string, params ...interface{}) 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 HTTPServerError
- type Handler
- type Logger
- type Middleware
- type MuxBinder
- type MuxRenderer
- type OnceRunner
- type RWLocker
- type RegexpHostRouter
- type Renderer
- 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) 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) 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) Route(path string) *Route
- func (g *RouteGroup) Ship() *Ship
- func (g *RouteGroup) Use(middlewares ...Middleware) *RouteGroup
- type RouteInfo
- type Router
- type Runner
- type Session
- 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, 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)
- func (s *Ship) Group(prefix string) *RouteGroup
- func (s *Ship) Host(host string) *RouteGroup
- func (s *Ship) Hosts() (hosts []string)
- func (s *Ship) NewContext() *Context
- func (s *Ship) Pre(middlewares ...Middleware) *Ship
- 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)
- func (s *Ship) Routers() (routers map[string]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)
- func (s *Ship) SetLogger(logger Logger) *Ship
- func (s *Ship) SetNewRegexpHostRouter(f func() RegexpHostRouter) *Ship
- func (s *Ship) SetNewRouter(f func() Router) *Ship
- 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 ( ErrMissingContentType = errors.New("missing the header 'Content-Type'") ErrRendererNotRegistered = errors.New("renderer not registered") ErrInvalidRedirectCode = errors.New("invalid redirect status code") ErrInvalidSession = errors.New("invalid session") ErrSessionNotExist = errors.New("session does not exist") ErrNoSessionSupport = errors.New("no session support") ErrNoResponder = errors.New("no responder") )
Some non-HTTP Errors
var ( ErrBadRequest = NewHTTPServerError(http.StatusBadRequest) ErrForbidden = NewHTTPServerError(http.StatusForbidden) ErrNotFound = NewHTTPServerError(http.StatusNotFound) ErrMethodNotAllowed = NewHTTPServerError(http.StatusMethodNotAllowed) ErrStatusNotAcceptable = NewHTTPServerError(http.StatusNotAcceptable) ErrRequestTimeout = NewHTTPServerError(http.StatusRequestTimeout) ErrStatusConflict = NewHTTPServerError(http.StatusConflict) ErrStatusGone = NewHTTPServerError(http.StatusGone) ErrStatusRequestEntityTooLarge = NewHTTPServerError(http.StatusRequestEntityTooLarge) ErrUnsupportedMediaType = NewHTTPServerError(http.StatusUnsupportedMediaType) ErrTooManyRequests = NewHTTPServerError(http.StatusTooManyRequests) ErrInternalServerError = NewHTTPServerError(http.StatusInternalServerError) ErrStatusNotImplemented = NewHTTPServerError(http.StatusNotImplemented) ErrBadGateway = NewHTTPServerError(http.StatusBadGateway) ErrStatusGatewayTimeout = NewHTTPServerError(http.StatusGatewayTimeout) ErrStatusHTTPVersionNotSupported = NewHTTPServerError(http.StatusHTTPVersionNotSupported) )
Some HTTP error.
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 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 AddContentTypeMapping ¶
AddContentTypeMapping add a content type mapping to convert contentType to contentTypeSlice, then 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 ¶
DeleteJSON is the same as RequestJSON, but use the method DELETE instead, which may has the request body and the response body.
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 GetJSON ¶
GetJSON is the same as RequestJSON, but use the method GET instead, which has no request body but has the response body if successfully.
func GetText ¶
GetText is the same as GetJSON, but get the response body as the string, which has no request body but has the response body if successfully.
func HeadJSON ¶
HeadJSON is the same as RequestJSON, but use the method HEADE instead, which has no request or response body.
func NewRequestWithContext ¶
func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*http.Request, error)
NewRequestWithContext is the compatibility of http.NewRequestWithContext.
func OptionsJSON ¶
OptionsJSON is the same as RequestJSON, but use the method OPTIONS instead, which has no request body but has the response body if successfully.
func PatchJSON ¶
PatchJSON is the same as RequestJSON, but use the method PATCH instead, which has the request body and the response body if successfully.
func PostJSON ¶
PostJSON is the same as RequestJSON, but use the method POST instead, which has the request body and the response body if successfully.
func PutJSON ¶
PutJSON is the same as RequestJSON, but use the method PUT instead, which has the request body but no response body.
func PutResponseIntoPool ¶
func PutResponseIntoPool(r *Response)
PutResponseIntoPool puts a Response into the pool.
func Request ¶
func Request(ctx context.Context, method, url string, reqHeader http.Header, reqBody, respBody interface{}) (err error)
Request sends the http request and parses the response body into respBody.
reqBody must be one of types:
- nil
- []byte
- string
- io.Reader
- func() (io.Reader, error)
respBody must be one of types:
- nil: ignore the response body.
- *[]byte: read the response body and puts it into respBody as []byte.
- *string: read the response body and puts it into respBody as string.
- io.Writer: copy the response body into the given writer.
- xml.Unmarshaler: read and parse the response body as the XML.
- json.Unmarshaler: read and parse the response body as the JSON.
- func(io.Reader) error: call the function with the response body.
- func(*bytes.Buffer) error: read the response body into the buffer and call the function.
- func(*http.Response) error: call the function with the response.
Notice: if the encoding of the response body is gzip, it will decode it firstly.
func RequestJSON ¶
func RequestJSON(ctx context.Context, method, url string, reqHeader http.Header, reqBody, respBody interface{}) error
RequestJSON is the same as Request, but encodes the request and decodes response body as JSON.
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 ¶
func SetStructFieldToDefault(v interface{}) (err error)
SetStructFieldToDefault sets the default value of the fields of the pointer to struct v to the value of the tag "default" of the fields when the field value is ZERO.
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 } time.Time // Format: A. Integer(UTC); B. String(RFC3339) time.Duration // Format: A. Integer(ms); B. String(time.ParseDuration) pointer to the types above
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:"-"` DurationInt time.Duration `default:"1000"` DurationStr time.Duration `default:"2s"` TimeInt time.Time `default:"1618059388"` TimeStr time.Time `default:"2021-04-10T12:56:28Z"` NoneP *int IntPtr *int `default:"456"` TimePtr *time.Time `default:"2021-04-10T12:56:28Z"` DurationPtr *time.Duration `default:"3s"` } 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) fmt.Println(s.DurationInt) fmt.Println(s.DurationStr) fmt.Println(s.TimeInt.UTC().Format(time.RFC3339)) fmt.Println(s.TimeStr.UTC().Format(time.RFC3339)) fmt.Println(s.NoneP == nil) fmt.Println(*s.IntPtr) fmt.Println(s.TimePtr.UTC().Format(time.RFC3339)) fmt.Println(*s.DurationPtr)
Output: <nil> false 123 123 123 123 123 123 123 123 123 123 123 1.2 1.2 1.2 abc 123 123 123 1s 2s 2021-04-10T12:56:28Z 2021-04-10T12:56:28Z true 456 2021-04-10T12:56:28Z 3s
func SplitHostPort ¶
SplitHostPort separates host and port. If the port is not valid, it returns the entire input as host, and it doesn't check the validity of the host. Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric.
Example ¶
var host, port string host, port = SplitHostPort("www.example.com") fmt.Printf("Host: %s, Port: %s#\n", host, port) host, port = SplitHostPort("www.example.com:80") fmt.Printf("Host: %s, Port: %s#\n", host, port) host, port = SplitHostPort(":80") fmt.Printf("Host: %s, Port: %s#\n", host, port) host, port = SplitHostPort("1.2.3.4:80") fmt.Printf("Host: %s, Port: %s#\n", host, port) host, port = SplitHostPort("[fe80::1122:3344:5566:7788]") fmt.Printf("Host: %s, Port: %s#\n", host, port) host, port = SplitHostPort("[fe80::1122:3344:5566:7788]:80") fmt.Printf("Host: %s, Port: %s#\n", host, port)
Output: Host: www.example.com, Port: # Host: www.example.com, Port: 80# Host: , Port: 80# Host: 1.2.3.4, Port: 80# Host: fe80::1122:3344:5566:7788, Port: # Host: fe80::1122:3344:5566:7788, Port: 80#
Types ¶
type Binder ¶
type Binder interface { // Bind parses the data from http.Request to v. // // Notice: v must be a non-nil pointer. Bind(req *http.Request, v interface{}) error }
Binder is the interface to bind the value to v from ctx.
func BinderFunc ¶
BinderFunc converts a function to Binder.
func FormBinder ¶
FormBinder returns a Form binder to bind the Form request.
Notice: The bound value must be a pointer to a struct with the tag named tag, which is "form" by default.
func JSONBinder ¶
func JSONBinder() Binder
JSONBinder returns a JSON binder to bind the JSON request.
func QueryBinder ¶
QueryBinder returns a query binder to bind the query parameters..
Notice: The bound value must be a pointer to a struct with the tag named tag, which is "query" by default.
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 // Data is used to store many key-value pairs about the context. // // Data maybe asks the system to allocate many memories. In order // to avoid it and if the interim context values is too few, // the context also defines three variables to resolve it. // // 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 it can be used 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 ¶
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) 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) Header ¶
Header is the alias of RespHeader to implement the interface http.ResponseWriter.
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 ¶
SetDefault calls the default setter to set the default value of v.
func (*Context) SetDefaulter ¶
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 ¶
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) 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) URLPath ¶
URLPath generates a url path by the route path name and provided parameters.
Return "" if there is not the route named name.
func (*Context) Write ¶
Write writes the content to the peer, which implements the interface http.ResponseWriter.
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, which implements the interface http.ResponseWriter.
type HTTPClientError ¶
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 ¶
func NewHTTPClientError(method, url string, code int, err error, data ...string) HTTPClientError
NewHTTPClientError returns a new HTTPClientError.
func (HTTPClientError) Error ¶
func (e HTTPClientError) Error() string
func (HTTPClientError) String ¶
func (e HTTPClientError) String() string
func (HTTPClientError) Unwrap ¶
func (e HTTPClientError) Unwrap() error
type HTTPServerError ¶
HTTPServerError represents a server error with HTTP Status Code.
func NewHTTPServerError ¶
func NewHTTPServerError(code int, msg ...string) HTTPServerError
NewHTTPServerError returns a new HTTPServerError.
func (HTTPServerError) Error ¶
func (e HTTPServerError) Error() string
func (HTTPServerError) New ¶
func (e HTTPServerError) New(err error) HTTPServerError
New returns a new HTTPError with the new error.
func (HTTPServerError) NewCT ¶
func (e HTTPServerError) NewCT(ct string) HTTPServerError
NewCT returns a new HTTPError with the new ContentType ct.
func (HTTPServerError) Newf ¶
func (e HTTPServerError) Newf(msg string, args ...interface{}) HTTPServerError
Newf is equal to New(fmt.Errorf(msg, args...)).
func (HTTPServerError) Unwrap ¶
func (e HTTPServerError) Unwrap() error
Unwrap unwraps the inner error.
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 ¶
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 MuxBinder ¶
type MuxBinder struct {
// contains filtered or unexported fields
}
MuxBinder is a multiplexer for kinds of Binders based on the Content-Type.
func (*MuxBinder) Bind ¶
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 ¶
type MuxRenderer struct {
// contains filtered or unexported fields
}
MuxRenderer is a multiplexer for kinds of Renderers.
func (*MuxRenderer) Add ¶
func (mr *MuxRenderer) Add(suffix string, renderer Renderer)
Add adds a renderer with a suffix identifier.
func (*MuxRenderer) Del ¶
func (mr *MuxRenderer) Del(suffix string)
Del removes the corresponding renderer by the suffix.
func (*MuxRenderer) Get ¶
func (mr *MuxRenderer) Get(suffix string) Renderer
Get returns the corresponding renderer by the suffix.
Return nil if not found.
func (*MuxRenderer) Render ¶
func (mr *MuxRenderer) Render(w http.ResponseWriter, name string, code int, data interface{}) error
Render implements the interface Renderer, which will get the renderer the name suffix then render the content.
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 RWLocker ¶
RWLocker represents an object that can be locked and unlocked with read and write.
func NewNoopRWLocker ¶
func NewNoopRWLocker() RWLocker
NewNoopRWLocker returns a No-Op RLocker, which does nothing.
type RegexpHostRouter ¶
type RegexpHostRouter interface { // Len returns the number of the regexp host routers. Len() int // Range is used to traverse all the regexp host routers. Range(func(regexpHost string, 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, error) // Del deletes and returns the regexp host router. // // If the regexp host router does not exist, return nil. Del(regexpHost string) Router // Router accurately returns the router by the regexp host. // // If the regexp host router does not exist, return nil. Router(regexpHost string) 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) }
RegexpHostRouter is the manager to match the host by the regular expression.
func NewRegexpHostRouter ¶
func NewRegexpHostRouter() RegexpHostRouter
NewRegexpHostRouter returns a new RegexpHostRouter, which uses the stdlib "regexp" to implement the regular expression syntax of Golang.
For the golang regexp syntax, see https://pkg.go.dev/regexp/syntax.
type Renderer ¶
type Renderer interface {
Render(w http.ResponseWriter, name string, code int, data interface{}) error
}
Renderer is the interface to render the response.
func RendererFunc ¶
RendererFunc converts a function to Renderer.
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, for 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) Method ¶
Method registers the routes with the handler and methods.
It will panic with it if there is an error when adding the routes.
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) 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 registers a set of the routes.
It will panic with it if there is an error when adding the routes.
func (*RouteGroup) Clone ¶
func (g *RouteGroup) Clone() *RouteGroup
Clone clones itself and returns a new one.
func (*RouteGroup) CtxData ¶
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 a set of the registered routes.
It will panic with it if there is an error when deleting the routes.
func (*RouteGroup) Group ¶
func (g *RouteGroup) Group(prefix string, middlewares ...Middleware) *RouteGroup
Group returns a new route 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, which is used to build and register the route.
You should call Route.Method() or its short method to register it.
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 { // The host is used to isolate the routes. And the different host // maybe has the same routes. // // If Host is empty, it represents the default host. Host string `json:"host,omitempty" xml:"host,omitempty"` // Path and Method represent the unique route in a certain host. // // Path maybe contain the parameters, which is determined by the underlying // router. And if Method is empty, it stands for all the methods. Path string `json:"path,omitempty" xml:"path,omitempty"` Method string `json:"method,omitempty" xml:"method,omitempty"` // Name is the name of the path, which may be empty to represent no name. Name string `json:"name,omitempty" xml:"name,omitempty"` // Handler is the handler of the route to handle the request. Handler Handler `json:"-" xml:"-"` // CtxData is any additional context data, which is passed to the handler // and it can be accessed by Context.RouteInfo.CtxData in the handler. CtxData interface{} `json:"ctxdata,omitempty" xml:"ctxdata,omitempty"` }
RouteInfo is used to represent the information of the registered 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 Session ¶
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 ¶
func NewMemorySession() Session
NewMemorySession return a Session implementation based on the memory.
type Ship ¶
type Ship struct { *Runner // Lock is used to access the host routers concurrently and thread-safely. // // Notice: It doesn't ensure that it's safe to access the routes // in a certain router concurrently and thread-safely. // But you maybe use the locked Router, such as router.LockRouter. // // Default: NewNoopRWLocker() Lock RWLocker // The initialization capacity of Context.Data. // // Default: 0 CtxDataInitCap int // The maximum number of the url paramters of the route. // // Default: 4 URLParamMaxNum 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 // 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 // RouterExecutor is the router 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. RouterExecutor 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. Session Session // Default: NewMemorySession() Logger Logger // Default: NewLoggerFromWriter(os.Stderr, "") Binder Binder // Default: nil Renderer Renderer // Default: nil Responder func(c *Context, args ...interface{}) error // Default: nil BindQuery func(interface{}, url.Values) error // Default: 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 ¶
AddHost adds the router with the host and returns it if it does not exist; or, do nothing and return the existed router.
If router is nil, new one firstly.
func (*Ship) AddRoutes ¶
AddRoutes registers a set of the routes.
It will panic with it if there is an error when adding the routes.
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) DelHost ¶
DelHost deletes the host router.
If the host is empty or the host router does not exist, do nothing.
func (*Ship) DelRoute ¶
DelRoute deletes the registered route, which only uses "Host", "Path" and "Method", and others are ignored.
If Method is empty, deletes all the routes associated with the path.
If the route does not exist, do nothing and return nil.
func (*Ship) DelRoutes ¶
DelRoutes deletes a set of the registered routes.
It will panic with it if there is an error when deleting the routes.
func (*Ship) GetDefaultRouter ¶
GetDefaultRouter returns the default host domain and router.
For the default default router, the host is "".
func (*Ship) Group ¶
func (s *Ship) Group(prefix string) *RouteGroup
Group returns a new route sub-group with the group prefix.
func (*Ship) Host ¶
func (s *Ship) Host(host string) *RouteGroup
Host returns a new route 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 ¶
func (s *Ship) ResetMiddlewares(mdws ...Middleware) *Ship
ResetMiddlewares resets the global middlewares to mdws.
func (*Ship) ResetPreMiddlewares ¶
func (s *Ship) ResetPreMiddlewares(mdws ...Middleware) *Ship
ResetPreMiddlewares resets the global pre-middlewares to mdws.
func (*Ship) Route ¶
Route returns a new route, which is used to build and register the route.
You should call Route.Method() or its short method to register it.
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 ¶
SetDefaultRouter resets the default router with the host domain. If the router is nil, it lookups the router by the host, and uses the default host router instead if failing to lookup it.
When matching the route, if no host router matches the request host, the default router will be used to find the route to handle the request.
func (*Ship) SetNewRegexpHostRouter ¶
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) 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. |
render
|
|
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. |