Documentation
¶
Overview ¶
Package gem is a high performance web framework, it is friendly to REST APIs.
Note: This package requires go1.8 or above.
Features ¶
1. High performance
2. Friendly to REST API
3. Full test of all APIs
4. Pretty and fast router
5. HTTP/2 support
6. Leveled logging - included four levels `debug`, `info`, `error` and `fatal`, there are many third-party implements the Logger:
logrus - Structured, pluggable logging for Go - https://github.com/Sirupsen/logrus go-logging - Golang logging library - https://github.com/op/go-logging gem-log - default logger - https://github.com/go-gem/log
7. Middlewares
CSRF Middleware - Cross-Site Request Forgery protection - https://github.com/go-gem/middleware-csrf CORS Middleware - Cross-Origin Resource Sharing - https://github.com/go-gem/middleware-cors AUTH Middleware - HTTP Basic and HTTP Digest authentication - https://github.com/go-gem/middleware-auth JWT Middleware - JSON WEB TOKEN authentication - https://github.com/go-gem/middleware-jwt Compress Middleware - compress response body - https://github.com/go-gem/middleware-compress Request Body Limit Middleware - limit request body size - https://github.com/go-gem/middleware-body-limit
8. Frozen APIs since the stable version `2.0.0` was released
Install ¶
use go get command to install:
$ go get -u github.com/go-gem/gem
Quick Start ¶
a simple HTTP server:
package main import ( "log" "github.com/go-gem/gem" ) func index(ctx *gem.Context) { ctx.HTML(200, "hello world") } func main() { // Create server. srv := gem.New(":8080") // Create router. router := gem.NewRouter() // Register handler router.GET("/", index) // Start server. log.Println(srv.ListenAndServe(router.Handler())) }
Logger ¶
AFAIK, the following leveled logging packages are compatible with Gem web framework:
1. logrus - structured, pluggable logging for Go - https://github.com/Sirupsen/logrus
2. go-logging - golang logging library - https://github.com/op/go-logging
3. gem-log - default logger, maintained by Gem Authors - https://github.com/go-gem/log
Logger(https://godoc.org/github.com/go-gem/gem#Logger) includes four levels: debug, info, error and fatal, their APIs are Debug and Debugf, Info and Infof, Error and Errorf, Fatal and Fatalf.
We take logrus as example to show that how to set and use logger.
// set logrus logger as server's logger. srv.SetLogger(logrus.New()) // we can use it in handler. router.GET("/logger", func(ctx *gem.Context) { ctx.Logger().Debug("debug") ctx.Logger().Info("info") ctx.Logger().Error("error") })
Static Files ¶
example that serve static files:
router.ServeFiles("/tmp/*filepath", http.Dir(os.TempDir()))
Note: the path(first parameter) must end with `*filepath`.
REST APIs ¶
The router is friendly to REST APIs.
// user list router.GET("/users", func(ctx *gem.Context) { ctx.JSON(200, userlist) }) // add user router.POST("/users", func(ctx *gem.Context) { ctx.Request.ParseForm() name := ctx.Request.FormValue("name") // add user ctx.JSON(200, msg) }) // user profile. router.GET("/users/:name", func(ctx *gem.Context) { // firstly, we need get the username from the URL query. name, ok := ctx.UserValue("name").(string) if !ok { ctx.JSON(404, userNotFound) return } // return user profile. ctx.JSON(200, userProfileByName(name)) }) // update user profile router.PUT("/users/:name", func(ctx *gem.Context) { // firstly, we need get the username from the URL query. name, ok := ctx.UserValue("name").(string) if !ok { ctx.JSON(404, userNotFound) return } // get nickname ctx.Request.ParseForm() nickname := ctx.Request.FormValue("nickname") // update user nickname. ctx.JSON(200, msg) }) // delete user router.DELETE("/users/:name", func(ctx *gem.Context) { // firstly, we need get the username from the URL query. name, ok := ctx.UserValue("name").(string) if !ok { ctx.JSON(404, userNotFound) return } // delete user. ctx.JSON(200, msg) }
HTTP2 Server Push ¶
see https://github.com/go-gem/examples/tree/master/http2
router.GET("/", func(ctx *gem.Context) { if err := ctx.Push("/images/logo.png", nil); err != nil { ctx.Logger().Info(err) } ctx.HTML(200, `<html><head></head><body><img src="/images/logo.png"/></body></html>`) }) router.ServeFiles("/images/*filepath", http.Dir(imagesDir))
Use Middleware ¶
It is easy to implement a middleware, see Middleware(https://godoc.org/github.com/go-gem/gem#Middleware) interface, you just need to implement the `Wrap` function.
type Middleware interface { Wrap(next Handler) Handler }
For example, we defined a simple debug middleware:
type Debug struct{} // Wrap implements the Middleware interface. func (d *Debug) Wrap(next gem.Handler) gem.Handler { // gem.HandlerFunc is adapter like http.HandlerFunc. return gem.HandlerFunc(func(ctx *gem.Context) { // print request info. log.Println(ctx.Request.URL, ctx.Request.Method) // call the next handler. next.Handle(ctx) }) }
and then we should register it:
register the middleware for all handlers via Router.Use(https://godoc.org/github.com/go-gem/gem#Router.Use).
router.Use(&Debug{})
we can also register the middleware for specific handler via HandlerOption(https://godoc.org/github.com/go-gem/gem#HandlerOption).
router.GET("/specific", specificHandler, &gem.HandlerOption{Middlewares:[]gem.Middleware{&Debug{}}})
Gem also provides some frequently used middlewares, such as:
1. CSRF Middleware - Cross-Site Request Forgery protection - https://github.com/go-gem/middleware-csrf
2. CORS Middleware - Cross-Origin Resource Sharing - https://github.com/go-gem/middleware-cors
3. AUTH Middleware - HTTP Basic and HTTP Digest authentication - https://github.com/go-gem/middleware-auth
4. JWT Middleware - JSON WEB TOKEN authentication - https://github.com/go-gem/middleware-jwt
5. Compress Middleware - Compress response body - https://github.com/go-gem/middleware-compress
6. Request Body Limit Middleware - limit request body maximum size - https://github.com/go-gem/middleware-body-limit
Share data between middlewares ¶
Context provides two useful methods: `SetUserValue` and `UserValue` to share data between middlewares.
// Store data into context in one middleware ctx.SetUserValue("name", "foo") // Get data from context in other middleware or handler ctx.UserValue("name")
Index ¶
- Constants
- func CleanPath(p string) string
- func Int(v interface{}) (int, error)
- func ListenAndServe(addr string, handler Handler) error
- func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error
- func String(v interface{}) (string, error)
- func Version() string
- type Application
- func (app *Application) Close() (errs []error)
- func (app *Application) Component(name string) interface{}
- func (app *Application) Init() (err error)
- func (app *Application) InitControllers() (err error)
- func (app *Application) Router() *Router
- func (app *Application) SetCloseCallback(callback ApplicationCallback)
- func (app *Application) SetComponent(name string, component interface{}) error
- func (app *Application) SetController(path string, controller Controller)
- func (app *Application) SetInitCallback(callback ApplicationCallback)
- func (app *Application) Templates() *Templates
- type ApplicationCallback
- type AssetsOption
- type Context
- func (ctx *Context) Error(error string, code int)
- func (ctx *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (ctx *Context) FormValue(key string) string
- func (ctx *Context) HTML(code int, body string)
- func (ctx *Context) Host() string
- func (ctx *Context) IsAjax() bool
- func (ctx *Context) IsDelete() bool
- func (ctx *Context) IsGet() bool
- func (ctx *Context) IsHead() bool
- func (ctx *Context) IsPost() bool
- func (ctx *Context) IsPut() bool
- func (ctx *Context) JSON(code int, v interface{})
- func (ctx *Context) Logger() Logger
- func (ctx *Context) NotFound()
- func (ctx *Context) ParseForm() error
- func (ctx *Context) PostFormValue(key string) string
- func (ctx *Context) Push(target string, opts *http.PushOptions) error
- func (ctx *Context) Redirect(url string, code int)
- func (ctx *Context) Referer() string
- func (ctx *Context) SetContentType(v string)
- func (ctx *Context) SetServer(server *Server)
- func (ctx *Context) SetStatusCode(code int)
- func (ctx *Context) SetUserValue(key string, value interface{})
- func (ctx *Context) URL() *url.URL
- func (ctx *Context) UserValue(key string) interface{}
- func (ctx *Context) Write(p []byte) (n int, err error)
- func (ctx *Context) XML(code int, v interface{}, headers ...string)
- type Controller
- type Handler
- type HandlerFunc
- type HandlerOption
- type Logger
- type Middleware
- type Router
- func (r *Router) DELETE(path string, handle HandlerFunc, opts ...*HandlerOption)
- func (r *Router) GET(path string, handle HandlerFunc, opts ...*HandlerOption)
- func (r *Router) HEAD(path string, handle HandlerFunc, opts ...*HandlerOption)
- func (r *Router) Handle(method, path string, handle HandlerFunc, opts ...*HandlerOption)
- func (r *Router) Handler() Handler
- func (r *Router) Lookup(method, path string, ctx *Context) (Handler, bool)
- func (r *Router) OPTIONS(path string, handle HandlerFunc, opts ...*HandlerOption)
- func (r *Router) PATCH(path string, handle HandlerFunc, opts ...*HandlerOption)
- func (r *Router) POST(path string, handle HandlerFunc, opts ...*HandlerOption)
- func (r *Router) PUT(path string, handle HandlerFunc, opts ...*HandlerOption)
- func (r *Router) ServeFiles(path string, root http.FileSystem, opts ...*HandlerOption)
- func (r *Router) Use(middleware Middleware)
- type Server
- type ServerOption
- type Templates
- func (ts *Templates) Filenames(filenames ...string) []string
- func (ts *Templates) Layout(name string) (*template.Template, error)
- func (ts *Templates) New(filenames ...string) (*template.Template, error)
- func (ts *Templates) Render(layoutName string, filenames ...string) (*template.Template, error)
- func (ts *Templates) SetLayout(filenames ...string) error
- type TemplatesOption
- type WebController
- func (wc *WebController) DELETE(ctx *Context)
- func (wc *WebController) GET(ctx *Context)
- func (wc *WebController) HEAD(ctx *Context)
- func (wc *WebController) HandlerOptions() map[string]*HandlerOption
- func (wc *WebController) Init(app *Application) error
- func (wc *WebController) Methods() []string
- func (wc *WebController) OPTIONS(ctx *Context)
- func (wc *WebController) PATCH(ctx *Context)
- func (wc *WebController) POST(ctx *Context)
- func (wc *WebController) PUT(ctx *Context)
Constants ¶
const ( MIMEHTML = "text/html" MIMEJSON = "application/json" MIMEXML = "application/xml" )
MIME types
const ( MethodGet = "GET" MethodPost = "POST" MethodPut = "PUT" MethodDelete = "DELETE" MethodHead = "HEAD" MethodConnect = "CONNECT" MethodOptions = "OPTIONS" MethodPatch = "PATCH" )
Request methods.
Variables ¶
This section is empty.
Functions ¶
func CleanPath ¶
CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.
The following rules are applied iteratively until no further processing can be done:
- Replace multiple slashes with a single slash.
- Eliminate each . path name element (the current directory).
- Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
- Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.
If the result of this process is an empty string, "/" is returned
func ListenAndServe ¶
ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections.
func ListenAndServeTLS ¶
ListenAndServeTLS acts identically to ListenAndServe, except that it expects HTTPS connections. Additionally, files containing a certificate and matching private key for the server must be provided. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.
Types ¶
type Application ¶
type Application struct { ServerOpt ServerOption `json:"server"` AssetsOpt AssetsOption `json:"assets"` TemplatesOpt TemplatesOption `json:"templates"` // contains filtered or unexported fields }
func (*Application) Close ¶
func (app *Application) Close() (errs []error)
Close close application, all the close callbacks will be invoked.
func (*Application) Component ¶
func (app *Application) Component(name string) interface{}
Component returns a component via the given name.
func (*Application) Init ¶
func (app *Application) Init() (err error)
Init initialize application, All the initialized callbacks.
func (*Application) InitControllers ¶
func (app *Application) InitControllers() (err error)
InitControllers initialize controllers.
func (*Application) Router ¶
func (app *Application) Router() *Router
Router returns an instance of router.
func (*Application) SetCloseCallback ¶
func (app *Application) SetCloseCallback(callback ApplicationCallback)
SetCloseCallback set user-defined close callback.
func (*Application) SetComponent ¶
func (app *Application) SetComponent(name string, component interface{}) error
SetComponent set component by the given name and component.
If the component already exists, returns an non-nil error.
func (*Application) SetController ¶
func (app *Application) SetController(path string, controller Controller)
SetController set controller with the given route's path and controller instance.
func (*Application) SetInitCallback ¶
func (app *Application) SetInitCallback(callback ApplicationCallback)
SetInitCallback set user-defined initialized callback.
func (*Application) Templates ¶
func (app *Application) Templates() *Templates
Templates returns an instance of templates manager.
type ApplicationCallback ¶
type ApplicationCallback func() error
ApplicationCallback is type of func that defines
type AssetsOption ¶
type AssetsOption struct { Root string `json:"root"` Dirs map[string]string `json:"dirs"` HandlerOption *HandlerOption }
type Context ¶
type Context struct { Request *http.Request Response http.ResponseWriter // contains filtered or unexported fields }
Context contains *http.Request and http.Response.
func (*Context) PostFormValue ¶
PostFormValue is a shortcut of http.Request.PostFormValue.
func (*Context) Push ¶
func (ctx *Context) Push(target string, opts *http.PushOptions) error
Push HTTP/2 server push.
If http.Response does not implements http.Pusher, returns errNotSupportHTTP2ServerPush.
func (*Context) Redirect ¶
Redirect replies to the request with a redirect to url, which may be a path relative to the request path.
func (*Context) SetContentType ¶
SetContentType set response Content-Type.
func (*Context) SetStatusCode ¶
SetStatusCode is shortcut of http.ResponseWriter.WriteHeader.
func (*Context) SetUserValue ¶
SetUserValue stores the given value under the given key in ctx.
func (*Context) UserValue ¶
UserValue returns the value stored via SetUserValue* under the given key.
type Controller ¶
type Handler ¶
type Handler interface {
Handle(*Context)
}
Handler for processing incoming requests.
type HandlerFunc ¶
type HandlerFunc func(*Context)
The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.
type HandlerOption ¶
type HandlerOption struct {
Middlewares []Middleware
}
HandlerOption option for handler.
func NewHandlerOption ¶
func NewHandlerOption(middlewares ...Middleware) *HandlerOption
NewHandlerOption returns HandlerOption instance by the given middlewares.
type Logger ¶
type Logger interface { Debug(v ...interface{}) Debugf(format string, v ...interface{}) Info(v ...interface{}) Infof(format string, v ...interface{}) Error(v ...interface{}) Errorf(format string, v ...interface{}) Fatal(v ...interface{}) Fatalf(format string, v ...interface{}) }
Logger defines a logging interface.
type Router ¶
type Router struct { // 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. RedirectTrailingSlash bool // If enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // If enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool // If enabled, the router automatically replies to OPTIONS requests. // Custom OPTIONS handlers take priority over automatic replies. HandleOPTIONS bool // Configurable http.Handler which is called when no matching route is // found. If it is not set, http.NotFound is used. NotFound Handler // Configurable http.Handler which is called when a request // cannot be routed and HandleMethodNotAllowed is true. // If it is not set, http.Error with http.StatusMethodNotAllowed is used. // The "Allow" header with allowed request methods is set before the handler // is called. MethodNotAllowed Handler // Function to handle panics recovered from http handlers. // It should be used to generate a error page and return the http error code // 500 (Internal Server Error). // The handler can be used to keep your server from crashing because of // unrecovered panics. PanicHandler func(*Context, interface{}) // contains filtered or unexported fields }
Router is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes
func NewRouter ¶
func NewRouter() *Router
NewRouter returns a new initialized Router. Path auto-correction, including trailing slashes, is enabled by default.
func (*Router) DELETE ¶
func (r *Router) DELETE(path string, handle HandlerFunc, opts ...*HandlerOption)
DELETE is a shortcut for router.Handle("DELETE", path, handle)
func (*Router) GET ¶
func (r *Router) GET(path string, handle HandlerFunc, opts ...*HandlerOption)
GET is a shortcut for router.Handle("GET", path, handle)
func (*Router) HEAD ¶
func (r *Router) HEAD(path string, handle HandlerFunc, opts ...*HandlerOption)
HEAD is a shortcut for router.Handle("HEAD", path, handle)
func (*Router) Handle ¶
func (r *Router) Handle(method, path string, handle HandlerFunc, opts ...*HandlerOption)
Handle registers a new request handle with the given path and method.
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) Lookup ¶
Lookup allows the manual lookup of a method + path combo. This is e.g. useful to build a framework around this router. If the path was found, it returns the handle function and the path parameter values. Otherwise the third return value indicates whether a redirection to the same path with an extra / without the trailing slash should be performed.
func (*Router) OPTIONS ¶
func (r *Router) OPTIONS(path string, handle HandlerFunc, opts ...*HandlerOption)
OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)
func (*Router) PATCH ¶
func (r *Router) PATCH(path string, handle HandlerFunc, opts ...*HandlerOption)
PATCH is a shortcut for router.Handle("PATCH", path, handle)
func (*Router) POST ¶
func (r *Router) POST(path string, handle HandlerFunc, opts ...*HandlerOption)
POST is a shortcut for router.Handle("POST", path, handle)
func (*Router) PUT ¶
func (r *Router) PUT(path string, handle HandlerFunc, opts ...*HandlerOption)
PUT is a shortcut for router.Handle("PUT", path, handle)
func (*Router) ServeFiles ¶
func (r *Router) ServeFiles(path string, root http.FileSystem, opts ...*HandlerOption)
ServeFiles serves files from the given file system root. The path must end with "/*filepath", files are then served from the local path /defined/root/dir/*filepath. For example if root is "/etc" and *filepath is "passwd", the local file "/etc/passwd" would be served. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use http.Dir:
router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
type Server ¶
Server contains *http.Server.
func (*Server) ListenAndServe ¶
ListenAndServe listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming connections.
func (*Server) ListenAndServeTLS ¶
ListenAndServeTLS listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming TLS connections. Accepted connections are configured to enable TCP keep-alives.
type ServerOption ¶
type Templates ¶
type Templates struct { Path string Suffix string Delims []string FuncMap template.FuncMap LayoutDir string // contains filtered or unexported fields }
Templates is a templates manager.
func NewTemplates ¶
NewTemplates returns a Templates instance with the given path and default options.
func (*Templates) New ¶
New returns a template.Template instance with the Templates's option and template.ParseFiles.
Note: filenames should be absolute paths, either uses Templates.Filenames or specifies manually.
type TemplatesOption ¶
type WebController ¶
type WebController struct{}
WebController is an empty controller that implements Controller interface.
func (*WebController) DELETE ¶
func (wc *WebController) DELETE(ctx *Context)
DELETE implements Controller's DELETE method.
func (*WebController) GET ¶
func (wc *WebController) GET(ctx *Context)
GET implements Controller's GET method.
func (*WebController) HEAD ¶
func (wc *WebController) HEAD(ctx *Context)
HEAD implements Controller's HEAD method.
func (*WebController) HandlerOptions ¶
func (wc *WebController) HandlerOptions() map[string]*HandlerOption
HandlerOptions defines handler's option.
The key should be the name of request method, case-sensitive, such as GET, POST.
func (*WebController) Init ¶
func (wc *WebController) Init(app *Application) error
Init initialize the controller.
It would be invoked when register a controller.
func (*WebController) Methods ¶
func (wc *WebController) Methods() []string
Methods defines which handlers should be registered.
The value should be the name of request method, case-sensitive, such as GET, POST. By default, GET and POST's handler will be registered.
func (*WebController) OPTIONS ¶
func (wc *WebController) OPTIONS(ctx *Context)
OPTIONS implements Controller's OPTIONS method.
func (*WebController) PATCH ¶
func (wc *WebController) PATCH(ctx *Context)
PATCH implements Controller's PATCH method.
func (*WebController) POST ¶
func (wc *WebController) POST(ctx *Context)
POST implements Controller's POST method.
func (*WebController) PUT ¶
func (wc *WebController) PUT(ctx *Context)
PUT implements Controller's PUT method.