gear

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2016 License: MIT Imports: 15 Imported by: 226

README

Gear

Gear implements a web framework with context.Context for Go. It focuses on performance and composition.

Build Status GoDoc

Demo

// package gear
import "github.com/teambition/gear"
// 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"))

Import

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

Document

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

Bench

https://godoc.org/github.com/teambition/gear/blob/master/bench

Gear with "net/http": 48307
> 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.30ms    2.53ms  59.54ms   94.28%
    Req/Sec    12.15k     1.56k   20.98k    81.75%
  484231 requests in 10.02s, 63.27MB read
Requests/sec:  48307.40
Transfer/sec:      6.31MB
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

License

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

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

Examples

Constants

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

All const values got from https://github.com/labstack/echo MIME types

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

Variables

View Source
var (
	GearParamsKey = &contextKey{"Gear-Params-Key"}
	GearLogsKey   = &contextKey{"Gear-Logs-Key"}
)

Gear global values

Functions

This section is empty.

Types

type Context

type Context interface {
	context.Context

	// Cancel cancel the ctx and all it' children context
	Cancel()

	// 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.
	WithCancel() (context.Context, context.CancelFunc)

	// WithDeadline returns a copy of the ctx with the deadline adjusted to be no later than d.
	WithDeadline(time.Time) (context.Context, context.CancelFunc)

	// WithTimeout returns WithDeadline(time.Now().Add(timeout)).
	WithTimeout(time.Duration) (context.Context, context.CancelFunc)

	// WithValue returns a copy of the ctx in which the value associated with key is val.
	WithValue(interface{}, interface{}) context.Context

	// SetValue save a key and value to the ctx.
	SetValue(interface{}, interface{})

	// Request returns `*http.Request`.
	Request() *http.Request

	// Request returns `*Response`.
	Response() *Response

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

	// Host returns the the client's request Host.
	Host() string

	// Method returns the client's request Method.
	Method() string

	// Path returns the client's request Path.
	Path() string

	// Param returns path parameter by name.
	Param(string) string

	// Query returns the query param for the provided name.
	Query(string) string

	// Cookie returns the named cookie provided in the request.
	Cookie(string) (*http.Cookie, error)

	// SetCookie adds a `Set-Cookie` header in HTTP response.
	SetCookie(*http.Cookie)

	// Cookies returns the HTTP cookies sent with the request.
	Cookies() []*http.Cookie

	// Get retrieves data from the request Header.
	Get(string) string

	// Set saves data to the response Header.
	Set(string, string)

	// Status set a status code to response
	Status(int)

	// Type set a content type to response
	Type(string)

	// Body set a string to response.
	Body(string)

	// Error set a error message with status code to response.
	Error(HTTPError)

	// HTML set an Html body with status code to response.
	// It will end the ctx.
	HTML(int, string) error

	// JSON set a JSON body with status code to response.
	// It will end the ctx.
	JSON(int, interface{}) error

	// JSONBlob set a JSON blob body with status code to response.
	// It will end the ctx.
	JSONBlob(int, []byte) error

	// JSONP sends a JSONP response with status code. It uses `callback` to construct the JSONP payload.
	// It will end the ctx.
	JSONP(int, string, interface{}) error

	// JSONPBlob sends a JSONP blob response with status code. It uses `callback`
	// to construct the JSONP payload.
	// It will end the ctx.
	JSONPBlob(int, string, []byte) error

	// XML set an XML body with status code to response.
	// It will end the ctx.
	XML(int, interface{}) error

	// XMLBlob set a XML blob body with status code to response.
	// It will end the ctx.
	XMLBlob(int, []byte) error

	// 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.
	Render(int, string, interface{}) error

	// Stream sends a streaming response with status code and content type.
	// It will end the ctx.
	Stream(int, string, io.Reader) error

	// Attachment sends a response from `io.ReaderSeeker` as attachment, prompting
	// client to save the file.
	// It will end the ctx.
	Attachment(string, io.ReadSeeker) error

	// Inline sends a response from `io.ReaderSeeker` as inline, opening
	// the file in the browser.
	// It will end the ctx.
	Inline(string, io.ReadSeeker) error

	// Redirect redirects the request with status code.
	// It will end the ctx.
	Redirect(int, string) error

	// 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.
	End(int, []byte)

	// IsEnded return the ctx' ended status.
	IsEnded() bool

	// After add a Hook to the ctx that will run after app's Middleware.
	After(hook Hook)

	// OnEnd add a Hook to the ctx that will run before response.WriteHeader.
	OnEnd(hook Hook)

	// String returns a string represent the ctx.
	String() string
}

Context represents the context of the current HTTP request. It holds request and response objects, path, path parameters, data, registered handler and content.Context.

type Error added in v0.3.0

type Error struct {
	Code int
	// contains filtered or unexported fields
}

Error is error struct that implemented HTTPError

func NewError added in v0.3.0

func NewError(err error, code int) Error

NewError create a Error instance with error and status code.

func (Error) Status added in v0.3.0

func (err Error) Status() int

Status returns Error's status code.

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 New

func New() *Gear

New creates an instance of Gear.

func (*Gear) Error added in v0.3.0

func (g *Gear) Error(err error)

Error writes error to underlayer logging system.

func (*Gear) Listen

func (g *Gear) Listen(addr string) error

Listen starts the HTTP server.

func (*Gear) ListenTLS

func (g *Gear) ListenTLS(addr, certFile, keyFile string) error

ListenTLS starts the HTTPS server.

func (*Gear) StartBG added in v0.2.0

func (g *Gear) StartBG(laddr string) *ServerBG

StartBG starts a background app instance. It is useful for testing. The background app instance must close by ServerBG.Close().

func (*Gear) Use

func (g *Gear) Use(handle Middleware)

Use uses the given middleware `handle`.

func (*Gear) UseHandler

func (g *Gear) UseHandler(h Handler)

UseHandler uses a instance that implemented Handler interface.

type HTTPError

type HTTPError interface {
	error
	Status() int
}

HTTPError represents an error that occurred while handling a request.

type Handler

type Handler interface {
	Middleware(Context) error
}

Handler is the interface that wraps the Middleware function.

type Hook

type Hook func(Context)

Hook defines a function to process hook.

type Middleware

type Middleware func(Context) error

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 Renderer

type Renderer interface {
	Render(Context, io.Writer, string, interface{}) error
}

Renderer is the interface that wraps the Render function.

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

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

Add adds the key, value pair to the header. It appends to any existing values associated with key.

func (*Response) Del

func (r *Response) Del(key string)

Del deletes the values associated with key.

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) 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) 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 {
	// 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 NewRouter

func NewRouter(root string, ignoreCase bool) *Router

NewRouter returns a new Router instance with root path and ignoreCase option.

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

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

Middleware implemented gear.Handler interface

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.

func (*ServerBG) Addr added in v0.2.0

func (s *ServerBG) Addr() net.Addr

Addr returns the background app instance addr.

func (*ServerBG) Close added in v0.2.0

func (s *ServerBG) Close() error

Close closes the background app instance.

func (*ServerBG) Wait added in v0.2.0

func (s *ServerBG) Wait() error

Wait waits the background app instance close.

Directories

Path Synopsis
bench

Jump to

Keyboard shortcuts

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