为什么 r.Method != “POST” 的分支没有执行到?

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

Why the r.Method != "POST" branch does not reach?

问题

下面是snippetCreate函数中的if分支,当我发送除POST以外的请求时,它不会执行:

func snippetCreate(w http.ResponseWriter, r *http.Request) {
	// 在这个if语句下的任何代码都不会执行,我甚至尝试写日志和fmt打印
    // 使用除POST以外的不同请求进行测试
    if r.Method != "POST" {
		w.Header().Set("Allow", "POST")
		http.Error(w, "Method Not Allowed", 405)
		return
	}
	// 这里的代码会执行
	w.Header().Set("Allow", "POST")

	w.Write([]byte("create a snippet"))

}
    
func main() {

	r := chi.NewRouter()
	r.Use(middleware.Logger)
	r.Get("/", home)
	r.Get("/snippet/view", snippetView)
	r.Post("/snippet/create", snippetCreate)

	log.Print("Starting server on port :8080")
	err := http.ListenAndServe(":8080", r)
	if err != nil {
		log.Fatal(err)

    }
}
英文:

The if branch in the snippetCreate func below doesn't reach when I make requests other than POST:

func snippetCreate(w http.ResponseWriter, r *http.Request) {
	// anything under this if statement doesnt work, I tried even write logs and fmt prints
    // tested with different requests other than POST
    if r.Method != "POST" {
		w.Header().Set("Allow", "POST")
		http.Error(w, "Method Not Allowed", 405)
		return
	}
	// it works
	w.Header().Set("Allow", "POST")

	w.Write([]byte("create a snippet"))

}
    
func main() {

	r := chi.NewRouter()
	r.Use(middleware.Logger)
	r.Get("/", home)
	r.Get("/snippet/view", snippetView)
	r.Post("/snippet/create", snippetCreate)

	log.Print("Starting server on port :8080")
	err := http.ListenAndServe(":8080", r)
	if err != nil {
		log.Fatal(err)

    }
}

答案1

得分: 1

> r.Post("/snippet/create", snippetCreate)

注意这里的 Post。只有 POST 请求会被路由到 snippetCreate 处理程序。

所以在处理程序 snippetCreate 中,r.Method 的值将始终为 POST。请参阅 (*Mux).Post 的文档:

> Post 添加了一个匹配 POST HTTP 方法的 pattern 路由,以执行 handlerFn

英文:

> r.Post("/snippet/create", snippetCreate)

Note the Post here. Only POST requests will be routed to the handler snippetCreate.

So in the handler snippetCreate, r.Method will always be POST. See the doc for (*Mux).Post:

> Post adds the route pattern that matches a POST http method to execute the handlerFn.

huangapple
  • 本文由 发表于 2023年5月13日 16:01:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76241687.html
匿名

发表评论

匿名网友

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

确定