Documentation
¶
Overview ¶
Package gem is a simple and fast web framework, for building web or restful application.
Install ¶
Run the following command to install Gem:
go get github.com/go-gem/gem
Example ¶
Run the following code, and then navigate to http://127.0.0.1:8080.
package main
import (
"log"
"github.com/go-gem/gem"
)
func main() {
log.Fatal(gem.ListenAndServe(":8080", func(c *gem.Context) {
c.HTML(200, "Hello world.")
}))
}
Server ¶
1. Create router:
router := gem.NewRouter()
2. Create Server:
server := gem.New(":8080", router.Handler())
3. Launch the server:
server.ListenAndServe()
Router ¶
1. Create router's instance:
router := gem.NewRouter()
2. Register Middlewares:
router.Use(middleware) ...
3. Register handler:
// Handle registers a new request handle with the given path and method.
router.Handle("GET", "/", func(c *gem.Context) {
c.Write([]byte("Hello world."))
})
// Router also provides some shortcuts: GET, POST, DELETE, PUT...
router.GET("/get", func(c *gem.Context) {
c.Write([]byte("Hello world."))
})
4. Specific configuration:
All of router's APIs can registers specific configuration through the last parameters.
router.GET("/specific-middleware", func(c *gem.Context) {
c.Write([]byte("Hello world."))
}, gem.HandlerConfig{
Middlewares:[]Middleware{
specificMiddlewareOne{},
specificMiddlewareTwo{},
},
})
5. Static resource files:
router.ServeFiles("/js/*filepath", "/path/to/js")
6. Router's parameters.
router.GET("/user/:name", func(c *gem.Context) {
c.HTML(200, fmt.Sprintf("Hello %s", c.UserValue("name")))
})
If you need to handle CORS, pass your CORS middleware as the third parameter like the following:
router.ServeFiles("/js/*filepath", "/path/to/js", corsMiddleware)
Context ¶
Context is extend edition of fasthttp.RequestCtx.
Context provides some convenient methods:
HTML(code int, body string)
JSON(code int, v interface{})
JSONP(code int, v interface{}, callback []byte)
XML(code int, v interface{}, headers ...string)
IsAjax() bool
Middleware ¶
Middleware is an useful feature, you can use it to implement some useful functions, such as BasicAuth, Gzip compress, Request Body Limit, IP white list or blacklist etc.
It is easy to write a middleware, you just need to implement the Handle method:
Handle(next Handler) Handler
Built-in middlewares:
- Compress(Gzip) Middleware.
- Request Body Limit Middleware.
- ...
Logger ¶
Gem defines Logger's interface, it is easy to choose your favorite logging package.
Gem provide a leveled logging package, see https://github.com/go-gem/log for more details.
How to set logger:
// Create logger instance.
logger := log.New(os.Stderr, log.LstdFlags, log.LevelAll)
// Set server's logger.
server.SetLogger(logger)
// Using logger.
router.Get("/log", func(c *gem.Context) {
c.Logger().Info("log info")
})
Logger interface following:
type Logger interface {
Debug(v ...interface{})
Debugf(format string, v ...interface{})
Debugln(v ...interface{})
Info(v ...interface{})
Infof(format string, v ...interface{})
Infoln(v ...interface{})
Warning(v ...interface{})
Warningf(format string, v ...interface{})
Warningln(v ...interface{})
Error(v ...interface{})
Errorf(format string, v ...interface{})
Errorln(v ...interface{})
Fatal(v ...interface{})
Fatalf(format string, v ...interface{})
Fatalln(v ...interface{})
}
Sessions Store ¶
See https://github.com/go-gem/sessions for more details.
How to set sessions store:
// Create sessions store instance.
store := sessions.NewCookieStore([]byte("something-very-secret"))
// Set server's sessions store.
server.SetSessionsStore(store)
// Using sessions store.
router.Get("/log", func(c *gem.Context) {
session,err := c.SessionsStore().Get(c.RequestCtx, "GOSESSION")
if err != nil {
...
}
...
})
Index ¶
- Constants
- Variables
- func Bytes2String(b []byte) string
- func CleanPath(p string) string
- func ListenAndServe(addr string, handler HandlerFunc) error
- func ListenAndServeTLS(addr, certFile, keyFile string, handler HandlerFunc) error
- func ListenAndServeUNIX(addr string, mode os.FileMode, handler HandlerFunc) error
- func Name() string
- func String2Bytes(s string) []byte
- func Version() string
- type Context
- func (ctx *Context) HTML(code int, body string)
- func (ctx *Context) IsAjax() bool
- func (ctx *Context) JSON(code int, v interface{})
- func (ctx *Context) JSONP(code int, v interface{}, callback []byte)
- func (ctx *Context) Logger() Logger
- func (ctx *Context) Param(key string) string
- func (ctx *Context) ParamInt(key string) int
- func (ctx *Context) SessionsStore() sessions.Store
- func (ctx *Context) XML(code int, v interface{}, headers ...string)
- type Handler
- type HandlerConfig
- type HandlerFunc
- type Logger
- type Middleware
- type Router
- func (r *Router) DELETE(path string, handle HandlerFunc, configs ...HandlerConfig)
- func (r *Router) GET(path string, handle HandlerFunc, configs ...HandlerConfig)
- func (r *Router) HEAD(path string, handle HandlerFunc, configs ...HandlerConfig)
- func (r *Router) Handle(method, path string, handle HandlerFunc, configs ...HandlerConfig)
- func (r *Router) Handler() HandlerFunc
- func (r *Router) Lookup(method, path string, ctx *Context) (HandlerFunc, bool)
- func (r *Router) OPTIONS(path string, handle HandlerFunc, configs ...HandlerConfig)
- func (r *Router) PATCH(path string, handle HandlerFunc, configs ...HandlerConfig)
- func (r *Router) POST(path string, handle HandlerFunc, configs ...HandlerConfig)
- func (r *Router) PUT(path string, handle HandlerFunc, configs ...HandlerConfig)
- func (r *Router) ServeFiles(path string, rootPath string, configs ...HandlerConfig)
- func (r *Router) Use(m Middleware)
- type Server
- func (srv *Server) ListenAndServe() error
- func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error
- func (srv *Server) ListenAndServeUNIX(mode os.FileMode) error
- func (srv *Server) LoadConfig(config *ServerConfig)
- func (srv *Server) ServeConn(conn net.Conn) (err error)
- func (srv *Server) SetLogger(logger Logger)
- func (srv *Server) SetSessionsStore(store sessions.Store)
- func (srv *Server) SetSignal(sig1 os.Signal, sig2 Signal) error
- func (srv *Server) SetWaitTimeout(duration time.Duration)
- type ServerConfig
- type Signal
Constants ¶
const ( // AcceptEncoding HeaderAcceptEncoding = "Accept-Encoding" HeaderAcceptEncodingDeflate = "deflate" HeaderAcceptEncodingGzip = "gzip" // Cross-Origin Resource Sharing Headers HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderAuthorization = "Authorization" HeaderBasic = "Basic" HeaderBearer = "Bearer" HeaderContentEncoding = "Content-Encoding" HeaderContentLength = "Content-Length" // Content-Types HeaderContentType = "Content-Type" HeaderContentTypeForm = "application/x-www-form-urlencoded" HeaderContentTypeHTML = "text/html; charset=utf-8" HeaderContentTypeJSON = "application/json; charset=utf-8" HeaderContentTypeJSONP = "application/javascript; charset=utf-8" HeaderContentTypeText = "text/plain; charset=utf-8" HeaderContentTypeXML = "application/xml; charset=utf-8" HeaderOrigin = "Origin" HeaderVary = "Vary" HeaderXMLHttpRequest = "XMLHttpRequest" HeaderXRequestedWith = "X-Requested-With" // Methods MethodConnect = "CONNECT" MethodDelete = "DELETE" MethodGet = "GET" MethodHead = "HEAD" MethodOptions = "OPTIONS" MethodPatch = "PATCH" MethodPost = "POST" MethodPut = "PUT" MethodTrace = "TRACE" )
Constants
const ( SignalShutdown = iota SignalRestart )
Signals
Variables ¶
var ( // AcceptEncoding HeaderAcceptEncodingBytes = []byte(HeaderAcceptEncoding) HeaderAcceptEncodingDeflateBytes = []byte(HeaderAcceptEncodingDeflate) HeaderAcceptEncodingGzipBytes = []byte(HeaderAcceptEncodingGzip) // Cross-Origin Resource Sharing Headers HeaderAccessControlAllowCredentialsBytes = []byte(HeaderAccessControlAllowCredentials) HeaderAccessControlAllowHeadersBytes = []byte(HeaderAccessControlAllowHeaders) HeaderAccessControlAllowMethodsBytes = []byte(HeaderAccessControlAllowMethods) HeaderAccessControlAllowOriginBytes = []byte(HeaderAccessControlAllowOrigin) HeaderAccessControlExposeHeadersBytes = []byte(HeaderAccessControlExposeHeaders) HeaderAccessControlMaxAgeBytes = []byte(HeaderAccessControlMaxAge) HeaderAccessControlRequestHeadersBytes = []byte(HeaderAccessControlRequestHeaders) HeaderAccessControlRequestMethodBytes = []byte(HeaderAccessControlRequestMethod) HeaderAuthorizationBytes = []byte(HeaderAuthorization) HeaderBasicBytes = []byte(HeaderBasic) HeaderBearerBytes = []byte(HeaderBearer) HeaderContentEncodingBytes = []byte(HeaderContentEncoding) HeaderContentLengthBytes = []byte(HeaderContentLength) // Content-Types HeaderContentTypeBytes = []byte(HeaderContentType) HeaderContentTypeHTMLBytes = []byte(HeaderContentTypeHTML) HeaderContentTypeJSONBytes = []byte(HeaderContentTypeJSON) HeaderContentTypeJSONPBytes = []byte(HeaderContentTypeJSONP) HeaderContentTypeTextBytes = []byte(HeaderContentTypeText) HeaderContentTypeXMLBytes = []byte(HeaderContentTypeXML) HeaderOriginBytes = []byte(HeaderOrigin) HeaderVaryBytes = []byte(HeaderVary) HeaderXMLHttpRequestBytes = []byte(HeaderXMLHttpRequest) HeaderXRequestedWithBytes = []byte(HeaderXRequestedWith) // Methods MethodConnectBytes = []byte(MethodConnect) MethodDeleteBytes = []byte(MethodDelete) MethodGetBytes = []byte(MethodGet) MethodHeadBytes = []byte(MethodHead) MethodOptionsBytes = []byte(MethodOptions) MethodPatchBytes = []byte(MethodPatch) MethodPostBytes = []byte(MethodPost) MethodPutBytes = []byte(MethodPut) MethodTraceBytes = []byte(MethodTrace) )
Bytes
Functions ¶
func Bytes2String ¶
Bytes2String converts byte slice to a string without memory allocation. See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ .
Note it may break if string and/or slice header will change in the future go versions.
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 ¶
func ListenAndServe(addr string, handler HandlerFunc) error
ListenAndServe serves HTTP requests from the given TCP addr using the given handler.
func ListenAndServeTLS ¶
func ListenAndServeTLS(addr, certFile, keyFile string, handler HandlerFunc) error
ListenAndServeTLS serves HTTPS requests from the given TCP addr using the given handler.
certFile and keyFile are paths to TLS certificate and key files.
func ListenAndServeUNIX ¶
func ListenAndServeUNIX(addr string, mode os.FileMode, handler HandlerFunc) error
ListenAndServeUNIX serves HTTP requests from the given UNIX addr using the given handler.
The function deletes existing file at addr before starting serving.
The server sets the given file mode for the UNIX addr.
func String2Bytes ¶
String2Bytes converts string to a byte slice without memory allocation.
Note it may break if string and/or slice header will change in the future go versions.
Types ¶
type Context ¶
type Context struct {
*fasthttp.RequestCtx
// contains filtered or unexported fields
}
Context context contains request and response.
It is forbidden copying Context instances.
func (*Context) IsAjax ¶
IsAjax returns bool to indicate whether the current request is an AJAX (XMLHttpRequest) request.
func (*Context) SessionsStore ¶
SessionsStore returns server's sessions store.
type HandlerConfig ¶
type HandlerConfig struct {
Middlewares []Middleware
}
HandlerConfig defines specific configuration of handler, such as specific middlewares.
type HandlerFunc ¶
type HandlerFunc func(*Context)
HandlerFunc is an adapter to allow the use of ordinary functions as HTTP handlers.
func Convert ¶
func Convert(h fasthttp.RequestHandler) HandlerFunc
Convert convert fasthttp.RequestHandler to HandlerFunc.
type Logger ¶
type Logger interface {
Print(v ...interface{})
Printf(format string, v ...interface{})
Println(v ...interface{})
Debug(v ...interface{})
Debugf(format string, v ...interface{})
Debugln(v ...interface{})
Info(v ...interface{})
Infof(format string, v ...interface{})
Infoln(v ...interface{})
Warning(v ...interface{})
Warningf(format string, v ...interface{})
Warningln(v ...interface{})
Error(v ...interface{})
Errorf(format string, v ...interface{})
Errorln(v ...interface{})
Fatal(v ...interface{})
Fatalf(format string, v ...interface{})
Fatalln(v ...interface{})
}
Logger is an interface for customizing logger.
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 HandlerFunc
// 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 HandlerFunc
// 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 (*Router) DELETE ¶
func (r *Router) DELETE(path string, handle HandlerFunc, configs ...HandlerConfig)
DELETE is a shortcut for router.Handle("DELETE", path, handle) Register specific middlewares through third parameter.
func (*Router) GET ¶
func (r *Router) GET(path string, handle HandlerFunc, configs ...HandlerConfig)
GET is a shortcut for router.Handle("GET", path, handle) Register specific middlewares through third parameter.
func (*Router) HEAD ¶
func (r *Router) HEAD(path string, handle HandlerFunc, configs ...HandlerConfig)
HEAD is a shortcut for router.Handle("HEAD", path, handle) Register specific middlewares through third parameter.
func (*Router) Handle ¶
func (r *Router) Handle(method, path string, handle HandlerFunc, configs ...HandlerConfig)
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).
Register specific middlewares through fourth parameter.
func (*Router) Handler ¶
func (r *Router) Handler() HandlerFunc
func (*Router) Lookup ¶
func (r *Router) Lookup(method, path string, ctx *Context) (HandlerFunc, bool)
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, configs ...HandlerConfig)
OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle) Register specific middlewares through third parameter.
func (*Router) PATCH ¶
func (r *Router) PATCH(path string, handle HandlerFunc, configs ...HandlerConfig)
PATCH is a shortcut for router.Handle("PATCH", path, handle) Register specific middlewares through third parameter.
func (*Router) POST ¶
func (r *Router) POST(path string, handle HandlerFunc, configs ...HandlerConfig)
POST is a shortcut for router.Handle("POST", path, handle) Register specific middlewares through third parameter.
func (*Router) PUT ¶
func (r *Router) PUT(path string, handle HandlerFunc, configs ...HandlerConfig)
PUT is a shortcut for router.Handle("PUT", path, handle) Register specific middlewares through third parameter.
func (*Router) ServeFiles ¶
func (r *Router) ServeFiles(path string, rootPath string, configs ...HandlerConfig)
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.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server
func New ¶
func New(addr string, handler HandlerFunc) *Server
New returns a Server instance with default setting.
func (*Server) ListenAndServe ¶
ListenAndServe serves HTTP requests from the given TCP4 addr.
func (*Server) ListenAndServeTLS ¶
ListenAndServeTLS serves HTTPS requests from the given TCP4 addr.
certFile and keyFile are paths to TLS certificate and key files.
Pass custom listener to Serve if you need listening on non-TCP4 media such as IPv6.
func (*Server) ListenAndServeUNIX ¶
ListenAndServeUNIX serves HTTP requests from the given UNIX addr.
The function deletes existing file at addr before starting serving.
The server sets the given file mode for the UNIX addr.
func (*Server) LoadConfig ¶
func (srv *Server) LoadConfig(config *ServerConfig)
LoadConfig load server configuration.
func (*Server) SetSessionsStore ¶
SetSessionsStore set sessions store.
func (*Server) SetWaitTimeout ¶
SetWaitTimeout wait timeout.
type ServerConfig ¶
type ServerConfig struct {
// Server name for sending in response headers.
//
// Default server name is used if left blank.
Name string `json:"name"`
// The maximum number of concurrent connections the server may serve.
//
// DefaultConcurrency is used if not set.
Concurrency int `json:"concurrency"`
// Whether to disable keep-alive connections.
//
// The server will close all the incoming connections after sending
// the first response to client if this option is set to true.
//
// By default keep-alive connections are enabled.
DisableKeepalive bool `json:"disable_keepalive"`
// Per-connection buffer size for requests' reading.
// This also limits the maximum header size.
//
// Increase this buffer if your clients send multi-KB RequestURIs
// and/or multi-KB headers (for example, BIG cookies).
//
// Default buffer size is used if not set.
ReadBufferSize int `json:"read_buffer_size"`
// Per-connection buffer size for responses' writing.
//
// Default buffer size is used if not set.
WriteBufferSize int `json:"write_buffer_size"`
// Maximum duration for reading the full request (including body).
//
// This also limits the maximum duration for idle keep-alive
// connections.
//
// By default request read timeout is unlimited.
ReadTimeout time.Duration `json:"read_timeout"`
// Maximum duration for writing the full response (including body).
//
// By default response write timeout is unlimited.
WriteTimeout time.Duration `json:"write_timeout"`
// Maximum number of concurrent client connections allowed per IP.
//
// By default unlimited number of concurrent connections
// may be established to the server from a single IP address.
MaxConnsPerIP int `json:"max_conns_per_ip"`
// Maximum number of requests served per connection.
//
// The server closes connection after the last request.
// 'Connection: close' header is added to the last response.
//
// By default unlimited number of requests may be served per connection.
MaxRequestsPerConn int `json:"max_requests_per_conn"`
// Maximum keep-alive connection lifetime.
//
// The server closes keep-alive connection after its' lifetime
// expiration.
//
// See also ReadTimeout for limiting the duration of idle keep-alive
// connections.
//
// By default keep-alive connection lifetime is unlimited.
MaxKeepaliveDuration time.Duration `json:"max_keepalive_duration"`
// Maximum request body size.
//
// The server rejects requests with bodies exceeding this limit.
//
// Request body size is limited by DefaultMaxRequestBodySize by default.
MaxRequestBodySize int `json:"max_request_body_size"`
// Aggressively reduces memory usage at the cost of higher CPU usage
// if set to true.
//
// Try enabling this option only if the server consumes too much memory
// serving mostly idle keep-alive connections. This may reduce memory
// usage by more than 50%.
//
// Aggressive memory usage reduction is disabled by default.
ReduceMemoryUsage bool `json:"reduce_memory_usage"`
// Rejects all non-GET requests if set to true.
//
// This option is useful as anti-DoS protection for servers
// accepting only GET requests. The request size is limited
// by ReadBufferSize if GetOnly is set.
//
// Server accepts all the requests by default.
GetOnly bool `json:"get_only"`
// Header names are passed as-is without normalization
// if this option is set.
//
// Disabled header names' normalization may be useful only for proxying
// incoming requests to other servers expecting case-sensitive
// header names. See https://github.com/valyala/fasthttp/issues/57
// for details.
//
// By default request and response header names are normalized, i.e.
// The first letter and the first letters following dashes
// are uppercased, while all the other letters are lowercased.
// Examples:
//
// * HOST -> Host
// * content-type -> Content-Type
// * cONTENT-lenGTH -> Content-Length
DisableHeaderNamesNormalizing bool `json:"disable_header_names_normalizing"`
}
ServerConfig see fasthttp.Server for more details.
