英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论