构建时传递自定义中间件类型给 alice.New() 函数失败
时间:2024-03-13
浏览:194
作者:佚名
Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《构建时传递自定义中间件类型给 alice.New() 函数失败》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!
问题内容
这是关于我在尝试构建应用程序时遇到的错误。
我使用 gorilla mux 作为路由器,使用 alice 来链接中间件。
我定义了一个名为“中间件”的自定义类型,具有以下签名;
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))
}以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
站内热门
最新文章
12.01
12.01
热门专题
