GolangNote

Golang笔记

Go-chi获取访问路径方法总结

Permalink

在Go语言的chi路由库中,获取访问路径的方式取决于你需要的是实际请求路径还是定义的路由模式:

1. 获取实际请求路径

使用标准库的r.URL.Path即可获取用户请求的实际路径:

Go:
1
2
3
r.Get("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
    path := r.URL.Path // 例如,访问"/users/123"得到"/users/123"
})

2. 获取路由模式(如/users/{id}

通过chi的RouteContext获取匹配的路由模式:

Go:
1
2
3
4
5
6
7
8
9
10
import "github.com/go-chi/chi/v5"

r.Get("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
    routeCtx := chi.RouteContext(r.Context())
    if routeCtx == nil {
        // 处理无上下文的情况
        return
    }
    routePattern := routeCtx.RoutePattern() // 返回"/users/{id}"
})

在中间件中获取路由模式

确保中间件在路由匹配之后执行,例如将中间件添加到具体路由或组:

Go:
1
2
3
4
5
6
7
8
9
r := chi.NewRouter()

r.With(func(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        next.ServeHTTP(w, r) // 先执行路由匹配
        routeCtx := chi.RouteContext(r.Context())
        pattern := routeCtx.RoutePattern() // 获取匹配后的路由模式
    })
}).Get("/users/{id}", handler)

注意事项

  • 中间件顺序:若在全局中间件中获取,可能因路由尚未匹配而得到空值。建议在具体路由的中间件或处理函数中获取。
  • 路由分组:若使用路由分组,RoutePattern()会返回完整路径(如/group/users/{id})。

示例代码

Go:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

import (
    "fmt"
    "net/http"

    "github.com/go-chi/chi/v5"
)

func main() {
    r := chi.NewRouter()

    r.Use(func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            next.ServeHTTP(w, r)
            routeCtx := chi.RouteContext(r.Context())
            if routeCtx != nil {
                fmt.Printf("路由模式: %s\n", routeCtx.RoutePattern())
            }
        })
    })

    r.Get("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("处理用户请求"))
    })

    http.ListenAndServe(":8080", r)
}

访问/users/123时,中间件会输出:

plaintext:
1
路由模式: /users/{id}

根据需求选择合适的方法获取路径信息。

本文网址: https://golangnote.com/topic/322.html 转摘请注明来源

Related articles

Go 编程格言谚语

这些 go 格言谚语大多出自 Rob Pike 振奋人心的演讲视频,有很大参考价值。...

Write a Comment to "Go-chi获取访问路径方法总结"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 19ms