在使用Go语言中的chi中间件时无法运行控制器。

huangapple go评论89阅读模式
英文:

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

huangapple
  • 本文由 发表于 2022年8月14日 00:44:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/73346070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定