英文:
Unable to run controller while using chi middleware in golang
问题
我正在使用golang的net/http
和chi编写一个中间件函数,但是控制器函数没有被执行(在函数中无法打印1)。
调用中间件:
r.With(myMiddleware.Authware).Post("/tryon", mainController.Tryon)
myMiddleware包:
func Authware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 中间件代码
})
}
mainController包:
func Tryon(w http.ResponseWriter, r *http.Request) {
// 不打印任何内容
log.Println(1)
}
我阅读了文档,但没有得到太多帮助。
你能帮忙调试并告诉我为什么会发生这种情况吗?另外,如果我想从中间件向控制器返回一些数据,应该如何做到?
英文:
I am writing a middleware function in golang net/http
using chi but the controller function isn't being executed (couldn't print 1 in the function).
Calling the middleware:
r.With(myMiddleware.Authware).Post("/tryon", mainController.Tryon)
package - myMiddleware
func Authware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Middleware code
})
}
package - mainController
func Tryon(w http.ResponseWriter, r *http.Request) {
// Dosent print anything
log.Println(1)
}
I read the documentation but it didn't help much
Could you please help out debug and let me know why is this happening? Also, if I want to return some data from the middleware to the controller, how do I do it?
答案1
得分: 2
main.go
func main() {
r := chi.NewRouter()
r.With(middle.Authware).Post("/tryon", controller.Tryon)
http.ListenAndServe(":3000", r)
}
在通过中间件逻辑后调用controller
:
middleware.go
func Authware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 中间件代码
next.ServeHTTP(w, r)
})
}
controller.go
func Tryon(w http.ResponseWriter, r *http.Request) {
// 不打印任何内容
log.Println(1)
}
如果你真的希望它是一个POST
请求:curl -X POST localhost:3000/tryon
附注:请查看这里的代码示例:https://github.com/go-chi/chi
英文:
main.go
func main() {
r := chi.NewRouter()
r.With(middle.Authware).Post("/tryon", controller.Tryon)
http.ListenAndServe(":3000", r)
}
Invoke the controller
after passing the middleware
logic:
middleware.go
func Authware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Middleware code
next.ServeHTTP(w, r)
})
}
controller.go
func Tryon(w http.ResponseWriter, r *http.Request) {
// Doesn't print anything
log.Println(1)
}
If you really want it to be a POST
request: curl -X POST localhost:3000/tryon
P.S: go through the code example here: https://github.com/go-chi/chi
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论