gear

package module
v0.22.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 6, 2017 License: MIT Imports: 24 Imported by: 0

README

Gear Build Status Coverage Status License GoDoc

===== A lightweight, composable and high performance web service framework for Go.

Demo

package main

import (
	"fmt"
	"os"

	"github.com/teambition/gear"
	"github.com/teambition/gear/logging"
)

func main() {
	app := gear.New()

	// Add logging middleware
	app.UseHandler(logging.Default())

	// Add router middleware
	router := gear.NewRouter()
	router.Use(func(ctx *gear.Context) error {
		// do some thing.
		fmt.Println("Router middleware...", ctx.Path)
		return nil
	})
	router.Get("/", func(ctx *gear.Context) error {
		return ctx.HTML(200, "<h1>Hello, Gear!</h1>")
	})
	app.UseHandler(router)
	app.Error(app.Listen(":3000"))
}

Import

// package gear
import "github.com/teambition/gear"

About Router

gear.Router is a tire base HTTP request handler. Features:

  1. Support regexp
  2. Support multi-router
  3. Support router layer middlewares
  4. Support fixed path automatic redirection
  5. Support trailing slash automatic redirection
  6. Automatic handle 405 Method Not Allowed
  7. Automatic handle 501 Not Implemented
  8. Automatic handle OPTIONS method
  9. Best Performance

The registered path, against which the router matches incoming requests, can contain three types of parameters:

Syntax Description
:name named parameter
:name* named with catch-all parameter
:name(regexp) named with regexp parameter
::name not named parameter, it is literal :name

Named parameters are dynamic path segments. They match anything until the next '/' or the path end:

Defined: /api/:type/:ID

/api/user/123             matched: 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.

Defined: /files/:filepath*

/files                           no match
/files/LICENSE                   matched: filepath="LICENSE"
/files/templates/article.html    matched: filepath="templates/article.html"

Named with regexp parameters match anything using regexp until the next '/' or the path end:

Defined: /api/:type/:ID(^\d+$)

/api/user/123             matched: 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")

About Middleware

// Middleware defines a function to process as middleware.
type Middleware func(*gear.Context) error

Middleware can be used in app layer or router layer or middleware inside. It be good at composition. We should write any module as a middleware. We should use middleware to compose all our business.

There are three build-in middlewares currently: https://godoc.org/github.com/teambition/gear/middleware

// package middleware
import "github.com/teambition/gear/middleware"
  1. Favicon middleware Use to serve favicon.ico.
  2. Static server middleware Use to serve static files.

All this middlewares can be use in app layer, router layer or middleware layer.

About Hook

Hook can be used to some teardowm job dynamically. For example, Logger middleware use ctx.OnEnd to write logs to underlayer. Hooks are executed in LIFO order, just like go defer. Hook can only be add in middleware. You can't add another hook in a hook.

ctx.After(hook func())

Add one or more "after hook" to current request process. They will run after middleware process(means context process ended), and before Response.WriteHeader. If some middleware return error, the middleware process will stop, all "after hooks" will be clear and not run.

ctx.OnEnd(hook func())

Add one or more "end hook" to current request process. They will run after Response.WriteHeader called. The middleware error will not stop "end hook" process.

Here is example using "end hook" in Logger middleware.

func (l *Logger) Serve(ctx *gear.Context) error {
	// Add a "end hook" to flush logs.
	ctx.OnEnd(func() {
		log := l.FromCtx(ctx)
		log["Status"] = ctx.Status()
		log["Type"] = ctx.Res.Get(gear.HeaderContentType)
		log["Length"] = ctx.Res.Get(gear.HeaderContentLength)

		// Don't block current process.
		go l.consume(log, ctx)
	})
	return nil
}

Documentation

https://godoc.org/github.com/teambition/gear

Benchmark

Gear with "net/http": 50030

> wrk 'http://localhost:3333/?foo[bar]=baz' -d 10 -c 100 -t 4

Running 10s test @ http://localhost:3333/?foo[bar]=baz
  4 threads and 100 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     2.22ms    3.91ms 155.60ms   97.49%
    Req/Sec    12.58k     1.26k   18.76k    84.25%
  501031 requests in 10.01s, 65.46MB read
Requests/sec:  50030.72
Transfer/sec:      6.54MB

Iris with "fasthttp": 70310

> wrk 'http://localhost:3333/?foo[bar]=baz' -d 10 -c 100 -t 4

Running 10s test @ http://localhost:3333/?foo[bar]=baz
  4 threads and 100 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     1.37ms  648.31us  15.60ms   89.48%
    Req/Sec    17.75k     2.32k   39.65k    84.83%
  710317 requests in 10.10s, 102.29MB read
Requests/sec:  70310.19
Transfer/sec:     10.13MB

Gin with "net/http": 50195

> wrk 'http://localhost:3333/?foo[bar]=baz' -d 10 -c 100 -t 4

Running 10s test @ http://localhost:3333/?foo[bar]=baz
  4 threads and 100 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     2.07ms    1.50ms  30.44ms   90.04%
    Req/Sec    12.62k     1.12k   15.42k    77.50%
  502815 requests in 10.02s, 65.69MB read
Requests/sec:  50195.68
Transfer/sec:      6.56MB

License

Gear is licensed under the MIT license. Copyright © 2016 Teambition.

Documentation

Overview

Example
package main

import (
	"fmt"

	"github.com/teambition/gear"
	"github.com/teambition/gear/logging"
	"github.com/teambition/gear/middleware/static"
)

func main() {
	// Create app
	app := gear.New()

	// Use a default logger middleware
	app.UseHandler(logging.Default())

	// Add a static middleware
	// http://localhost:3000/middleware/static.go
	app.Use(static.New(static.Options{
		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() {
			// Do something in after hook
			fmt.Println("After hook")
		})
		return
	})

	// Create views router
	ViewRouter := gear.NewRouter()
	// "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(gear.RouterOptions{Root: "/api", IgnoreCase: 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

Examples

Constants

View Source
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

View Source
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

View Source
const Version = "v0.22.0"

Version is Gear's version

Variables

This section is empty.

Functions

func IsStatusCode added in v0.18.0

func IsStatusCode(status int) bool

IsStatusCode returns true if status is HTTP status code. https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

func NewAppError added in v0.7.0

func NewAppError(err string) error

NewAppError create a error instance with "Gear: " prefix.

Types

type Any added in v0.10.0

type Any interface {
	New(ctx *Context) (interface{}, error)
}

Any interface is used by ctx.Any.

type App added in v0.11.0

type App struct {
	Server *http.Server
	// contains filtered or unexported fields
}

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(func(ctx *gear.Context) error {
		return ctx.HTML(200, "<h1>Hello, Gear!</h1>")
	})
	app.Error(app.Listen(":3000"))
}

func New

func New() *App

New creates an instance of App.

func (*App) Error added in v0.11.0

func (app *App) Error(err error)

Error writes error to underlayer logging system (ErrorLog).

func (*App) Listen added in v0.11.0

func (app *App) Listen(addr string) error

Listen starts the HTTP server.

func (*App) ListenTLS added in v0.11.0

func (app *App) ListenTLS(addr, certFile, keyFile string) error

ListenTLS starts the HTTPS server.

func (*App) Set added in v0.12.0

func (app *App) Set(setting string, val interface{})

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("AppTimeout", val time.Duration)     // Default to 0, no timeout
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

func (app *App) UseHandler(h Handler)

UseHandler uses a instance that implemented Handler interface.

type Compressible added in v0.16.5

type Compressible interface {
	// Compressible checks the response Content-Type and Content-Length to
	// determine whether to compress.
	// `length == 0` means response body maybe stream, or will be writed later.
	Compressible(contentType string, contentLength int) bool
}

Compressible 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

func NewContext(app *App, w http.ResponseWriter, req *http.Request) *Context

NewContext creates an instance of Context. Export for testing middleware.

func (*Context) AcceptCharset added in v0.21.0

func (ctx *Context) AcceptCharset(preferred ...string) string

AcceptCharset returns the most preferred charset from the HTTP Accept-Charset header. If nothing accepted, then empty string is returned.

func (*Context) AcceptEncoding added in v0.21.0

func (ctx *Context) AcceptEncoding(preferred ...string) string

AcceptEncoding returns the most preferred encoding from the HTTP Accept-Encoding header. If nothing accepted, then empty string is returned.

func (*Context) AcceptLanguage added in v0.21.0

func (ctx *Context) AcceptLanguage(preferred ...string) string

AcceptLanguage returns the most preferred language from the HTTP Accept-Language header. If nothing accepted, then empty string is returned.

func (*Context) AcceptType added in v0.21.0

func (ctx *Context) AcceptType(preferred ...string) string

AcceptType returns the most preferred content type from the HTTP Accept header. If nothing accepted, then empty string is returned.

func (*Context) After

func (ctx *Context) After(hook func())

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

func (ctx *Context) Any(any interface{}) (val interface{}, err error)

Any returns the value on this ctx by 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, inline ...bool) (err error)

Attachment sends a response from `io.ReaderSeeker` as attachment, prompting client to save the file. If inline is true, the attachment will sends 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) Cancel

func (ctx *Context) Cancel()

Cancel cancel the ctx and all it' children context. The ctx' process will ended too.

func (*Context) Cookie

func (ctx *Context) Cookie(name string) (*http.Cookie, error)

Cookie returns the named cookie provided in the request.

func (*Context) Cookies

func (ctx *Context) Cookies() []*http.Cookie

Cookies returns the HTTP cookies sent with the request.

func (*Context) Deadline added in v0.5.0

func (ctx *Context) Deadline() (time.Time, bool)

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

func (ctx *Context) End(code int, buf ...[]byte) (err error)

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) Err added in v0.5.0

func (ctx *Context) Err() error

Err returns a non-nil error value after Done is closed.

func (*Context) Error

func (ctx *Context) Error(e error) (err error)

Error send a error message with status code to response. It will not reset response headers and not use app.OnError hook 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) Get

func (ctx *Context) Get(key string) string

Get retrieves data from the request Header.

func (*Context) HTML

func (ctx *Context) HTML(code int, str string) error

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

func (ctx *Context) IP() net.IP

IP returns the client's network address based on `X-Forwarded-For` or `X-Real-IP` request header.

func (*Context) JSON

func (ctx *Context) JSON(code int, val interface{}) error

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

func (ctx *Context) JSONBlob(code int, buf []byte) error

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

func (ctx *Context) JSONP(code int, callback string, val interface{}) error

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

func (ctx *Context) JSONPBlob(code int, callback string, buf []byte) error

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

func (ctx *Context) OnEnd(hook func())

OnEnd add a "end hook" to the ctx that will run after Response.WriteHeader.

func (*Context) Param

func (ctx *Context) Param(key string) (val string)

Param returns path parameter by name.

func (*Context) Query

func (ctx *Context) Query(name string) string

Query returns the query param for the provided name.

func (*Context) QueryValues added in v0.15.0

func (ctx *Context) QueryValues(name string) []string

QueryValues returns all query params for the provided name.

func (*Context) Redirect

func (ctx *Context) Redirect(url string) (err error)

Redirect redirects the request with status code 302. You can use other status code with ctx.Status method, It is a wrap of http.Redirect. 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

func (ctx *Context) Render(code int, name string, data interface{}) (err error)

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) Set

func (ctx *Context) Set(key, value string)

Set saves data to the response Header.

func (*Context) SetAny added in v0.10.0

func (ctx *Context) SetAny(key, val interface{})

SetAny save a key, value pair on the ctx. Then we can use ctx.Any(key) to retrieve the value from ctx.

func (*Context) SetCookie

func (ctx *Context) SetCookie(cookie *http.Cookie)

SetCookie adds a `Set-Cookie` header in HTTP response.

func (*Context) Setting added in v0.12.0

func (ctx *Context) Setting(key string) interface{}

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) Status

func (ctx *Context) Status(code ...int) int

Status set a status code (optional) to the response, returns the new status code.

func (*Context) Stream

func (ctx *Context) Stream(code int, contentType string, r io.Reader) (err error)

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) Timing added in v0.16.1

func (ctx *Context) Timing(dt time.Duration, fn func(context.Context) interface{}) (res interface{}, err error)

Timing runs fn with the given time limit. If a call runs for longer than its time limit, it will return context.DeadlineExceeded as error, otherwise return fn's result.

func (*Context) Type

func (ctx *Context) Type(str ...string) string

Type set a content type (optional) to the response, returns the new content type.

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

func (ctx *Context) WithDeadline(deadline time.Time) (context.Context, context.CancelFunc)

WithDeadline returns a copy of the ctx with the deadline adjusted to be no later than d.

func (*Context) WithTimeout

func (ctx *Context) WithTimeout(timeout time.Duration) (context.Context, context.CancelFunc)

WithTimeout returns WithDeadline(time.Now().Add(timeout)).

func (*Context) WithValue

func (ctx *Context) WithValue(key, val interface{}) context.Context

WithValue returns a copy of the ctx in which the value associated with key is val.

func (*Context) XML

func (ctx *Context) XML(code int, val interface{}) error

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.

func (*Context) XMLBlob

func (ctx *Context) XMLBlob(code int, buf []byte) error

XMLBlob set a XML 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.

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, contentLength int) bool

Compressible implemented Compress interface. Recommend https://github.com/teambition/compressible-go.

import "github.com/teambition/compressible-go"

app := gear.New()
app.Set("AppCompress", compressible.WithThreshold(1024))

// Add a static middleware
app.Use(static.New(static.Options{
	Root:   "./",
	Prefix: "/",
}))
app.Error(app.Listen(":3000")) // http://127.0.0.1:3000/

type DefaultOnError added in v0.12.0

type DefaultOnError struct{}

DefaultOnError is default ctx error handler.

func (*DefaultOnError) OnError added in v0.12.0

func (o *DefaultOnError) OnError(ctx *Context, err error) *Error

OnError implemented OnError interface.

type Error added in v0.3.0

type Error struct {
	Code int
	Msg  string
	Meta interface{}
}

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

func ParseError(e error, code ...int) *Error

ParseError parse a error, textproto.Error or HTTPError to *Error

func (*Error) Error added in v0.10.0

func (err *Error) Error() string

Error implemented HTTPError interface.

func (*Error) Status added in v0.3.0

func (err *Error) Status() int

Status implemented HTTPError interface.

func (*Error) String added in v0.15.1

func (err *Error) String() string

String implemented fmt.Stringer interface, returns a Go-syntax string.

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 Handler

type Handler interface {
	Serve(ctx *Context) error
}

Handler interface is used by app.UseHandler as a middleware.

type Middleware

type Middleware func(*Context) error

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 OnError added in v0.12.0

type OnError interface {
	OnError(ctx *Context, err error) *Error
}

OnError interface is use to deal with errors returned by middlewares.

type Renderer

type Renderer interface {
	Render(ctx *Context, w io.Writer, name string, data interface{}) error
}

Renderer interface is used by ctx.Render.

type Response

type Response struct {
	// 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) CloseNotify added in v0.20.0

func (r *Response) CloseNotify() <-chan bool

CloseNotify implements the http.CloseNotifier interface to allow detecting when the underlying connection has gone away. This mechanism can be used to cancel long operations on the server if the client has disconnected before the response is ready. See http.CloseNotifier(https://golang.org/pkg/net/http/#CloseNotifier)

func (*Response) Del

func (r *Response) Del(key string)

Del deletes the header entries associated with key.

func (*Response) Flush added in v0.20.0

func (r *Response) Flush()

Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client. See http.Flusher(https://golang.org/pkg/net/http/#Flusher)

func (*Response) Get

func (r *Response) Get(key string) string

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) Header

func (r *Response) Header() http.Header

Header returns the header map that will be sent by WriteHeader.

func (*Response) HeaderWrote added in v0.14.0

func (r *Response) HeaderWrote() bool

HeaderWrote indecates that whether the reply header has been (logically) written.

func (*Response) Hijack added in v0.20.0

func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)

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) ResetHeader added in v0.16.4

func (r *Response) ResetHeader(filterReg ...*regexp.Regexp)

ResetHeader reset headers. If keepSubset is true, header matching `(?i)^(accept|allow|retry-after|warning|access-control-allow-)` will be keep

func (*Response) Set

func (r *Response) Set(key, value string)

Set sets the header entries associated with key to the single element value. It replaces any existing values associated with key.

func (*Response) Vary added in v0.21.0

func (r *Response) Vary(field string)

Vary manipulate the HTTP Vary header. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary

func (*Response) Write

func (r *Response) Write(buf []byte) (int, error)

Write writes the data to the connection as part of an HTTP reply.

func (*Response) WriteHeader

func (r *Response) WriteHeader(code int)

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

	router := gear.NewRouter()
	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
::name         not named parameter, it is literal `:name`

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

func NewRouter(routerOptions ...RouterOptions) *Router

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()
viewRouter.Get("/", Ctl.IndexView)
// add more ...

apiRouter := gear.NewRouter(RouterOptions{
	Root: "/api",
	IgnoreCase: true,
	FixedPathRedirect: true,
	TrailingSlashRedirect: true,
})
// support one more middleware
apiRouter.Get("/user/:id", API.Auth, 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, handlers ...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, handlers ...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, handlers ...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, handlers ...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, handlers ...Middleware)

Options registers a new OPTIONS route for a path with matching handler in the router.

func (*Router) Otherwise

func (r *Router) Otherwise(handlers ...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, handlers ...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, handlers ...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, handlers ...Middleware)

Put registers a new PUT route for a path with matching handler in the router.

func (*Router) Serve added in v0.5.0

func (r *Router) Serve(ctx *Context) error

Serve implemented gear.Handler interface

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 RouterOptions added in v0.15.0

type RouterOptions struct {
	// Router's namespace. Gear supports multiple routers with different namespace.
	// Root string should start with "/", default to "/"
	Root string

	// Ignore case when matching URL path.
	IgnoreCase bool

	// Enables automatic redirection if the current path can't be matched but
	// a handler for the fixed path exists.
	// For example if "/api//foo" is requested but a route only exists for "/api/foo", the
	// client is redirected to "/api/foo"" with http status code 301 for GET requests
	// and 307 for all other request methods.
	FixedPathRedirect bool

	// Enables automatic redirection if the current route can't be matched but a
	// handler for the path with (without) the trailing slash exists.
	// For example if "/foo/" is requested but a route only exists for "/foo", the
	// client is redirected to "/foo"" with http status code 301 for GET requests
	// and 307 for all other request methods.
	TrailingSlashRedirect bool
}

RouterOptions is options for 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.

Directories

Path Synopsis
middleware

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL