将自定义中间件类型传递给 alice.New() 函数时构建失败

Build fails when passing custom middleware type to alice.New() function

这是我在尝试构建应用程序时遇到的错误。

我使用 Gorilla mux 作为路由器,使用 Alice 链接中间件。

我定义了一个名为 'Middleware' 的自定义类型,具有以下签名;

type Middleware func(http.Handler) http.Handler

下面是我使用 Alice 链接中间件和处理程序的代码。

if len(config.Middlewares()) > 0 {
   subRouter.Handle(config.Path(), alice.New(config.Middlewares()...).Then(config.Handler())).Methods(config.Methods()...).Schemes(config.Schemes()...)
}

但是当我尝试构建时,我在控制台中收到以下错误;

infrastructure/router.go:88:63: cannot use config.Middlewares() (type []Middleware) as type []alice.Constructor in argument to alice.New

我检查了 alice.Constructor 的代码。它还具有与我的中间件类型相同的签名。

我用的是Go 1.13,以及Alice以下版本

github.com/justinas/alice v1.2.0

你能帮我解决这个问题吗?

alice.Constructor 具有相同的签名,但它被定义为另一种类型。所以你不能只使用它。

观看这个 https://www.youtube.com/watch?v=Vg603e9C-Vg 有很好的解释。

你能做的就是使用type aliases 像这样:

var Middleware = alice.Constructor

看起来像这样:

之前:


func timeoutHandler(h http.Handler) http.Handler {
    return http.TimeoutHandler(h, 1*time.Second, "timed out")
}

func myApp(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello world!"))
}

type Middleware func(http.Handler) http.Handler

func main() {
    middlewares := []Middleware{timeoutHandler}

    http.Handle("/", alice.New(middlewares...).ThenFunc(myApp))
}

之后:

func timeoutHandler(h http.Handler) http.Handler {
    return http.TimeoutHandler(h, 1*time.Second, "timed out")
}

func myApp(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello world!"))
}

type Middleware = alice.Constructor

func main() {
    middlewares := []Middleware{timeoutHandler}

    http.Handle("/", alice.New(middlewares...).ThenFunc(myApp))
}