当前仓库属于关闭状态,部分功能使用受限,详情请查阅 仓库状态说明
17 Star 35 Fork 0

vz/ego
关闭

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
routergroup.go 11.26 KB
一键复制 编辑 原始数据 按行查看 历史
vz 提交于 2018-07-03 23:33 +08:00 . update router name and add hand
// 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.
// Copyright 2016 The go-ego Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// https://github.com/go-ego/ego/blob/master/LICENSE
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
package ego
import (
// "fmt"
"net/http"
"path"
"regexp"
"strings"
"github.com/go-ego/ego/mid/rego"
"github.com/go-ego/ego/mid/util"
)
type IRouter interface {
IRoutes
Group(string, ...HandlerFunc) *RouterGroup
}
type IRoutes interface {
Use(...HandlerFunc) IRoutes
Handle(string, string, ...HandlerFunc) IRoutes
Any(string, ...HandlerFunc) IRoutes
GET(string, ...HandlerFunc) IRoutes
POST(string, ...HandlerFunc) IRoutes
DELETE(string, ...HandlerFunc) IRoutes
PATCH(string, ...HandlerFunc) IRoutes
PUT(string, ...HandlerFunc) IRoutes
OPTIONS(string, ...HandlerFunc) IRoutes
HEAD(string, ...HandlerFunc) IRoutes
StaticFile(string, string) IRoutes
Static(string, string) IRoutes
StaticFS(string, http.FileSystem) IRoutes
}
// RouterGroup is used internally to configure router, a RouterGroup is associated with a prefix
// and an array of handlers (middleware).
type RouterGroup struct {
Handlers HandlersChain
basePath string
engine *Engine
root bool
}
var (
_ IRouter = &RouterGroup{}
rendersInt int
)
// Use adds middleware to the group, see example code in github.
func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes {
group.Handlers = append(group.Handlers, middleware...)
return group.returnObj()
}
// Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix.
// For example, all the routes that use a common middlware for authorization could be grouped.
func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {
return &RouterGroup{
Handlers: group.combineHandlers(handlers),
basePath: group.calculateAbsolutePath(relativePath),
engine: group.engine,
}
}
func (group *RouterGroup) BasePath() string {
return group.basePath
}
func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes {
absolutePath := group.calculateAbsolutePath(relativePath)
handlers = group.combineHandlers(handlers)
group.engine.addRoute(httpMethod, absolutePath, handlers)
return group.returnObj()
}
// Handle registers a new request handle and middleware with the given path and method.
// The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes.
// See the example code in github.
//
// 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 (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes {
if matches, err := regexp.MatchString("^[A-Z]+$", httpMethod); !matches || err != nil {
panic("http method " + httpMethod + " is not valid")
}
return group.handle(httpMethod, relativePath, handlers)
}
// POST is a shortcut for router.Handle("POST", path, handle).
func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes {
return group.handle("POST", relativePath, handlers)
}
// GET is a shortcut for router.Handle("GET", path, handle).
func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes {
return group.handle("GET", relativePath, handlers)
}
// DELETE is a shortcut for router.Handle("DELETE", path, handle).
func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes {
return group.handle("DELETE", relativePath, handlers)
}
// PATCH is a shortcut for router.Handle("PATCH", path, handle).
func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes {
return group.handle("PATCH", relativePath, handlers)
}
// PUT is a shortcut for router.Handle("PUT", path, handle).
func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes {
return group.handle("PUT", relativePath, handlers)
}
// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle).
func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes {
return group.handle("OPTIONS", relativePath, handlers)
}
// HEAD is a shortcut for router.Handle("HEAD", path, handle).
func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes {
return group.handle("HEAD", relativePath, handlers)
}
// Any registers a route that matches all the HTTP methods.
// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.
func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {
group.handle("GET", relativePath, handlers)
group.handle("POST", relativePath, handlers)
group.handle("PUT", relativePath, handlers)
group.handle("PATCH", relativePath, handlers)
group.handle("HEAD", relativePath, handlers)
group.handle("OPTIONS", relativePath, handlers)
group.handle("DELETE", relativePath, handlers)
group.handle("CONNECT", relativePath, handlers)
group.handle("TRACE", relativePath, handlers)
return group.returnObj()
}
// StaticFile registers a single route in order to serve a single file of
// the local filesystem.
// router.StaticFile("favicon.ico", "./resources/favicon.ico")
func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes {
if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {
panic("URL parameters can not be used when serving a static file")
}
handler := func(c *Context) {
c.File(filepath)
}
group.GET(relativePath, handler)
group.HEAD(relativePath, handler)
return group.returnObj()
}
// Static serves files from the given file system root.
// 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 :
// router.Static("/static", "/var/www")
func (group *RouterGroup) Static(relativePath, root string) IRoutes {
return group.StaticFS(relativePath, util.Dir(root, false))
}
func (group *RouterGroup) StaticT(relativePath, root string) IRoutes {
return group.StaticFS(relativePath, util.Dir(root, true))
}
// StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead.
// Ego by default user: util.Dir()
func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes {
if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {
panic("URL parameters can not be used when serving a static folder")
}
handler := group.createStaticHandler(relativePath, fs)
urlPattern := path.Join(relativePath, "/*filepath")
// Register GET and HEAD handlers
group.GET(urlPattern, handler)
group.HEAD(urlPattern, handler)
return group.returnObj()
}
func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc {
absolutePath := group.calculateAbsolutePath(relativePath)
fileServer := http.StripPrefix(absolutePath, http.FileServer(fs))
_, nolisting := fs.(*util.OnlyfilesFS)
return func(c *Context) {
if nolisting {
c.Writer.WriteHeader(http.StatusNotFound)
}
fileServer.ServeHTTP(c.Writer, c.Request)
}
}
func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain {
finalSize := len(group.Handlers) + len(handlers)
if finalSize >= int(abortIndex) {
panic("too many handlers")
}
mergedHandlers := make(HandlersChain, finalSize)
copy(mergedHandlers, group.Handlers)
copy(mergedHandlers[len(group.Handlers):], handlers)
return mergedHandlers
}
func (group *RouterGroup) calculateAbsolutePath(relativePath string) string {
return joinPaths(group.basePath, relativePath)
}
func (group *RouterGroup) returnObj() IRoutes {
if group.root {
return group.engine
}
return group
}
///////////// Router
// Go Router
func (group *RouterGroup) Go(url, name string, obj ...interface{}) {
var data interface{}
if len(obj) > 0 {
data = obj[0]
}
group.GET(url, func(c *Context) {
c.HTML(http.StatusOK, name, data)
})
}
// GoGroup
func (group *RouterGroup) GoGroup(rmap Map) {
for k, v := range rmap {
group.Go(k, v.(string))
}
}
func UseRenders() {
rendersInt = 1
}
// Ego Router
func (group *RouterGroup) Ego(url, name string, obj ...interface{}) {
// func (group *RouterGroup) EgoRouter(url, name string, obj ...interface{}) {
var data interface{}
if len(obj) > 0 {
data = obj[0]
}
if rendersInt == 1 {
tname := strings.Replace(name, ".html", "", -1)
rego.RendersVgo(tname)
}
var wname string
if strings.Contains(name, "/") {
sname := strings.Split(name, "/")
wname = sname[0] + "_" + sname[1]
} else {
wname = name
}
group.GET(url, func(c *Context) {
c.HTML(http.StatusOK, wname, data)
})
}
// EgoGroup
func (group *RouterGroup) EgoGroup(rmap Map) {
for k, v := range rmap {
group.Ego(k, v.(string))
}
}
// Hand hand map router func(*Context)
func (group *RouterGroup) Hand(rmap Map, args ...string) {
var method = "POST"
if len(args) > 0 {
method = args[0]
}
for k, v := range rmap {
group.Handle(method, k, v.(func(*Context)))
}
}
/* __ __ .___________.___________..______ _______ .______ .______ ______ .______
| | | | | | || _ \ | ____|| _ \ | _ \ / __ \ | _ \
| |__| | `---| |----`---| |----`| |_) | | |__ | |_) | | |_) | | | | | | |_) |
| __ | | | | | | ___/ | __| | / | / | | | | | /
| | | | | | | | | | | |____ | |\ \----.| |\ \----.| `--' | | |\ \----.
|__| |__| |__| |__| | _| |_______|| _| `._____|| _| `._____| \______/ | _| `._____|
*/
// Go404 configurates http.HandlerFunc which is called when no matching route is
// found. If it is not set, http.NotFound is used.
// Be sure to set 404 response code in your handler.
func Go404(html string) {
var c *Context
c.Next()
c.HTML(http.StatusNotFound, html, nil)
}
// NotFound configurates http.HandlerFunc which is called when no matching route is
// found. If it is not set, http.NotFound is used.
// Be sure to set 404 response code in your handler.
func (router *Engine) NotFound(html ...string) {
html404 := "404.html"
if len(html) > 0 {
html404 = html[0]
}
router.Use(func(c *Context) {
c.Next()
c.HTML(http.StatusNotFound, html404, nil)
})
}
// Go500 configurates handler which is called when route handler returns
// error. If it is not set, default handler is used.
// Be sure to set 500 response code in your handler.
func (router *Engine) Go500(html ...string) {
html500 := "500.html"
if len(html) > 0 {
html500 = html[0]
}
router.Use(func(c *Context) {
c.Next()
errorToPrint := c.Errors.ByType(util.ErrorTypePublic).Last()
if errorToPrint != nil {
c.HTML(500, html500, nil)
}
})
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/veni0/ego.git
git@gitee.com:veni0/ego.git
veni0
ego
ego
master

搜索帮助