Documentation ¶
Overview ¶
Example ¶
package main import ( "errors" "fmt" "github.com/teambition/gear" "github.com/teambition/gear/middleware" ) func main() { // Create app app := gear.New() // Use a default logger middleware app.Use(gear.NewDefaultLogger()) // 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
- func ColorMethod(method string) string
- func ColorStatus(code int) string
- func ColorString(code int, str string) string
- func NewAppError(err string) error
- func NewError(err error, code int) *textproto.Error
- type Context
- func (ctx *Context) After(hook Hook)
- 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)
- func (ctx *Context) Err() error
- func (ctx *Context) Error(err *textproto.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) 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(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 DefaultLogger
- type Gear
- type Handler
- type Hook
- type Log
- type Logger
- 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 ServerListener
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 ( ColorCodeRed = 31 ColorCodeGreen = 32 ColorCodeYellow = 33 ColorCodeBlue = 34 ColorCodeMagenta = 35 ColorCodeCyan = 36 ColorCodeWhite = 37 ColorCodeGray = 90 )
Color Code https://en.wikipedia.org/wiki/ANSI_escape_code 30–37: set text color to one of the colors 0 to 7, 40–47: set background color to one of the colors 0 to 7, 39: reset text color to default, 49: reset background color to default, 1: make text bold / bright (this is the standard way to access the bright color variants), 22: turn off bold / bright effect, and 0: reset all text properties (color, background, brightness, etc.) to their default values. For example, one could select bright purple text on a green background (eww!) with the code `\x1B[35;1;42m`
const Version = "v0.7.0"
Version is Gear's version
Variables ¶
var ( GearParamsKey = &contextKey{"Gear-Params-Key"} GearLogsKey = &contextKey{"Gear-Logs-Key"} )
Gear global values
Functions ¶
func ColorMethod ¶ added in v0.7.0
ColorMethod convert a HTTP method to a color string.
func ColorStatus ¶ added in v0.7.0
ColorStatus convert a HTTP status code to a color string.
func ColorString ¶ added in v0.7.0
ColorString convert a string to a color string with color code.
func NewAppError ¶ added in v0.7.0
NewAppError create a error instance with "Gear " prefix.
Types ¶
type Context ¶
type Context struct { // Log recodes key-value pairs for logs. See gear.NewLogger Log Log 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. 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 set 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) OnEnd ¶
OnEnd add a "end hook" to the ctx that will run before response.WriteHeader.
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) 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. 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 DefaultLogger ¶ added in v0.7.0
type DefaultLogger struct{}
DefaultLogger is Gear's default logger, useful for development.
func (*DefaultLogger) Format ¶ added in v0.7.0
func (d *DefaultLogger) Format(l Log) string
Format implements Logger interface
func (*DefaultLogger) Init ¶ added in v0.7.0
func (d *DefaultLogger) Init(ctx *Context)
Init implements Logger interface
type Gear ¶
type Gear struct { // OnError is default ctx error handler. // Override it for your business logic. OnError func(*Context, error) *textproto.Error 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) Start ¶ added in v0.6.0
func (g *Gear) 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 (*Gear) UseHandler ¶
UseHandler uses a instance that implemented Handler interface.
type Log ¶ added in v0.7.0
type Log map[string]interface{}
Log represents the key-value pairs for logs.
type Middleware ¶
Middleware defines a function to process middleware.
func NewDefaultLogger ¶ added in v0.7.0
func NewDefaultLogger() Middleware
NewDefaultLogger creates a Gear default logger middleware.
func NewLogger ¶ added in v0.7.0
func NewLogger(w io.Writer, l Logger) Middleware
NewLogger creates a logger middleware with io.Writer and Logger.
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 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.