Documentation ¶
Overview ¶
Example ¶
package main import ( "fmt" "os" "github.com/teambition/gear" "github.com/teambition/gear/middleware" ) func main() { // Create app app := gear.New() // Use a default logger middleware logger := &middleware.DefaultLogger{W: os.Stdout} app.Use(middleware.NewLogger(logger)) // Add a static middleware // http://localhost:3000/middleware/static.go app.Use(middleware.NewStatic(middleware.StaticOptions{ Root: "./middleware", Prefix: "/middleware", StripPrefix: true, })) // Add some middleware to app app.Use(func(ctx *gear.Context) (err error) { // fmt.Println(ctx.IP(), ctx.Method, ctx.Path // Do something... // Add after hook to the ctx ctx.After(func(ctx *gear.Context) { // Do something in after hook fmt.Println("After hook") }) return }) // Create views router ViewRouter := gear.NewRouter("", true) // "http://localhost:3000" ViewRouter.Get("/", func(ctx *gear.Context) error { return ctx.HTML(200, "<h1>Hello, Gear!</h1>") }) // "http://localhost:3000/view/abc" // "http://localhost:3000/view/123" ViewRouter.Get("/view/:view", func(ctx *gear.Context) error { view := ctx.Param("view") if view == "" { return &gear.Error{Code: 400, Msg: "Invalid view"} } return ctx.HTML(200, "View: "+view) }) // "http://localhost:3000/abc" // "http://localhost:3000/abc/efg" ViewRouter.Get("/:others*", func(ctx *gear.Context) error { others := ctx.Param("others") if others == "" { return &gear.Error{Code: 400, Msg: "Invalid path"} } return ctx.HTML(200, "Request path: /"+others) }) // Create API router APIRouter := gear.NewRouter("/api", true) // "http://localhost:3000/api/user/abc" // "http://localhost:3000/abc/user/123" APIRouter.Get("/user/:id", func(ctx *gear.Context) error { id := ctx.Param("id") if id == "" { return &gear.Error{Code: 400, Msg: "Invalid user id"} } return ctx.JSON(200, map[string]string{ "Method": ctx.Method, "Path": ctx.Path, "UserID": id, }) }) // Must add APIRouter first. app.UseHandler(APIRouter) app.UseHandler(ViewRouter) // Start app at 3000 app.Error(app.Listen(":3000")) }
Output:
Index ¶
- Constants
- func NewAppError(err string) error
- type Any
- type App
- func (app *App) Error(err error)
- func (app *App) Listen(addr string) error
- func (app *App) ListenTLS(addr, certFile, keyFile string) error
- func (app *App) Set(setting string, val interface{})
- func (app *App) Start(addr ...string) *ServerListener
- func (app *App) Use(handle Middleware)
- func (app *App) UseHandler(h Handler)
- type Compress
- type Context
- func (ctx *Context) After(hook Hook)
- func (ctx *Context) Any(any interface{}) (val interface{}, err error)
- func (ctx *Context) Attachment(name string, content io.ReadSeeker) error
- func (ctx *Context) Cancel()
- func (ctx *Context) Cookie(name string) (*http.Cookie, error)
- func (ctx *Context) Cookies() []*http.Cookie
- func (ctx *Context) Deadline() (time.Time, bool)
- func (ctx *Context) Done() <-chan struct{}
- func (ctx *Context) End(code int, buf ...[]byte) (err error)
- func (ctx *Context) Err() error
- func (ctx *Context) Error(e error) (err error)
- func (ctx *Context) Get(key string) string
- func (ctx *Context) HTML(code int, str string) error
- func (ctx *Context) IP() string
- func (ctx *Context) Inline(name string, content io.ReadSeeker) error
- func (ctx *Context) JSON(code int, val interface{}) error
- func (ctx *Context) JSONBlob(code int, buf []byte) error
- func (ctx *Context) JSONP(code int, callback string, val interface{}) error
- func (ctx *Context) JSONPBlob(code int, callback string, buf []byte) error
- func (ctx *Context) OnEnd(hook Hook)
- func (ctx *Context) Param(key string) (val string)
- func (ctx *Context) Query(name string) string
- func (ctx *Context) Redirect(code int, url string) (err error)
- func (ctx *Context) Render(code int, name string, data interface{}) (err error)
- func (ctx *Context) Set(key, value string)
- func (ctx *Context) SetAny(key, val interface{})
- func (ctx *Context) SetCookie(cookie *http.Cookie)
- func (ctx *Context) Setting(key string) interface{}
- func (ctx *Context) Status(code int)
- func (ctx *Context) Stream(code int, contentType string, r io.Reader) (err error)
- func (ctx *Context) String(str string)
- func (ctx *Context) Type(str string)
- func (ctx *Context) Value(key interface{}) (val interface{})
- func (ctx *Context) WithCancel() (context.Context, context.CancelFunc)
- func (ctx *Context) WithDeadline(deadline time.Time) (context.Context, context.CancelFunc)
- func (ctx *Context) WithTimeout(timeout time.Duration) (context.Context, context.CancelFunc)
- func (ctx *Context) WithValue(key, val interface{}) context.Context
- func (ctx *Context) XML(code int, val interface{}) error
- func (ctx *Context) XMLBlob(code int, buf []byte) error
- type DefaultCompress
- type DefaultOnError
- type Error
- type HTTPError
- type Handler
- type Hook
- type Middleware
- type OnError
- type Renderer
- type Response
- func (r *Response) Add(key, value string)
- func (r *Response) Del(key string)
- func (r *Response) Get(key string) string
- func (r *Response) Header() http.Header
- func (r *Response) HeaderWrote() bool
- func (r *Response) Set(key, value string)
- func (r *Response) Write(buf []byte) (int, error)
- func (r *Response) WriteHeader(code int)
- type Router
- func (r *Router) Delete(pattern string, handle Middleware)
- func (r *Router) Get(pattern string, handle Middleware)
- func (r *Router) Handle(method, pattern string, handle Middleware)
- func (r *Router) Head(pattern string, handle Middleware)
- func (r *Router) Options(pattern string, handle Middleware)
- func (r *Router) Otherwise(handle Middleware)
- func (r *Router) Patch(pattern string, handle Middleware)
- func (r *Router) Post(pattern string, handle Middleware)
- func (r *Router) Put(pattern string, handle Middleware)
- func (r *Router) Serve(ctx *Context) error
- func (r *Router) Use(handle Middleware)
- type ServerListener
Examples ¶
Constants ¶
const ( // Got from https://github.com/labstack/echo MIMEApplicationJSON = "application/json" MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8" MIMEApplicationJavaScript = "application/javascript" MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8" MIMEApplicationXML = "application/xml" MIMEApplicationXMLCharsetUTF8 = "application/xml; charset=utf-8" MIMEApplicationForm = "application/x-www-form-urlencoded" MIMEApplicationProtobuf = "application/protobuf" MIMEApplicationMsgpack = "application/msgpack" MIMETextHTML = "text/html" MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8" MIMETextPlain = "text/plain" MIMETextPlainCharsetUTF8 = "text/plain; charset=utf-8" MIMEMultipartForm = "multipart/form-data" MIMEOctetStream = "application/octet-stream" )
MIME types
const ( HeaderAccept = "Accept" // Requests, Responses HeaderAcceptCharset = "Accept-Charset" // Requests HeaderAcceptEncoding = "Accept-Encoding" // Requests HeaderAcceptLanguage = "Accept-Language" // Requests HeaderAuthorization = "Authorization" // Requests HeaderCacheControl = "Cache-Control" // Requests, Responses HeaderContentLength = "Content-Length" // Requests, Responses HeaderContentMD5 = "Content-MD5" // Requests, Responses HeaderContentType = "Content-Type" // Requests, Responses HeaderIfMatch = "If-Match" // Requests HeaderIfModifiedSince = "If-Modified-Since" // Requests HeaderIfNoneMatch = "If-None-Match" // Requests HeaderIfRange = "If-Range" // Requests HeaderIfUnmodifiedSince = "If-Unmodified-Since" // Requests HeaderMaxForwards = "Max-Forwards" // Requests HeaderProxyAuthorization = "Proxy-Authorization" // Requests HeaderPragma = "Pragma" // Requests, Responses HeaderRange = "Range" // Requests HeaderReferer = "Referer" // Requests HeaderUserAgent = "User-Agent" // Requests HeaderTE = "TE" // Requests HeaderVia = "Via" // Requests HeaderWarning = "Warning" // Requests, Responses HeaderCookie = "Cookie" // Requests HeaderOrigin = "Origin" // Requests HeaderAcceptDatetime = "Accept-Datetime" // Requests HeaderXRequestedWith = "X-Requested-With" // Requests HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" // Responses HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" // Responses HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" // Responses HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" // Responses HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" // Responses HeaderAccessControlMaxAge = "Access-Control-Max-Age" // Responses HeaderAccessControlRequestMethod = "Access-Control-Request-Method" // Responses HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" // Responses HeaderAcceptPatch = "Accept-Patch" // Responses HeaderAcceptRanges = "Accept-Ranges" // Responses HeaderAllow = "Allow" // Responses HeaderContentEncoding = "Content-Encoding" // Responses HeaderContentLanguage = "Content-Language" // Responses HeaderContentLocation = "Content-Location" // Responses HeaderContentDisposition = "Content-Disposition" // Responses HeaderContentRange = "Content-Range" // Responses HeaderETag = "ETag" // Responses HeaderExpires = "Expires" // Responses HeaderLastModified = "Last-Modified" // Responses HeaderLink = "Link" // Responses HeaderLocation = "Location" // Responses HeaderP3P = "P3P" // Responses HeaderProxyAuthenticate = "Proxy-Authenticate" // Responses HeaderRefresh = "Refresh" // Responses HeaderRetryAfter = "Retry-After" // Responses HeaderServer = "Server" // Responses HeaderSetCookie = "Set-Cookie" // Responses HeaderStrictTransportSecurity = "Strict-Transport-Security" // Responses HeaderTransferEncoding = "Transfer-Encoding" // Responses HeaderUpgrade = "Upgrade" // Responses HeaderVary = "Vary" // Responses HeaderWWWAuthenticate = "WWW-Authenticate" // Responses // Common Non-Standard Response Headers HeaderXFrameOptions = "X-Frame-Options" // Responses HeaderXXSSProtection = "X-XSS-Protection" // Responses HeaderContentSecurityPolicy = "Content-Security-Policy" // Responses HeaderXContentSecurityPolicy = "X-Content-Security-Policy" // Responses HeaderXWebKitCSP = "X-WebKit-CSP" // Responses HeaderXContentTypeOptions = "X-Content-Type-Options" // Responses HeaderXPoweredBy = "X-Powered-By" // Responses HeaderXUACompatible = "X-UA-Compatible" // Responses HeaderXForwardedProto = "X-Forwarded-Proto" // Responses HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" // Responses HeaderXForwardedFor = "X-Forwarded-For" // Responses HeaderXRealIP = "X-Real-IP" // Responses HeaderXCSRFToken = "X-CSRF-Token" // Responses )
HTTP Header Fields
const Version = "v0.14.1"
Version is Gear's version
Variables ¶
This section is empty.
Functions ¶
func NewAppError ¶ added in v0.7.0
NewAppError create a error instance with "App " prefix.
Types ¶
type App ¶ added in v0.11.0
App is the top-level framework app instance.
Hello Gear!
package main import "github.com/teambition/gear" func main() { app := gear.New() // Create app app.Use(gear.NewDefaultLogger()) app.Use(func(ctx *gear.Context) error { return ctx.HTML(200, "<h1>Hello, Gear!</h1>") }) app.Error(app.Listen(":3000")) }
func (*App) Set ¶ added in v0.12.0
Set add app settings. The settings can be retrieved by ctx.Setting. There are 4 build-in app settings:
app.Set("AppOnError", val gear.OnError) // Default to gear.DefaultOnError app.Set("AppRenderer", val gear.Renderer) // No default app.Set("AppLogger", val *log.Logger) // No default app.Set("AppCompress", val gear.Compress) // Enable to compress response content. app.Set("AppEnv", val string) // Default to "development"
func (*App) Start ¶ added in v0.11.0
func (app *App) Start(addr ...string) *ServerListener
Start starts a non-blocking app instance. It is useful for testing. If addr omit, the app will listen on a random addr, use ServerListener.Addr() to get it. The non-blocking app instance must close by ServerListener.Close().
func (*App) Use ¶ added in v0.11.0
func (app *App) Use(handle Middleware)
Use uses the given middleware `handle`.
func (*App) UseHandler ¶ added in v0.11.0
UseHandler uses a instance that implemented Handler interface.
type Compress ¶ added in v0.14.0
type Compress interface { // Compressible checks the response content type to decide whether to compress. Compressible(contentType string) bool // Threshold return the minimun response size in bytes to compress. // Default value is 1024 (1 kb). Threshold() int }
Compress interface is use to enable compress response context.
type Context ¶
type Context struct { Req *http.Request Res *Response Host string Method string Path string // contains filtered or unexported fields }
Context represents the context of the current HTTP request. It holds request and response objects, path, path parameters, data, registered handler and content.Context.
func NewContext ¶ added in v0.5.0
NewContext creates an instance of Context. Export for testing middleware.
func (*Context) After ¶
After add a "after hook" to the ctx that will run after middleware process, but before Response.WriteHeader.
func (*Context) Any ¶ added in v0.10.0
Any returns the value on this ctx for key. If key is instance of Any and value not set, any.New will be called to eval the value, and then set to the ctx. if any.New returns error, the value will not be set.
// create some Any type for your project. type someAnyType struct{} type someAnyResult struct { r *http.Request } var someAnyKey = &someAnyType{} func (t *someAnyType) New(ctx *gear.Context) (interface{}, error) { return &someAnyResult{r: ctx.Req}, nil } // use it in app if val, err := ctx.Any(someAnyKey); err == nil { res := val.(*someAnyResult) }
func (*Context) Attachment ¶
func (ctx *Context) Attachment(name string, content io.ReadSeeker) error
Attachment sends a response from `io.ReaderSeeker` as attachment, prompting client to save the file. It will end the ctx. The middlewares after current middleware will not run. "after hooks" and "end hooks" will run normally. Note that this will not stop the current handler.
func (*Context) Cancel ¶
func (ctx *Context) Cancel()
Cancel cancel the ctx and all it' children context. The ctx' process will ended too.
func (*Context) Deadline ¶ added in v0.5.0
Deadline returns the time when work done on behalf of this context should be canceled.
func (*Context) Done ¶ added in v0.5.0
func (ctx *Context) Done() <-chan struct{}
Done returns a channel that's closed when work done on behalf of this context should be canceled.
func (*Context) End ¶
End end the ctx with bytes and status code optionally. After it's called, the rest of middleware handles will not run. But "after hooks" and "end hooks" will run normally. Note that this will not stop the current handler.
func (*Context) Error ¶
Error send a error message with status code to response. It will end the ctx. The middlewares after current middleware and "after hooks" will not run. "end hooks" will run normally. Note that this will not stop the current handler.
func (*Context) HTML ¶
HTML set an Html body with status code to response. It will end the ctx. The middlewares after current middleware will not run. "after hooks" and "end hooks" will run normally. Note that this will not stop the current handler.
func (*Context) IP ¶
IP returns the client's network address based on `X-Forwarded-For` or `X-Real-IP` request header.
func (*Context) Inline ¶
func (ctx *Context) Inline(name string, content io.ReadSeeker) error
Inline sends a response from `io.ReaderSeeker` as inline, opening the file in the browser. It will end the ctx. The middlewares after current middleware will not run. "after hooks" and "end hooks" will run normally. Note that this will not stop the current handler.
func (*Context) JSON ¶
JSON set a JSON body with status code to response. It will end the ctx. The middlewares after current middleware will not run. "after hooks" (if no error) and "end hooks" will run normally. Note that this will not stop the current handler.
func (*Context) JSONBlob ¶
JSONBlob set a JSON blob body with status code to response. It will end the ctx. The middlewares after current middleware will not run. "after hooks" and "end hooks" will run normally. Note that this will not stop the current handler.
func (*Context) JSONP ¶
JSONP sends a JSONP response with status code. It uses `callback` to construct the JSONP payload. It will end the ctx. The middlewares after current middleware will not run. "after hooks" (if no error) and "end hooks" will run normally. Note that this will not stop the current handler.
func (*Context) JSONPBlob ¶
JSONPBlob sends a JSONP blob response with status code. It uses `callback` to construct the JSONP payload. It will end the ctx. The middlewares after current middleware will not run. "after hooks" and "end hooks" will run normally. Note that this will not stop the current handler.
func (*Context) Redirect ¶
Redirect redirects the request with status code. It will end the ctx. The middlewares after current middleware will not run. "after hooks" and "end hooks" will run normally. Note that this will not stop the current handler.
func (*Context) Render ¶
Render renders a template with data and sends a text/html response with status code. Templates can be registered using `app.Renderer = Renderer`. It will end the ctx. The middlewares after current middleware will not run. "after hooks" (if no error) and "end hooks" will run normally. Note that this will not stop the current handler.
func (*Context) SetAny ¶ added in v0.10.0
func (ctx *Context) SetAny(key, val interface{})
SetAny save a key, value pair on the ctx. logger middleware used ctx.SetAny and ctx.Any to implement FromCtx:
func (logger *DefaultLogger) FromCtx(ctx *gear.Context) Log { if any, err := ctx.Any(logger); err == nil { return any.(Log) } log := Log{} ctx.SetAny(logger, log) log["IP"] = ctx.IP() log["Method"] = ctx.Method log["URL"] = ctx.Req.URL.String() log["Start"] = time.Now() return log }
func (*Context) Setting ¶ added in v0.12.0
Setting returns App's settings by key
fmt.Println(ctx.Setting("AppEnv").(string) == "development") app.Set("AppEnv", "production") fmt.Println(ctx.Setting("AppEnv").(string) == "production")
func (*Context) Stream ¶
Stream sends a streaming response with status code and content type. It will end the ctx. The middlewares after current middleware will not run. "after hooks" and "end hooks" will run normally. Note that this will not stop the current handler.
func (*Context) Value ¶ added in v0.5.0
func (ctx *Context) Value(key interface{}) (val interface{})
Value returns the value associated with this context for key, or nil if no value is associated with key. Successive calls to Value with the same key returns the same result.
func (*Context) WithCancel ¶
func (ctx *Context) WithCancel() (context.Context, context.CancelFunc)
WithCancel returns a copy of the ctx with a new Done channel. The returned context's Done channel is closed when the returned cancel function is called or when the parent context's Done channel is closed, whichever happens first.
func (*Context) WithDeadline ¶
WithDeadline returns a copy of the ctx with the deadline adjusted to be no later than d.
func (*Context) WithTimeout ¶
WithTimeout returns WithDeadline(time.Now().Add(timeout)).
func (*Context) WithValue ¶
WithValue returns a copy of the ctx in which the value associated with key is val.
func (*Context) XML ¶
XML set an XML body with status code to response. It will end the ctx. The middlewares after current middleware will not run. "after hooks" (if no error) and "end hooks" will run normally. Note that this will not stop the current handler.
type DefaultCompress ¶ added in v0.14.0
type DefaultCompress struct{}
DefaultCompress is defalut Compress implemented. Use it to enable compress:
app.Set("AppCompress", &gear.DefaultCompress{})
func (*DefaultCompress) Compressible ¶ added in v0.14.0
func (d *DefaultCompress) Compressible(contentType string) bool
Compressible implemented Compress interface.
func (*DefaultCompress) Threshold ¶ added in v0.14.0
func (d *DefaultCompress) Threshold() int
Threshold implemented Compress interface.
type DefaultOnError ¶ added in v0.12.0
type DefaultOnError struct{}
DefaultOnError is default ctx error handler.
type Error ¶ added in v0.3.0
Error represents a numeric error with optional meta. It can be used in middleware as a return result.
func ParseError ¶ added in v0.10.0
ParseError parse a error, textproto.Error or HTTPError to *Error
type HTTPError ¶
type HTTPError interface { // Error returns error's message. Error() string // Status returns error's http status code. Status() int }
HTTPError interface is used to create a server error that include status code and error message.
type Middleware ¶
Middleware defines a function to process as middleware.
func WrapHandler ¶ added in v0.3.0
func WrapHandler(handler http.Handler) Middleware
WrapHandler wrap a http.Handler to Gear Middleware
func WrapHandlerFunc ¶ added in v0.3.0
func WrapHandlerFunc(fn http.HandlerFunc) Middleware
WrapHandlerFunc wrap a http.HandlerFunc to Gear Middleware
type Response ¶
type Response struct { Status int // response Status Type string // response Content-Type Body []byte // response Content // contains filtered or unexported fields }
Response wraps an http.ResponseWriter and implements its interface to be used by an HTTP handler to construct an HTTP response.
func (*Response) Add ¶
Add adds the key, value pair to the header. It appends to any existing values associated with key.
func (*Response) Get ¶
Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "". To access multiple values of a key, access the map directly with CanonicalHeaderKey.
func (*Response) HeaderWrote ¶ added in v0.14.0
HeaderWrote indecates that whether the reply header has been (logically) written.
func (*Response) Set ¶
Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key.
func (*Response) WriteHeader ¶
WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router is a tire base HTTP request handler for Gear which can be used to dispatch requests to different handler functions. A trivial example is:
package main import ( "fmt" "github.com/teambition/gear" ) func SomeRouterMiddleware(ctx *gear.Context) error { // do some thing. fmt.Println("Router middleware...") return nil } func ViewHello(ctx *gear.Context) error { return ctx.HTML(200, "<h1>Hello, Gear!</h1>") } func main() { app := gear.New() // Add app middleware app.Use(gear.NewDefaultLogger()) router := gear.NewRouter("", true) router.Use(SomeRouterMiddleware) // Add router middleware, optionally router.Get("/", ViewHello) app.UseHandler(router) app.Error(app.Listen(":3000")) }
The router matches incoming requests by the request method and the path. If a handle is registered for this path and method, the router delegates the request to that function.
The registered path, against which the router matches incoming requests, can contain three types of parameters:
Syntax Type :name named parameter :name* named with catch-all parameter :name(regexp) named with regexp parameter
Named parameters are dynamic path segments. They match anything until the next '/' or the path end:
Path: /api/:type/:ID Requests: /api/user/123 match: type="user", ID="123" /api/user no match /api/user/123/comments no match
Named with catch-all parameters match anything until the path end, including the directory index (the '/' before the catch-all). Since they match anything until the end, catch-all parameters must always be the final path element.
Path: /files/:filepath* Requests: /files no match /files/LICENSE match: filepath="LICENSE" /files/templates/article.html match: filepath="templates/article.html"
Named with regexp parameters match anything using regexp until the next '/' or the path end:
Path: /api/:type/:ID(^\\d+$) Requests: /api/user/123 match: type="user", ID="123" /api/user no match /api/user/abc no match /api/user/123/comments no match
The value of parameters is saved on the gear.Context. Retrieve the value of a parameter by name:
type := ctx.Param("type") id := ctx.Param("ID")
func NewRouter ¶
NewRouter returns a new Router instance with root path and ignoreCase option. Gear support multi-routers. For example:
// Create app app := gear.New() // Create views router viewRouter := gear.NewRouter("", true) viewRouter.Get("/", Ctl.IndexView) // add more ... apiRouter := gear.NewRouter("/api", true) apiRouter.Get("/user/:id", API.User) // add more .. app.UseHandler(apiRouter) // Must add apiRouter first. app.UseHandler(viewRouter) // Start app at 3000 app.Listen(":3000")
func (*Router) Delete ¶
func (r *Router) Delete(pattern string, handle Middleware)
Delete registers a new DELETE route for a path with matching handler in the router.
func (*Router) Get ¶
func (r *Router) Get(pattern string, handle Middleware)
Get registers a new GET route for a path with matching handler in the router.
func (*Router) Handle ¶
func (r *Router) Handle(method, pattern string, handle Middleware)
Handle registers a new Middleware handler with method and path in the router. For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.
This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).
func (*Router) Head ¶
func (r *Router) Head(pattern string, handle Middleware)
Head registers a new HEAD route for a path with matching handler in the router.
func (*Router) Options ¶
func (r *Router) Options(pattern string, handle Middleware)
Options registers a new OPTIONS route for a path with matching handler in the router.
func (*Router) Otherwise ¶
func (r *Router) Otherwise(handle Middleware)
Otherwise registers a new Middleware handler in the router that will run if there is no other handler matching.
func (*Router) Patch ¶
func (r *Router) Patch(pattern string, handle Middleware)
Patch registers a new PATCH route for a path with matching handler in the router.
func (*Router) Post ¶
func (r *Router) Post(pattern string, handle Middleware)
Post registers a new POST route for a path with matching handler in the router.
func (*Router) Put ¶
func (r *Router) Put(pattern string, handle Middleware)
Put registers a new PUT route for a path with matching handler in the router.
func (*Router) Use ¶
func (r *Router) Use(handle Middleware)
Use registers a new Middleware in the router, that will be called when router mathed.
type ServerListener ¶ added in v0.6.0
type ServerListener struct {
// contains filtered or unexported fields
}
ServerListener is returned by a non-blocking app instance.
func (*ServerListener) Addr ¶ added in v0.6.0
func (s *ServerListener) Addr() net.Addr
Addr returns the non-blocking app instance addr.
func (*ServerListener) Close ¶ added in v0.6.0
func (s *ServerListener) Close() error
Close closes the non-blocking app instance.
func (*ServerListener) Wait ¶ added in v0.6.0
func (s *ServerListener) Wait() error
Wait make the non-blocking app instance blocking.