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

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

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

问题

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

  1. func snippetCreate(w http.ResponseWriter, r *http.Request) {
  2. // 在这个if语句下的任何代码都不会执行,我甚至尝试写日志和fmt打印
  3. // 使用除POST以外的不同请求进行测试
  4. if r.Method != "POST" {
  5. w.Header().Set("Allow", "POST")
  6. http.Error(w, "Method Not Allowed", 405)
  7. return
  8. }
  9. // 这里的代码会执行
  10. w.Header().Set("Allow", "POST")
  11. w.Write([]byte("create a snippet"))
  12. }
  13. func main() {
  14. r := chi.NewRouter()
  15. r.Use(middleware.Logger)
  16. r.Get("/", home)
  17. r.Get("/snippet/view", snippetView)
  18. r.Post("/snippet/create", snippetCreate)
  19. log.Print("Starting server on port :8080")
  20. err := http.ListenAndServe(":8080", r)
  21. if err != nil {
  22. log.Fatal(err)
  23. }
  24. }
英文:

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

  1. func snippetCreate(w http.ResponseWriter, r *http.Request) {
  2. // anything under this if statement doesnt work, I tried even write logs and fmt prints
  3. // tested with different requests other than POST
  4. if r.Method != "POST" {
  5. w.Header().Set("Allow", "POST")
  6. http.Error(w, "Method Not Allowed", 405)
  7. return
  8. }
  9. // it works
  10. w.Header().Set("Allow", "POST")
  11. w.Write([]byte("create a snippet"))
  12. }
  13. func main() {
  14. r := chi.NewRouter()
  15. r.Use(middleware.Logger)
  16. r.Get("/", home)
  17. r.Get("/snippet/view", snippetView)
  18. r.Post("/snippet/create", snippetCreate)
  19. log.Print("Starting server on port :8080")
  20. err := http.ListenAndServe(":8080", r)
  21. if err != nil {
  22. log.Fatal(err)
  23. }
  24. }

答案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:

确定