如何在中间件 go-chi 中获取 url 参数

How to get url param in middleware go-chi

我为特定的一组路由使用特定的中间件

r.Route("/platform", func(r chi.Router) {
    r.Use(authService.AuthMiddleware)
    r.Get("/{id}/latest", RequestPlatformVersion)
})

现在如何访问此 AuthMiddleware 中间件中的 id url 参数

func (s *Service) AuthMiddleware(h http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        fmt.Println(chi.URLParam(r, "id"))
        id := chi.URLParam(r, "id")
        
        if id > 100 {
          http.Error(w, errors.New("Error").Error(), http.StatusUnauthorized)
          return
        }
    }
    return http.HandlerFunc(fn)
}

然而,id 参数打印为空字符串,即使中间件正在 运行 并且正在调用特定路由

你把你的 chi.URLParam 放在路径参数 {id} 之前,你忘了把 .ServeHTTP(w, r) 放在中间件上。如果你不放那个东西,你的请求将不会进入 Route 内的路径。

这是工作示例:

package main

import (
    "fmt"
    "net/http"

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

func AuthMiddleware(h http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        fmt.Println(chi.URLParam(r, "id"))
        h.ServeHTTP(w, r)
    }
    return http.HandlerFunc(fn)
}

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

    r.Route("/platform/{id}", func(r chi.Router) {
        r.Use(AuthMiddleware)
        r.Get("/latest", func(rw http.ResponseWriter, r *http.Request) {
            fmt.Println("here ", chi.URLParam(r, "id")) // <- here
        })
    })

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

我将 {id} 移动到 platform/{id} 以便中间件获得 id 路径值,并在中间件内添加 h.ServeHTTP(w, r)

尝试访问 http://localhost:8080/platform/1/latest

输出将是:

1
here  1

更新

代码后运行验证不好,必须修正定义路径的方式,验证后移动.ServeHTTP

这是例子:

package main

import (
    "errors"
    "fmt"
    "net/http"
    "strconv"

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

func AuthMiddleware(h http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        fmt.Printf("Middleware First, id: %+v\n", chi.URLParam(r, "id"))
        id, _ := strconv.Atoi(chi.URLParam(r, "id"))

        if id > 100 {
            http.Error(w, errors.New("Error").Error(), http.StatusUnauthorized)
            return
        }
        h.ServeHTTP(w, r)
    }
    return http.HandlerFunc(fn)
}

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

    // This works too ()
    // r.Route("/platform/{id}", func(r chi.Router) {
    //  r.Use(AuthMiddleware)
    //  r.Get("/latest", func(rw http.ResponseWriter, r *http.Request) {
    //      fmt.Println("second: ", chi.URLParam(r, "id")) // <- here
    //  })
    // })

    // Other Solution (Wrapping Middleware)
    r.Route("/platform", func(r chi.Router) {
        r.Get("/{id}/latest", AuthMiddleware(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
            fmt.Println("second: ", chi.URLParam(r, "id")) // <- here
        })).ServeHTTP)
    })

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