improve comment for ghttp.Server

This commit is contained in:
John 2020-03-05 16:08:55 +08:00
parent f68b66e606
commit 7072244420
4 changed files with 54 additions and 39 deletions

View File

@ -95,23 +95,24 @@ func (r *Response) CORS(options CORSOptions) {
}
// No continue service handling if it's OPTIONS request.
if gstr.Equal(r.Request.Method, "OPTIONS") {
// Request method's handler searching.
// It here uses Server.routesMap attribute enhancing the searching performance.
// Request method handler searching.
// It here simply uses Server.routesMap attribute enhancing the searching performance.
if method := r.Request.Header.Get("Access-Control-Request-Method"); method != "" {
routerKey := ""
for _, domain := range []string{gDEFAULT_DOMAIN, r.Request.GetHost()} {
for _, v := range []string{gDEFAULT_METHOD, method} {
routerKey = r.Server.handlerKey("", v, r.Request.URL.Path, domain)
routerKey = r.Server.routerMapKey("", v, r.Request.URL.Path, domain)
if r.Server.routesMap[routerKey] != nil {
if r.Status == 0 {
r.Status = http.StatusOK
}
// No continue serving.
r.Request.ExitAll()
}
}
}
}
// Cannot find the request handler.
// Cannot find the request serving handler, it then responses 404.
if r.Status == 0 {
r.Status = http.StatusNotFound
}

View File

@ -28,8 +28,10 @@ var (
handlerIdGenerator = gtype.NewInt()
)
// handlerKey creates and returns an unique router key for given parameters.
func (s *Server) handlerKey(hook, method, path, domain string) string {
// routerMapKey creates and returns an unique router key for given parameters.
// This key is used for Server.routerMap attribute, which is mainly for checks for
// repeated router registering.
func (s *Server) routerMapKey(hook, method, path, domain string) string {
return hook + "%" + s.serveHandlerKey(method, path, domain)
}
@ -76,7 +78,7 @@ func (s *Server) setHandler(pattern string, handler *handlerItem) {
}
// Repeated router checks, this feature can be disabled by server configuration.
routerKey := s.handlerKey(handler.hookName, method, uri, domain)
routerKey := s.routerMapKey(handler.hookName, method, uri, domain)
if !s.config.RouteOverWrite {
switch handler.itemType {
case gHANDLER_TYPE_HANDLER, gHANDLER_TYPE_OBJECT, gHANDLER_TYPE_CONTROLLER:
@ -98,7 +100,7 @@ func (s *Server) setHandler(pattern string, handler *handlerItem) {
if _, ok := s.serveTree[domain]; !ok {
s.serveTree[domain] = make(map[string]interface{})
}
// List array, very important for router register.
// List array, very important for router registering.
// There may be multiple lists adding into this array when searching from root to leaf.
lists := make([]*glist.List, 0)
array := ([]string)(nil)

View File

@ -15,13 +15,24 @@ import (
"github.com/gogf/gf/text/gregex"
)
// handlerCacheItem is an item for router searching cache.
// handlerCacheItem is an item just for internal router searching cache.
type handlerCacheItem struct {
parsedItems []*handlerParsedItem
hasHook bool
hasServe bool
}
// serveHandlerKey creates and returns a handler key for router.
func (s *Server) serveHandlerKey(method, path, domain string) string {
if len(domain) > 0 {
domain = "@" + domain
}
if method == "" {
return path + strings.ToLower(domain)
}
return strings.ToUpper(method) + ":" + path + strings.ToLower(domain)
}
// getHandlersWithCache searches the router item with cache feature for given request.
func (s *Server) getHandlersWithCache(r *Request) (parsedItems []*handlerParsedItem, hasHook, hasServe bool) {
method := r.Method
@ -76,10 +87,12 @@ func (s *Server) searchHandlers(method, path, domain string) (parsedItems []*han
if part == "" {
continue
}
// Add all list of each node to the list array.
if v, ok := p.(map[string]interface{})["*list"]; ok {
lists = append(lists, v.(*glist.List))
}
if v, ok := p.(map[string]interface{})[part]; ok {
// Loop to the next node by certain key name.
p = v
if i == len(array)-1 {
if v, ok := p.(map[string]interface{})["*list"]; ok {
@ -87,33 +100,36 @@ func (s *Server) searchHandlers(method, path, domain string) (parsedItems []*han
break
}
}
} else {
if v, ok := p.(map[string]interface{})["*fuzz"]; ok {
p = v
}
} else if v, ok := p.(map[string]interface{})["*fuzz"]; ok {
// Loop to the next node by fuzzy node item.
p = v
}
// 如果是叶子节点,同时判断当前层级的"*fuzz"键名,解决例如:/user/*action 匹配 /user 的规则
if i == len(array)-1 {
// It here also checks the fuzzy item,
// for rule case like: "/user/*action" matches to "/user".
if v, ok := p.(map[string]interface{})["*fuzz"]; ok {
p = v
}
// The leaf must have a list item. It adds the list to the list array.
if v, ok := p.(map[string]interface{})["*list"]; ok {
lists = append(lists, v.(*glist.List))
}
}
}
// 多层链表遍历检索,从数组末尾的链表开始遍历,末尾的深度高优先级也高
// OK, let's loop the result list array, adding the handler item to the result handler result array.
// As the tail of the list array has the most priority, it iterates the list array from its tail to head.
for i := len(lists) - 1; i >= 0; i-- {
for e := lists[i].Front(); e != nil; e = e.Next() {
item := e.Value.(*handlerItem)
// 主要是用于路由注册函数的重复添加判断(特别是中间件和钩子函数)
// Filter repeated handler item, especially the middleware and hook handlers.
// It is necessary, do not remove this checks logic unless you really know how it is necessary.
if _, ok := repeatHandlerCheckMap[item.itemId]; ok {
continue
} else {
repeatHandlerCheckMap[item.itemId] = struct{}{}
}
// 服务路由函数只能添加一次,将重复判断放在这里提高检索效率
// Serving handler can only be added to the handler array just once.
if hasServe {
switch item.itemType {
case gHANDLER_TYPE_HANDLER, gHANDLER_TYPE_OBJECT, gHANDLER_TYPE_CONTROLLER:
@ -121,26 +137,29 @@ func (s *Server) searchHandlers(method, path, domain string) (parsedItems []*han
}
}
if item.router.Method == gDEFAULT_METHOD || item.router.Method == method {
// 注意当不带任何动态路由规则时,len(match) == 1
// Note the rule having no fuzzy rules: len(match) == 1
if match, err := gregex.MatchString(item.router.RegRule, path); err == nil && len(match) > 0 {
parsedItem := &handlerParsedItem{item, nil}
// 如果需要路由规则中带有URI名称匹配那么需要重新正则解析URL
// If the rule contains fuzzy names,
// it needs paring the URL to retrieve the values for the names.
if len(item.router.RegNames) > 0 {
if len(match) > len(item.router.RegNames) {
parsedItem.values = make(map[string]string)
// 如果存在存在同名路由参数名称,那么执行覆盖
// It there repeated names, it just overwrites the same one.
for i, name := range item.router.RegNames {
parsedItem.values[name] = match[i+1]
}
}
}
switch item.itemType {
// 服务路由函数只能添加一次
// The serving handler can be only added just once.
case gHANDLER_TYPE_HANDLER, gHANDLER_TYPE_OBJECT, gHANDLER_TYPE_CONTROLLER:
hasServe = true
parsedItemList.PushBack(parsedItem)
// 中间件需要排序在链表中服务函数之前,并且多个中间件按照顺序添加以便于后续执行
// The middleware is inserted before the serving handler.
// If there're multiple middlewares, they're inserted into the result list by their registering order.
// The middlewares are also executed by their registering order.
case gHANDLER_TYPE_MIDDLEWARE:
if lastMiddlewareElem == nil {
lastMiddlewareElem = parsedItemList.PushFront(parsedItem)
@ -148,7 +167,7 @@ func (s *Server) searchHandlers(method, path, domain string) (parsedItems []*han
lastMiddlewareElem = parsedItemList.InsertAfter(lastMiddlewareElem, parsedItem)
}
// 钩子函数存在性判断
// HOOK handler, just push it back to the list.
case gHANDLER_TYPE_HOOK:
hasHook = true
parsedItemList.PushBack(parsedItem)
@ -210,14 +229,3 @@ func (item *handlerItem) MarshalJSON() ([]byte, error) {
func (item *handlerParsedItem) MarshalJSON() ([]byte, error) {
return json.Marshal(item.handler)
}
// serveHandlerKey creates and returns a cache key for router.
func (s *Server) serveHandlerKey(method, path, domain string) string {
if len(domain) > 0 {
domain = "@" + domain
}
if method == "" {
return path + strings.ToLower(domain)
}
return strings.ToUpper(method) + ":" + path + strings.ToLower(domain)
}

View File

@ -39,7 +39,7 @@ func (s *Server) BindObjectRest(pattern string, object interface{}) {
}
func (s *Server) doBindObject(pattern string, object interface{}, method string, middleware []HandlerFunc) {
// Convert input method to map for convenience and high performance searching.
// Convert input method to map for convenience and high performance searching purpose.
var methodMap map[string]bool
if len(method) > 0 {
methodMap = make(map[string]bool)
@ -86,12 +86,16 @@ func (s *Server) doBindObject(pattern string, object interface{}, method string,
if !ok {
if len(methodMap) > 0 {
// 指定的方法名称注册,那么需要使用错误提示
s.Logger().Errorf(`invalid route method: %s.%s.%s defined as "%s", but "func(*ghttp.Request)" is required for object registry`,
pkgPath, objName, methodName, v.Method(i).Type().String())
s.Logger().Errorf(
`invalid route method: %s.%s.%s defined as "%s", but "func(*ghttp.Request)" is required for object registry`,
pkgPath, objName, methodName, v.Method(i).Type().String(),
)
} else {
// 否则只是Debug提示
s.Logger().Debugf(`ignore route method: %s.%s.%s defined as "%s", no match "func(*ghttp.Request)"`,
pkgPath, objName, methodName, v.Method(i).Type().String())
s.Logger().Debugf(
`ignore route method: %s.%s.%s defined as "%s", no match "func(*ghttp.Request)"`,
pkgPath, objName, methodName, v.Method(i).Type().String(),
)
}
continue
}