首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用带有Go-chi参数的中间件包装处理程序。

用带有Go-chi参数的中间件包装处理程序。
EN

Stack Overflow用户
提问于 2021-01-11 22:28:33
回答 1查看 2.3K关注 0票数 0

我一直在尝试用go-chi实现教程,特别是关于包装/将参数传递给包装器的部分。

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

代码语言:javascript
复制
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) does not implement http.Handler (missing ServeHTTP method)

如果我尝试输入assert来执行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

我似乎找不到一种方法来使它工作,也找不到能够用中间件包装单一路由的方法。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-12 04:20:30

有一个函数http.HandleFunc,然后有一个类型的http.HandlerFunc。你用的是前者,但你需要后者。

代码语言:javascript
复制
r.Get("/user", MustParams(http.HandlerFunc(sayHello), "key", "auth"))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65675434

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档