这是关于我在尝试构建应用程序时遇到的错误。
[我使用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))
}