Documentation ¶
Overview ¶
Example ¶
package main import ( "errors" "fmt" "github.com/teambition/gear" "github.com/teambition/gear/middleware" ) func main() { // Create app app := gear.New() // 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 == "" { ctx.Status(400) return errors.New("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 == "" { ctx.Status(400) return errors.New("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 == "" { ctx.Status(400) return errors.New("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
- Variables
- type Context
- func (ctx *Context) After(hook Hook)
- func (ctx *Context) Attachment(name string, content io.ReadSeeker) error
- func (ctx *Context) Body(str string)
- 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)
- func (ctx *Context) Err() error
- func (ctx *Context) Error(err HTTPError)
- 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) IsEnded() bool
- 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) error
- func (ctx *Context) Render(code int, name string, data interface{}) (err error)
- func (ctx *Context) Reset(w http.ResponseWriter, req *http.Request)
- func (ctx *Context) Set(key, value string)
- func (ctx *Context) SetCookie(cookie *http.Cookie)
- func (ctx *Context) SetValue(key, val interface{})
- func (ctx *Context) Status(code int)
- func (ctx *Context) Stream(code int, contentType string, r io.Reader) (err error)
- func (ctx *Context) String() 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 Error
- type Gear
- type HTTPError
- type Handler
- type Hook
- type Middleware
- type Renderer
- type Response
- type Router
- func (r *Router) Del(pattern string, handle Middleware)
- 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 ServerBG
Examples ¶
Constants ¶
const ( MIMEApplicationJSON = "application/json" MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8 MIMEApplicationJavaScript = "application/javascript" MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8 MIMEApplicationXML = "application/xml" MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + 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 ( HeaderAcceptEncoding = "Accept-Encoding" HeaderAllow = "Allow" HeaderAuthorization = "Authorization" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLength = "Content-Length" HeaderContentType = "Content-Type" HeaderCookie = "Cookie" HeaderSetCookie = "Set-Cookie" HeaderIfModifiedSince = "If-Modified-Since" HeaderLastModified = "Last-Modified" HeaderLocation = "Location" HeaderUpgrade = "Upgrade" HeaderVary = "Vary" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" HeaderXForwardedFor = "X-Forwarded-For" HeaderXRealIP = "X-Real-IP" HeaderServer = "Server" HeaderOrigin = "Origin" 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" 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
const Version = "v0.5.0"
Version is Gear's version
Variables ¶
var ( GearParamsKey = &contextKey{"Gear-Params-Key"} GearLogsKey = &contextKey{"Gear-Logs-Key"} )
Gear global values
Functions ¶
This section is empty.
Types ¶
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. It is useful for testing a middleware.
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.
func (*Context) Cancel ¶
func (ctx *Context) Cancel()
Cancel cancel the ctx and all it' children context
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 string body and status code optionally. After it's called, the rest of middleware handles will not run. But the registered hook on the ctx will run.
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.
func (*Context) JSONBlob ¶
JSONBlob set a JSON blob body with status code to response. It will end the ctx.
func (*Context) JSONP ¶
JSONP sends a JSONP response with status code. It uses `callback` to construct the JSONP payload. It will end the ctx.
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.
func (*Context) Render ¶
Render renders a template with data and sends a text/html response with status code. Templates can be registered using `app.SetRenderer()`. It will end the ctx.
func (*Context) Reset ¶ added in v0.5.0
func (ctx *Context) Reset(w http.ResponseWriter, req *http.Request)
Reset initializes the ctx with http.ResponseWriter and http.Request.
func (*Context) SetValue ¶
func (ctx *Context) SetValue(key, val interface{})
SetValue save a key and value to the ctx.
func (*Context) Stream ¶
Stream sends a streaming response with status code and content type. It will end the ctx.
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.
type Error ¶ added in v0.3.0
type Error struct { Code int // contains filtered or unexported fields }
Error is error struct that implemented HTTPError
type Gear ¶
type Gear struct { // OnError is default ctx error handler. // Override it for your business logic. OnError func(*Context, error) HTTPError Renderer Renderer // ErrorLog specifies an optional logger for app's errors. Default to nil ErrorLog *log.Logger Server *http.Server // contains filtered or unexported fields }
Gear is the top-level framework app instance.
func (*Gear) StartBG ¶ added in v0.2.0
StartBG starts a background app instance. It is useful for testing. The background app instance must close by ServerBG.Close().
func (*Gear) UseHandler ¶
UseHandler uses a instance that implemented Handler interface.
type Middleware ¶
Middleware defines a function to process middleware.
func WrapHandler ¶ added in v0.3.0
func WrapHandler(h http.Handler) Middleware
WrapHandler wrap a http.Handler to Gear Middleware
func WrapHandlerFunc ¶ added in v0.3.0
func WrapHandlerFunc(h 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) 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 { // If enabled, the router automatically replies to OPTIONS requests. // Default to true HandleOPTIONS bool // If enabled, the router automatically replies to OPTIONS requests. // Default to true IsEndpoint bool // 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
func (*Router) Del ¶
func (r *Router) Del(pattern string, handle Middleware)
Del registers a new DELETE route for a path with matching handler in the router.
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.
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 handler in the router.
type ServerBG ¶ added in v0.2.0
type ServerBG struct {
// contains filtered or unexported fields
}
ServerBG is a server returned by a background app instance.