// Copyright 2013 Julien Schmidt. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found
// at https://github.com/julienschmidt/httprouter/blob/master/LICENSE
package gin
import (
"bytes"
"net/url"
"strings"
"unicode"
"unicode/utf8"
"github.com/gin-gonic/gin/internal/bytesconv"
)
var (
strColon = []byte(":")
strStar = []byte("*")
strSlash = []byte("/")
)
// Param is a single URL parameter, consisting of a key and a value.
// Param是一个URL参数,由一个键和一个值组成。
type Param struct {
Key string
Value string
}
// Params is a Param-slice, as returned by the router.
// Params是一个由路由器返回的Param切片。
// The slice is ordered, the first URL parameter is also the first slice value.
// 切片是有序的,第一个URL参数也是第一个切片值。
// It is therefore safe to read values by the index.
// 因此,通过索引读取值是安全的。
type Params []Param
// Get returns the value of the first Param which key matches the given name and a boolean true.
// Get返回与给定名称匹配的第一个Param的值,并返回布尔值true。
// If no matching Param is found, an empty string is returned and a boolean false .
// 如果没有找到匹配的Param,则返回一个空字符串和一个布尔值false。
func (ps Params) Get(name string) (string, bool) {
for _, entry := range ps {
if entry.Key == name {
return entry.Value, true
}
}
return "", false
}
// ByName returns the value of the first Param which key matches the given name.
// ByName返回与给定名称匹配的键的第一个Param的值。
// If no matching Param is found, an empty string is returned.
// 如果没有找到匹配的Param,则返回一个空字符串。
func (ps Params) ByName(name string) (va string) {
va, _ = ps.Get(name)
return
}
type methodTree struct {
method string
root *node
}
type methodTrees []methodTree
func (trees methodTrees) get(method string) *node {
for _, tree := range trees {
if tree.method == method {
return tree.root
}
}
return nil
}
func min(a, b int) int {
if a <= b {
return a
}
return b
}
func longestCommonPrefix(a, b string) int {
i := 0
max := min(len(a), len(b))
for i < max && a[i] == b[i] {
i++
}
return i
}
// addChild will add a child node, keeping wildcardChild at the end
// addChild将添加一个子节点,并在末尾保留wildcardChild
func (n *node) addChild(child *node) {
if n.wildChild && len(n.children) > 0 {
wildcardChild := n.children[len(n.children)-1]
n.children = append(n.children[:len(n.children)-1], child, wildcardChild)
} else {
n.children = append(n.children, child)
}
}
func countParams(path string) uint16 {
var n uint16
s := bytesconv.StringToBytes(path)
n += uint16(bytes.Count(s, strColon))
n += uint16(bytes.Count(s, strStar))
return n
}
func countSections(path string) uint16 {
s := bytesconv.StringToBytes(path)
return uint16(bytes.Count(s, strSlash))
}
type nodeType uint8
const (
static nodeType = iota
root
param
catchAll
)
type node struct {
path string
indices string
wildChild bool
nType nodeType
priority uint32
children []*node // child nodes, at most 1 :param style node at the end of the array 子节点,数组末尾最多1:param样式的节点
handlers HandlersChain
fullPath string
}
// Increments priority of the given child and reorders if necessary
// Increments给定子项的优先级,并在必要时重新排序
func (n *node) incrementChildPrio(pos int) int {
cs := n.children
cs[pos].priority++
prio := cs[pos].priority
// Adjust position (move to front) 调整位置(向前移动)
newPos := pos
for ; newPos > 0 && cs[newPos-1].priority < prio; newPos-- {
// Swap node positions 交换节点位置
cs[newPos-1], cs[newPos] = cs[newPos], cs[newPos-1]
}
// Build new index char string 生成新的索引字符串
if newPos != pos {
n.indices = n.indices[:newPos] + // Unchanged prefix, might be empty 未更改的前缀,可能为空
n.indices[pos:pos+1] + // The index char we move 我们移动的索引字符
n.indices[newPos:pos] + n.indices[pos+1:] // Rest without char at 'pos' 在“pos”处无字符休息
}
return newPos
}
// addRoute adds a node with the given handle to the path.
// addRoute将具有给定句柄的节点添加到路径中。
// Not concurrency-safe! 不安全并发!
func (n *node) addRoute(path string, handlers HandlersChain) {
fullPath := path
n.priority++
// Empty tree
if len(n.path) == 0 && len(n.children) == 0 {
n.insertChild(path, fullPath, handlers)
n.nType = root
return
}
parentFullPathIndex := 0
walk:
for {
// Find the longest common prefix. 查找最长的公共前缀
// This also implies that the common prefix contains no ':' or '*'
// since the existing key can't contain those chars.
// 这也意味着公共前缀不包含“:”或“*”,因为现有密钥不能包含这些字符。
i := longestCommonPrefix(path, n.path)
// Split edge
if i < len(n.path) {
child := node{
path: n.path[i:],
wildChild: n.wildChild,
nType: static,
indices: n.indices,
children: n.children,
handlers: n.handlers,
priority: n.priority - 1,
fullPath: n.fullPath,
}
n.children = []*node{&child}
// []byte for proper unicode char conversion, see #65 []字节,以进行正确的unicode字符转换,请参阅#65
n.indices = bytesconv.BytesToString([]byte{n.path[i]})
n.path = path[:i]
n.handlers = nil
n.wildChild = false
n.fullPath = fullPath[:parentFullPathIndex+i]
}
// Make new node a child of this node 使新节点成为此节点的子节点
if i < len(path) {
path = path[i:]
c := path[0]
// '/' after param
if n.nType == param && c == '/' && len(n.children) == 1 {
parentFullPathIndex += len(n.path)
n = n.children[0]
n.priority++
continue walk
}
// Check if a child with the next path byte exists 检查是否存在具有下一个路径字节的子级
for i, max := 0, len(n.indices); i < max; i++ {
if c == n.indices[i] {
parentFullPathIndex += len(n.path)
i = n.incrementChildPrio(i)
n = n.children[i]
continue walk
}
}
// Otherwise insert it 否则插入
if c != ':' && c != '*' && n.nType != catchAll {
// []byte for proper unicode char conversion, see #65 []字节,以进行正确的unicode字符转换,请参阅#65
n.indices += bytesconv.BytesToString([]byte{c})
child := &node{
fullPath: fullPath,
}
n.addChild(child)
n.incrementChildPrio(len(n.indices) - 1)
n = child
} else if n.wildChild {
// inserting a wildcard node, need to check if it conflicts with the existing wildcard
// 插入通配符节点,需要检查它是否与现有通配符冲突
n = n.children[len(n.children)-1]
n.priority++
// Check if the wildcard matches
// 检查通配符是否匹配
if len(path) >= len(n.path) && n.path == path[:len(n.path)] &&
// Adding a child to a catchAll is not possible
// 无法将子项添加到catchAll
n.nType != catchAll &&
// Check for longer wildcard, e.g. :name and :names
// 检查较长的通配符,例如:name和:names
(len(n.path) >= len(path) || path[len(n.path)] == '/') {
continue walk
}
// Wildcard conflict 通配符冲突
pathSeg := path
if n.nType != catchAll {
pathSeg = strings.SplitN(pathSeg, "/", 2)[0]
}
prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path
panic("'" + pathSeg +
"' in new path '" + fullPath +
"' conflicts with existing wildcard '" + n.path +
"' in existing prefix '" + prefix +
"'")
}
n.insertChild(path, fullPath, handlers)
return
}
// Otherwise add handle to current node 否则,将句柄添加到当前节点
if n.handlers != nil {
panic("handlers are already registered for path '" + fullPath + "'")
}
n.handlers = handlers
n.fullPath = fullPath
return
}
}
// Search for a wildcard segment and check the name for invalid characters.
// 搜索通配符段,并检查名称中是否有无效字符。
// Returns -1 as index, if no wildcard was found.
// 如果未找到通配符,则返回-1作为索引。
func findWildcard(path string) (wildcard string, i int, valid bool) {
// Find start 查找开始
for start, c := range []byte(path) {
// A wildcard starts with ':' (param) or '*' (catch-all)
// 通配符以“:”(param)或“*”(catch-all)开头
if c != ':' && c != '*' {
continue
}
// Find end and check for invalid characters 查找结尾并检查无效字符
valid = true
for end, c := range []byte(path[start+1:]) {
switch c {
case '/':
return path[start : start+1+end], start, valid
case ':', '*':
valid = false
}
}
return path[start:], start, valid
}
return "", -1, false
}
func (n *node) insertChild(path string, fullPath string, handlers HandlersChain) {
for {
// Find prefix until first wildcard 查找前缀直到第一个通配符
wildcard, i, valid := findWildcard(path)
if i < 0 { // No wildcard found
break
}
// The wildcard name must only contain one ':' or '*' character
// 通配符名称只能包含一个“:”或“*”字符
if !valid {
panic("only one wildcard per path segment is allowed, has: '" +
wildcard + "' in path '" + fullPath + "'")
}
// check if the wildcard has a name
// 检查通配符是否有名称
if len(wildcard) < 2 {
// 通配符在路径中必须使用非空名称命名
panic("wildcards must be named with a non-empty name in path '" + fullPath + "'")
}
if wildcard[0] == ':' { // param
if i > 0 {
// Insert prefix before the current wildcard
// 在当前通配符之前插入前缀
n.path = path[:i]
path = path[i:]
}
child := &node{
nType: param,
path: wildcard,
fullPath: fullPath,
}
n.addChild(child)
n.wildChild = true
n = child
n.priority++
// if the path doesn't end with the wildcard, then there
// will be another subpath starting with '/'
// 如果路径没有以通配符结尾,则会有另一个子路径以“/”开头
if len(wildcard) < len(path) {
path = path[len(wildcard):]
child := &node{
priority: 1,
fullPath: fullPath,
}
n.addChild(child)
n = child
continue
}
// Otherwise we're done. Insert the handle in the new leaf
// 否则我们就完了。将手柄插入新叶片
n.handlers = handlers
return
}
// catchAll
if i+len(wildcard) != len(path) {
panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'")
}
if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {
pathSeg := strings.SplitN(n.children[0].path, "/", 2)[0]
panic("catch-all wildcard '" + path +
"' in new path '" + fullPath +
"' conflicts with existing path segment '" + pathSeg +
"' in existing prefix '" + n.path + pathSeg +
"'")
}
// currently fixed width 1 for '/' “/”的当前固定宽度1
i--
if path[i] != '/' {
panic("no / before catch-all in path '" + fullPath + "'")
}
n.path = path[:i]
// First node: catchAll node with empty path
// 第一个节点:具有空路径的catchAll节点
child := &node{
wildChild: true,
nType: catchAll,
fullPath: fullPath,
}
n.addChild(child)
n.indices = string('/')
n = child
n.priority++
// second node: node holding the variable
// 第二个节点:保存变量的节点
child = &node{
path: path[i:],
nType: catchAll,
handlers: handlers,
priority: 1,
fullPath: fullPath,
}
n.children = []*node{child}
return
}
// If no wildcard was found, simply insert the path and handle
// 如果没有找到通配符,只需插入路径和句柄
n.path = path
n.handlers = handlers
n.fullPath = fullPath
}
// nodeValue holds return values of (*Node).getValue method
// nodeValue保存(*Node).getValue方法的返回值
type nodeValue struct {
handlers HandlersChain
params *Params
tsr bool
fullPath string
}
type skippedNode struct {
path string
node *node
paramsCount int16
}
// Returns the handle registered with the given path (key). The values of
// wildcards are saved to a map.
// 返回使用给定路径(键)注册的句柄。通配符的值将保存到映射中。
// If no handle can be found, a TSR (trailing slash redirect) recommendation is
// made if a handle exists with an extra (without the) trailing slash for the
// given path.
// 如果找不到句柄,则如果存在一个为给定路径添加额外(没有)尾部斜杠的句柄,则会提出TSR(尾部斜杠重定向)建议。
func (n *node) getValue(path string, params *Params, skippedNodes *[]skippedNode, unescape bool) (value nodeValue) {
var globalParamsCount int16
walk: // Outer loop for walking the tree 用于走树的外环
for {
prefix := n.path
if len(path) > len(prefix) {
if path[:len(prefix)] == prefix {
path = path[len(prefix):]
// Try all the non-wildcard children first by matching the indices 通过匹配索引,首先尝试所有非通配符子项
idxc := path[0]
for i, c := range []byte(n.indices) {
if c == idxc {
// strings.HasPrefix(n.children[len(n.children)-1].path, ":") == n.wildChild
if n.wildChild {
index := len(*skippedNodes)
*skippedNodes = (*skippedNodes)[:index+1]
(*skippedNodes)[index] = skippedNode{
path: prefix + path,
node: &node{
path: n.path,
wildChild: n.wildChild,
nType: n.nType,
priority: n.priority,
children: n.children,
handlers: n.handlers,
fullPath: n.fullPath,
},
paramsCount: globalParamsCount,
}
}
n = n.children[i]
continue walk
}
}
if !n.wildChild {
// If the path at the end of the loop is not equal to '/' and the current node has no child nodes
// the current node needs to roll back to last valid skippedNode
// 如果循环末尾的路径不等于“/”,并且当前节点没有子节点,则当前节点需要回滚到最后一个有效的skippedNode
if path != "/" {
for length := len(*skippedNodes); length > 0; length-- {
skippedNode := (*skippedNodes)[length-1]
*skippedNodes = (*skippedNodes)[:length-1]
if strings.HasSuffix(skippedNode.path, path) {
path = skippedNode.path
n = skippedNode.node
if value.params != nil {
*value.params = (*value.params)[:skippedNode.paramsCount]
}
globalParamsCount = skippedNode.paramsCount
continue walk
}
}
}
// Nothing found.
// We can recommend to redirect to the same URL without a
// trailing slash if a leaf exists for that path.
// 如果该路径存在叶,我们可以建议重定向到相同的URL,而不使用尾部斜杠。
value.tsr = path == "/" && n.handlers != nil
return
}
// Handle wildcard child, which is always at the end of the array
// 处理通配符子项,该子项始终位于数组的末尾
n = n.children[len(n.children)-1]
globalParamsCount++
switch n.nType {
case param:
// fix truncate the parameter 修复截断参数的问题
// tree_test.go line: 204
// Find param end (either '/' or path end) 查找参数结尾(“/”或路径结尾)
end := 0
for end < len(path) && path[end] != '/' {
end++
}
// Save param value 保存参数值
if params != nil && cap(*params) > 0 {
if value.params == nil {
value.params = params
}
// Expand slice within preallocated capacity 在预先分配的容量内扩展切片
i := len(*value.params)
*value.params = (*value.params)[:i+1]
val := path[:end]
if unescape {
if v, err := url.QueryUnescape(val); err == nil {
val = v
}
}
(*value.params)[i] = Param{
Key: n.path[1:],
Value: val,
}
}
// we need to go deeper! 我们需要更深入!
if end < len(path) {
if len(n.children) > 0 {
path = path[end:]
n = n.children[0]
continue walk
}
// ... but we can't
value.tsr = len(path) == end+1
return
}
if value.handlers = n.handlers; value.handlers != nil {
value.fullPath = n.fullPath
return
}
if len(n.children) == 1 {
// No handle found. Check if a handle for this path + a
// trailing slash exists for TSR recommendation
// 找不到句柄。检查是否存在此路径的句柄+TSR建议的尾部斜线
n = n.children[0]
value.tsr = (n.path == "/" && n.handlers != nil) || (n.path == "" && n.indices == "/")
}
return
case catchAll:
// Save param value
if params != nil {
if value.params == nil {
value.params = params
}
// Expand slice within preallocated capacity
// 在预先分配的容量内扩展切片
i := len(*value.params)
*value.params = (*value.params)[:i+1]
val := path
if unescape {
if v, err := url.QueryUnescape(path); err == nil {
val = v
}
}
(*value.params)[i] = Param{
Key: n.path[2:],
Value: val,
}
}
value.handlers = n.handlers
value.fullPath = n.fullPath
return
default:
panic("invalid node type")
}
}
}
if path == prefix {
// If the current path does not equal '/' and the node does not have a registered handle and the most recently matched node has a child node
// the current node needs to roll back to last valid skippedNode
// 如果当前路径不等于“/”,并且节点没有注册句柄,并且最近匹配的节点有一个子节点,则当前节点需要回滚到最后一个有效的skippedNode
if n.handlers == nil && path != "/" {
for length := len(*skippedNodes); length > 0; length-- {
skippedNode := (*skippedNodes)[length-1]
*skippedNodes = (*skippedNodes)[:length-1]
if strings.HasSuffix(skippedNode.path, path) {
path = skippedNode.path
n = skippedNode.node
if value.params != nil {
*value.params = (*value.params)[:skippedNode.paramsCount]
}
globalParamsCount = skippedNode.paramsCount
continue walk
}
}
// n = latestNode.children[len(latestNode.children)-1]
}
// We should have reached the node containing the handle.
// Check if this node has a handle registered.
// 我们应该已经到达包含句柄的节点。请检查此节点是否已注册句柄。
if value.handlers = n.handlers; value.handlers != nil {
value.fullPath = n.fullPath
return
}
// If there is no handle for this route, but this route has a
// wildcard child, there must be a handle for this path with an
// additional trailing slash
// 如果此路由没有句柄,但此路由有一个通配符子路径,则此路径必须有一个带有附加尾部斜杠的句柄
if path == "/" && n.wildChild && n.nType != root {
value.tsr = true
return
}
if path == "/" && n.nType == static {
value.tsr = true
return
}
// No handle found. Check if a handle for this path + a
// trailing slash exists for trailing slash recommendation
// 找不到句柄。检查是否存在此路径的句柄+用于尾部斜线建议的尾部斜线
for i, c := range []byte(n.indices) {
if c == '/' {
n = n.children[i]
value.tsr = (len(n.path) == 1 && n.handlers != nil) ||
(n.nType == catchAll && n.children[0].handlers != nil)
return
}
}
return
}
// Nothing found. We can recommend to redirect to the same URL with an
// extra trailing slash if a leaf exists for that path
// 未找到任何内容。如果该路径存在叶,我们可以建议使用额外的尾部斜杠重定向到相同的URL
value.tsr = path == "/" ||
(len(prefix) == len(path)+1 && prefix[len(path)] == '/' &&
path == prefix[:len(prefix)-1] && n.handlers != nil)
// roll back to last valid skippedNode 回滚到最后一个有效的skippedNode
if !value.tsr && path != "/" {
for length := len(*skippedNodes); length > 0; length-- {
skippedNode := (*skippedNodes)[length-1]
*skippedNodes = (*skippedNodes)[:length-1]
if strings.HasSuffix(skippedNode.path, path) {
path = skippedNode.path
n = skippedNode.node
if value.params != nil {
*value.params = (*value.params)[:skippedNode.paramsCount]
}
globalParamsCount = skippedNode.paramsCount
continue walk
}
}
}
return
}
}
// Makes a case-insensitive lookup of the given path and tries to find a handler.
// It can optionally also fix trailing slashes.
// 对给定的路径进行不区分大小写的查找,并尝试找到一个处理程序。它还可以选择性地修复尾部斜杠。
// It returns the case-corrected path and a bool indicating whether the lookup
// was successful.
// 它返回大小写校正后的路径和一个指示查找是否成功的bool。
func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) ([]byte, bool) {
const stackBufSize = 128
// Use a static sized buffer on the stack in the common case. 在常见情况下,在堆栈上使用静态大小的缓冲区。
// If the path is too long, allocate a buffer on the heap instead. 如果路径太长,请改为在堆上分配一个缓冲区。
buf := make([]byte, 0, stackBufSize)
if length := len(path) + 1; length > stackBufSize {
buf = make([]byte, 0, length)
}
ciPath := n.findCaseInsensitivePathRec(
path,
buf, // Preallocate enough memory for new path 为新路径预先分配足够的内存
[4]byte{}, // Empty rune buffer
fixTrailingSlash,
)
return ciPath, ciPath != nil
}
// Shift bytes in array by n bytes left 将数组中的字节向左移动n个字节
func shiftNRuneBytes(rb [4]byte, n int) [4]byte {
switch n {
case 0:
return rb
case 1:
return [4]byte{rb[1], rb[2], rb[3], 0}
case 2:
return [4]byte{rb[2], rb[3]}
case 3:
return [4]byte{rb[3]}
default:
return [4]byte{}
}
}
// Recursive case-insensitive lookup function used by n.findCaseInsensitivePath
// n.findCaseInsensitivePath使用的不区分大小写的递归查找函数
func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) []byte {
npLen := len(n.path)
walk: // Outer loop for walking the tree 用于走树的外环
for len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) {
// Add common prefix to result 将公共前缀添加到结果
oldPath := path
path = path[npLen:]
ciPath = append(ciPath, n.path...)
if len(path) == 0 {
// We should have reached the node containing the handle. 我们应该已经到达包含句柄的节点。
// Check if this node has a handle registered. 检查此节点是否已注册句柄。
if n.handlers != nil {
return ciPath
}
// No handle found.
// Try to fix the path by adding a trailing slash 尝试通过添加尾部斜线来修复路径
if fixTrailingSlash {
for i, c := range []byte(n.indices) {
if c == '/' {
n = n.children[i]
if (len(n.path) == 1 && n.handlers != nil) ||
(n.nType == catchAll && n.children[0].handlers != nil) {
return append(ciPath, '/')
}
return nil
}
}
}
return nil
}
// If this node does not have a wildcard (param or catchAll) child,
// we can just look up the next child node and continue to walk down
// the tree
// 如果这个节点没有通配符(param或catchAll)子节点,我们可以查找下一个子节点,然后继续沿着树往下走
if !n.wildChild {
// Skip rune bytes already processed 跳过已处理的符文字节
rb = shiftNRuneBytes(rb, npLen)
if rb[0] != 0 {
// Old rune not finished 旧符文未完成
idxc := rb[0]
for i, c := range []byte(n.indices) {
if c == idxc {
// continue with child node 继续使用子节点
n = n.children[i]
npLen = len(n.path)
continue walk
}
}
} else {
// Process a new rune 处理新符文
var rv rune
// Find rune start. 查找符文开始。
// Runes are up to 4 byte long,
// -4 would definitely be another rune.
// 符文长达4字节,-4肯定是另一个符文。
var off int
for max := min(npLen, 3); off < max; off++ {
if i := npLen - off; utf8.RuneStart(oldPath[i]) {
// read rune from cached path
rv, _ = utf8.DecodeRuneInString(oldPath[i:])
break
}
}
// Calculate lowercase bytes of current rune
// 计算当前符文的小写字节
lo := unicode.ToLower(rv)
utf8.EncodeRune(rb[:], lo)
// Skip already processed bytes 跳过已处理的字节
rb = shiftNRuneBytes(rb, off)
idxc := rb[0]
for i, c := range []byte(n.indices) {
// Lowercase matches
if c == idxc {
// must use a recursive approach since both the
// uppercase byte and the lowercase byte might exist
// as an index
// 必须使用递归方法,因为大写字节和小写字节都可能作为索引存在
if out := n.children[i].findCaseInsensitivePathRec(
path, ciPath, rb, fixTrailingSlash,
); out != nil {
return out
}
break
}
}
// If we found no match, the same for the uppercase rune,
// if it differs
// 如果我们没有找到匹配项,大写符文也是如此,如果不同
if up := unicode.ToUpper(rv); up != lo {
utf8.EncodeRune(rb[:], up)
rb = shiftNRuneBytes(rb, off)
idxc := rb[0]
for i, c := range []byte(n.indices) {
// Uppercase matches 大写匹配
if c == idxc {
// Continue with child node 继续使用子节点
n = n.children[i]
npLen = len(n.path)
continue walk
}
}
}
}
// Nothing found. We can recommend to redirect to the same URL
// without a trailing slash if a leaf exists for that path
// 未找到任何内容。如果该路径存在叶,我们可以建议重定向到相同的URL,而不使用尾部斜杠
if fixTrailingSlash && path == "/" && n.handlers != nil {
return ciPath
}
return nil
}
n = n.children[0]
switch n.nType {
case param:
// Find param end (either '/' or path end) 查找参数结尾(“/”或路径结尾)
end := 0
for end < len(path) && path[end] != '/' {
end++
}
// Add param value to case insensitive path 将参数值添加到不区分大小写的路径
ciPath = append(ciPath, path[:end]...)
// We need to go deeper! 我们需要更深入!
if end < len(path) {
if len(n.children) > 0 {
// Continue with child node 继续使用子节点
n = n.children[0]
npLen = len(n.path)
path = path[end:]
continue
}
// ... but we can't
if fixTrailingSlash && len(path) == end+1 {
return ciPath
}
return nil
}
if n.handlers != nil {
return ciPath
}
if fixTrailingSlash && len(n.children) == 1 {
// No handle found. Check if a handle for this path + a
// trailing slash exists
// 找不到句柄。检查是否存在此路径的句柄+尾部斜线
n = n.children[0]
if n.path == "/" && n.handlers != nil {
return append(ciPath, '/')
}
}
return nil
case catchAll:
return append(ciPath, path...)
default:
panic("invalid node type")
}
}
// Nothing found.
// Try to fix the path by adding / removing a trailing slash
// 尝试通过添加/删除尾部斜线来修复路径
if fixTrailingSlash {
if path == "/" {
return ciPath
}
if len(path)+1 == npLen && n.path[len(path)] == '/' &&
strings.EqualFold(path[1:], n.path[1:len(path)]) && n.handlers != nil {
return append(ciPath, n.path...)
}
}
return nil
}
【Gin-v1.9.0源码阅读】tree.go
原创
©著作权归作者所有:来自51CTO博客作者深漂小码哥的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Apache Doris 聚合函数源码阅读与解析|源码解读系列
Apache Doris Active Contributor 隐形通过本文记录下对源码的理解,以方便新人快速上手源码开发。
Apache Doris 数据库 大数据 数据分析 数据仓库 -
【Gin-v1.9.0源码阅读】gin.go
【代码】【Gin-v1.9.0源码阅读】gin.go。
golang 开发语言 后端 gin JSON -
【Gin-v1.9.0源码阅读】recovery.go
【代码】【Gin-v1.9.0源码阅读】recovery.go。
gin golang 中间件 死机 堆栈 -
【Gin-v1.9.0源码阅读】context.go
【代码】【Gin-v1.9.0源码阅读】context.go。
golang 开发语言 gin 后端 JSON -
【Gin-v1.9.0源码阅读】utils.go
【代码】【Gin-v1.9.0源码阅读】utils.go。
gin golang 开发语言 xml ico -
【Gin-v1.9.0源码阅读】debug.go
【Gin-v1.9.0源码阅读】debug.go
gin golang Powered by 金山文档 版本号 线程安全 -
【Gin-v1.9.0源码阅读】any.go
【Gin-v1.9.0源码阅读】any.go
gin golang 开发语言 Powered by 金山文档 Core -
【Gin-v1.9.0源码阅读】routergroup.go
【代码】【Gin-v1.9.0源码阅读】routergroup.go。
gin golang 智能路由器 处理程序 sed -
【Gin-v1.9.0源码阅读】path.go
【代码】【Gin-v1.9.0源码阅读】path.go。
gin golang 字符串 堆栈 函数调用 -
【Gin-v1.9.0源码阅读】doc.go
【Gin-v1.9.0源码阅读】doc.go
gin golang Powered by 金山文档 github HTTP -
【Gin-v1.9.0源码阅读】mode.go
【Gin-v1.9.0源码阅读】mode.go
gin golang Powered by 金山文档 JSON github -
【Gin-v1.9.0源码阅读】version.go
【Gin-v1.9.0源码阅读】version.go
golang Powered by 金山文档 Core -
【Gin-v1.9.0源码阅读】logger.go
【代码】【Gin-v1.9.0源码阅读】logger.go。
gin golang 开发语言 中间件 HTTP -
【Gin-v1.9.0源码阅读】fs.go
【代码】【Gin-v1.9.0源码阅读】fs.go。
gin golang sed 工作原理 文件系统 -
【Gin-v1.9.0源码阅读】errors.go
【代码】【Gin-v1.9.0源码阅读】errors.go。
gin golang 开发语言 后端 json -
【Gin-v1.9.0源码阅读】deprecated.go
【Gin-v1.9.0源码阅读】deprecated.go
gin golang Powered by 金山文档 HTTP github -
【Gin-v1.9.0源码阅读】auth.go
【Gin-v1.9.0源码阅读】auth.go
gin golang Powered by 金山文档 HTTP 字符串 -
【Gin-v1.9.0源码阅读】binding/toml.go
【代码】【Gin-v1.9.0源码阅读】binding/toml.go。
gin golang Core github