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

问题描述

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

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

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)

如果我尝试输入断言它做 r.Get("/user",MustParams(http.HandleFunc(sayHello),"auth"))

我收到错误 cannot use MustParams(http.HandleFunc(sayHello),"auth") (type http.Handler) as type http.HandlerFunc in argument to r.Get: need type assertion

我似乎找不到让它工作的方法,也找不到能够用中间件包装单个路由的方法

解决方法

有一个 function http.HandleFunc,然后有一个 type http.HandlerFunc。您正在使用前者,但您需要后者。

master