使用 Go-chi 中间件包装处理程序的方法

作者:佚名

时间:2024-03-21

来源:stackoverflow

浏览:472

我一直在尝试使用go-chi来实现本教程,尤其是有关包装/将参数传递给包装器的部分。我的目标是能够使用带有该路由的自定义参数的中间件来包装一些特定的路由,而不是使用对我的所有路由而言“全局”的中间件,但我在执行此操作时遇到了问题。packagemainimport("context""io""net/http""github.com/go-chi/chi""github.com/go-chi/chi/middleware")func

从现在开始,努力学习吧!本文《使用 Go-chi 中间件包装处理程序的方法》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

我一直在尝试使用 go-chi 来实现本教程,尤其是有关包装/将参数传递给包装器的部分。

我的目标是能够使用带有该路由的自定义参数的中间件来包装一些特定的路由,而不是使用对我的所有路由而言“全局”的中间件,但我在执行此操作时遇到了问题。

package main

import (
    "context"
    "io"
    "net/http"

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

func main() {

    r := chi.NewRouter()
    r.Use(middleware.Logger)

    r.Get("/user", MustParams(sayHello, "key", "auth"))

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


func sayHello(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("hi"))
}

func MustParams(h http.Handler, params ...string) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        q := r.URL.Query()
        for _, param := range params {
            if len(q.Get(param)) == 0 {
                http.Error(w, "missing "+param, http.StatusBadRequest)
                return // exit early
            }
        }
        h.ServeHTTP(w, r) // all params present, proceed
    })
}

我得到 cannot use sayhello (type func(http.responsewriter, *http.request)) as type http.handler in argument to mustparams: func(http.responsewriter, *http.request) 不实现 http。处理程序(缺少 servehttp 方法)

如果我尝试输入断言,执行 r.get("/user", mustparams(http.handlefunc(sayhello), "key", "auth"))

我收到错误 cannot use mustparams(http.handlefunc(sayhello), "key", "auth") (type http.handler) as type http.handlerfunc in argument to r.get: need type assertion

我似乎找不到一种方法让它工作或能够用中间件包装单个路由。


解决方案


有一个函数 http.HandleFunc,然后有一个类型 http.HandlerFunc。您正在使用前者,但需要后者。

r.Get("/user", MustParams(http.HandlerFunc(sayHello), "key", "auth"))

今天关于《使用 Go-chi 中间件包装处理程序的方法》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
返回顶部