woodpecker/vendor/github.com/gin-gonic/gin/gin.go

371 lines
11 KiB
Go
Raw Normal View History

2015-05-22 18:37:40 +00:00
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"html/template"
"net"
"net/http"
"os"
"sync"
2015-09-30 01:21:17 +00:00
"github.com/gin-gonic/gin/render"
2015-05-22 18:37:40 +00:00
)
2015-09-30 01:21:17 +00:00
// Framework's version
const Version = "v1.0rc2"
2015-05-22 18:37:40 +00:00
var default404Body = []byte("404 page not found")
var default405Body = []byte("405 method not allowed")
2015-09-30 01:21:17 +00:00
type HandlerFunc func(*Context)
type HandlersChain []HandlerFunc
// Last returns the last handler in the chain. ie. the last handler is the main own.
func (c HandlersChain) Last() HandlerFunc {
length := len(c)
if length > 0 {
return c[length-1]
}
return nil
}
2015-05-22 18:37:40 +00:00
type (
2015-09-30 01:21:17 +00:00
RoutesInfo []RouteInfo
RouteInfo struct {
Method string
Path string
Handler string
}
2015-05-22 18:37:40 +00:00
2015-09-30 01:21:17 +00:00
// Engine is the framework's instance, it contains the muxer, middleware and configuration settings.
// Create an instance of Engine, by using New() or Default()
2015-05-22 18:37:40 +00:00
Engine struct {
RouterGroup
HTMLRender render.HTMLRender
allNoRoute HandlersChain
allNoMethod HandlersChain
noRoute HandlersChain
noMethod HandlersChain
2015-09-30 01:21:17 +00:00
pool sync.Pool
trees methodTrees
2015-05-22 18:37:40 +00:00
// 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
2015-09-30 01:21:17 +00:00
ForwardedByClientIP bool
2015-05-22 18:37:40 +00:00
}
)
2015-09-30 01:21:17 +00:00
var _ IRouter = &Engine{}
// New returns a new blank Engine instance without any middleware attached.
// By default the configuration is:
// - RedirectTrailingSlash: true
// - RedirectFixedPath: false
// - HandleMethodNotAllowed: false
// - ForwardedByClientIP: true
2015-05-22 18:37:40 +00:00
func New() *Engine {
2015-09-30 01:21:17 +00:00
debugPrintWARNINGNew()
2015-05-22 18:37:40 +00:00
engine := &Engine{
RouterGroup: RouterGroup{
Handlers: nil,
2015-09-30 01:21:17 +00:00
basePath: "/",
root: true,
2015-05-22 18:37:40 +00:00
},
RedirectTrailingSlash: true,
2015-09-30 01:21:17 +00:00
RedirectFixedPath: false,
HandleMethodNotAllowed: false,
ForwardedByClientIP: true,
trees: make(methodTrees, 0, 9),
2015-05-22 18:37:40 +00:00
}
engine.RouterGroup.engine = engine
engine.pool.New = func() interface{} {
return engine.allocateContext()
}
return engine
}
2015-09-30 01:21:17 +00:00
// Default returns an Engine instance with the Logger and Recovery middleware already attached.
2015-05-22 18:37:40 +00:00
func Default() *Engine {
engine := New()
2016-03-07 19:23:49 +00:00
engine.Use(Logger(), Recovery())
2015-05-22 18:37:40 +00:00
return engine
}
2015-09-30 01:21:17 +00:00
func (engine *Engine) allocateContext() *Context {
return &Context{engine: engine}
2015-05-22 18:37:40 +00:00
}
func (engine *Engine) LoadHTMLGlob(pattern string) {
if IsDebugging() {
2015-09-30 01:21:17 +00:00
debugPrintLoadTemplate(template.Must(template.ParseGlob(pattern)))
2015-05-22 18:37:40 +00:00
engine.HTMLRender = render.HTMLDebug{Glob: pattern}
} else {
templ := template.Must(template.ParseGlob(pattern))
engine.SetHTMLTemplate(templ)
}
}
func (engine *Engine) LoadHTMLFiles(files ...string) {
if IsDebugging() {
engine.HTMLRender = render.HTMLDebug{Files: files}
} else {
templ := template.Must(template.ParseFiles(files...))
engine.SetHTMLTemplate(templ)
}
}
func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
2015-09-30 01:21:17 +00:00
if len(engine.trees) > 0 {
debugPrintWARNINGSetHTMLTemplate()
}
2015-05-22 18:37:40 +00:00
engine.HTMLRender = render.HTMLProduction{Template: templ}
}
// Adds handlers for NoRoute. It return a 404 code by default.
func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
engine.noRoute = handlers
engine.rebuild404Handlers()
}
2015-09-30 01:21:17 +00:00
// Sets the handlers called when... TODO
2015-05-22 18:37:40 +00:00
func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
engine.noMethod = handlers
engine.rebuild405Handlers()
}
2015-09-30 01:21:17 +00:00
// Attachs a global middleware to the router. ie. the middleware attached though Use() will be
// included in the handlers chain for every single request. Even 404, 405, static files...
// For example, this is the right place for a logger or error management middleware.
func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {
engine.RouterGroup.Use(middleware...)
2015-05-22 18:37:40 +00:00
engine.rebuild404Handlers()
engine.rebuild405Handlers()
2015-09-30 01:21:17 +00:00
return engine
2015-05-22 18:37:40 +00:00
}
func (engine *Engine) rebuild404Handlers() {
engine.allNoRoute = engine.combineHandlers(engine.noRoute)
}
func (engine *Engine) rebuild405Handlers() {
engine.allNoMethod = engine.combineHandlers(engine.noMethod)
}
func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {
2016-03-07 19:23:49 +00:00
assert1(path[0] == '/', "path must begin with '/'")
assert1(len(method) > 0, "HTTP method can not be empty")
assert1(len(handlers) > 0, "there must be at least one handler")
2015-05-22 18:37:40 +00:00
2016-03-07 19:23:49 +00:00
debugPrintRoute(method, path, handlers)
2015-09-30 01:21:17 +00:00
root := engine.trees.get(method)
2015-05-22 18:37:40 +00:00
if root == nil {
root = new(node)
2016-03-07 19:23:49 +00:00
engine.trees = append(engine.trees, methodTree{method: method, root: root})
2015-05-22 18:37:40 +00:00
}
root.addRoute(path, handlers)
}
2015-09-30 01:21:17 +00:00
// Routes returns a slice of registered routes, including some useful information, such as:
// the http method, path and the handler name.
func (engine *Engine) Routes() (routes RoutesInfo) {
for _, tree := range engine.trees {
routes = iterate("", tree.method, routes, tree.root)
}
return routes
}
func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo {
path += root.path
if len(root.handlers) > 0 {
routes = append(routes, RouteInfo{
Method: method,
Path: path,
Handler: nameOfFunction(root.handlers.Last()),
})
}
for _, child := range root.children {
routes = iterate(path, method, routes, child)
}
return routes
}
// Run attaches the router to a http.Server and starts listening and serving HTTP requests.
// It is a shortcut for http.ListenAndServe(addr, router)
2016-03-07 19:23:49 +00:00
// Note: this method will block the calling goroutine indefinitely unless an error happens.
2015-09-30 01:21:17 +00:00
func (engine *Engine) Run(addr ...string) (err error) {
2015-05-22 18:37:40 +00:00
defer func() { debugPrintError(err) }()
2015-09-30 01:21:17 +00:00
address := resolveAddress(addr)
debugPrint("Listening and serving HTTP on %s\n", address)
err = http.ListenAndServe(address, engine)
2015-05-22 18:37:40 +00:00
return
}
2015-09-30 01:21:17 +00:00
// RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests.
// It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router)
2016-03-07 19:23:49 +00:00
// Note: this method will block the calling goroutine indefinitely unless an error happens.
2015-09-30 01:21:17 +00:00
func (engine *Engine) RunTLS(addr string, certFile string, keyFile string) (err error) {
2015-05-22 18:37:40 +00:00
debugPrint("Listening and serving HTTPS on %s\n", addr)
defer func() { debugPrintError(err) }()
2015-09-30 01:21:17 +00:00
err = http.ListenAndServeTLS(addr, certFile, keyFile, engine)
2015-05-22 18:37:40 +00:00
return
}
2015-09-30 01:21:17 +00:00
// RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests
// through the specified unix socket (ie. a file).
2016-03-07 19:23:49 +00:00
// Note: this method will block the calling goroutine indefinitely unless an error happens.
2015-05-22 18:37:40 +00:00
func (engine *Engine) RunUnix(file string) (err error) {
debugPrint("Listening and serving HTTP on unix:/%s", file)
defer func() { debugPrintError(err) }()
os.Remove(file)
listener, err := net.Listen("unix", file)
if err != nil {
return
}
defer listener.Close()
err = http.Serve(listener, engine)
return
}
2015-09-30 01:21:17 +00:00
// Conforms to the http.Handler interface.
2015-05-22 18:37:40 +00:00
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
c := engine.pool.Get().(*Context)
c.writermem.reset(w)
c.Request = req
c.reset()
2015-09-30 01:21:17 +00:00
engine.handleHTTPRequest(c)
2015-05-22 18:37:40 +00:00
engine.pool.Put(c)
}
func (engine *Engine) handleHTTPRequest(context *Context) {
httpMethod := context.Request.Method
path := context.Request.URL.Path
// Find root of the tree for the given HTTP method
2015-09-30 01:21:17 +00:00
t := engine.trees
for i, tl := 0, len(t); i < tl; i++ {
if t[i].method == httpMethod {
root := t[i].root
// Find route in tree
handlers, params, tsr := root.getValue(path, context.Params)
if handlers != nil {
context.handlers = handlers
context.Params = params
context.Next()
context.writermem.WriteHeaderNow()
2015-05-22 18:37:40 +00:00
return
2015-09-30 01:21:17 +00:00
} else if httpMethod != "CONNECT" && path != "/" {
if tsr && engine.RedirectTrailingSlash {
redirectTrailingSlash(context)
return
}
if engine.RedirectFixedPath && redirectFixedPath(context, root, engine.RedirectFixedPath) {
return
}
2015-05-22 18:37:40 +00:00
}
2015-09-30 01:21:17 +00:00
break
2015-05-22 18:37:40 +00:00
}
}
2015-09-30 01:21:17 +00:00
// TODO: unit test
2015-05-22 18:37:40 +00:00
if engine.HandleMethodNotAllowed {
2015-09-30 01:21:17 +00:00
for _, tree := range engine.trees {
if tree.method != httpMethod {
if handlers, _, _ := tree.root.getValue(path, nil); handlers != nil {
2015-05-22 18:37:40 +00:00
context.handlers = engine.allNoMethod
serveError(context, 405, default405Body)
return
}
}
}
}
context.handlers = engine.allNoRoute
serveError(context, 404, default404Body)
}
2015-09-30 01:21:17 +00:00
var mimePlain = []string{MIMEPlain}
func serveError(c *Context, code int, defaultMessage []byte) {
c.writermem.status = code
c.Next()
if !c.writermem.Written() {
if c.writermem.Status() == code {
c.writermem.Header()["Content-Type"] = mimePlain
c.Writer.Write(defaultMessage)
} else {
c.writermem.WriteHeaderNow()
}
}
}
func redirectTrailingSlash(c *Context) {
2015-05-22 18:37:40 +00:00
req := c.Request
path := req.URL.Path
code := 301 // Permanent redirect, request with GET method
if req.Method != "GET" {
code = 307
}
2015-09-30 01:21:17 +00:00
if len(path) > 1 && path[len(path)-1] == '/' {
req.URL.Path = path[:len(path)-1]
} else {
req.URL.Path = path + "/"
}
debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
http.Redirect(c.Writer, req, req.URL.String(), code)
c.writermem.WriteHeaderNow()
}
func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool {
req := c.Request
path := req.URL.Path
fixedPath, found := root.findCaseInsensitivePath(
cleanPath(path),
trailingSlash,
)
if found {
code := 301 // Permanent redirect, request with GET method
if req.Method != "GET" {
code = 307
2015-05-22 18:37:40 +00:00
}
2015-09-30 01:21:17 +00:00
req.URL.Path = string(fixedPath)
2015-05-22 18:37:40 +00:00
debugPrint("redirecting request %d: %s --> %s", code, path, req.URL.String())
http.Redirect(c.Writer, req, req.URL.String(), code)
c.writermem.WriteHeaderNow()
return true
}
return false
}