英文:
Go http Request detecting POST as GET
问题
我对Go语言非常陌生,实际上今天才开始学习。但是我遇到了一个奇怪且令人沮丧的问题。简单来说,当我通过POSTMAN发送POST请求时,以下代码将r.Method
打印为GET。
package main
import (
"fmt"
"net/http"
"routes"
)
func cartHandler(w http.ResponseWriter, r *http.Request) {
fmt.Printf(r.Method)
if r.Method == "GET" {
cart.GetHandler(w,r)
} else if r.Method == "POST" {
cart.PostHandler(w,r)
}
//fmt.Fprintf(w, "Hi there, I love %s!", r.Method)
}
func main() {
http.HandleFunc("/cart/", cartHandler)
http.ListenAndServe(":8010", nil)
}
发送的请求是正确的,因为在Node.js中的类似代码中,它被检测为POST请求。
英文:
I am very new to Go, infact started today. But have run into a weird and frustrating problem. Simply put, the following code prints r.Method
as GET when I make a POST request via POSTMAN.
package main
import (
"fmt"
"net/http"
"routes"
)
func cartHandler(w http.ResponseWriter, r *http.Request) {
fmt.Printf(r.Method);
if r.Method == "GET" {
cart.GetHandler(w,r)
} else if r.Method == "POST" {
cart.PostHandler(w,r)
}
//fmt.Fprintf(w, "Hi there, I love %s!", r.Method)
}
func main() {
http.HandleFunc("/cart/", cartHandler)
http.ListenAndServe(":8010", nil)
}
The request being made is fine because a similar piece of code in nodejs detects it as a POST request.
答案1
得分: 4
在你的HandleFunc中移除最后的斜杠
http.HandleFunc("/cart", cartHandler)
而不是
http.HandleFunc("/cart/", cartHandler)
或者如果你想要你的URL这样,可以在POSTMAN中带上斜杠,它应该按预期工作。
英文:
In your HandleFunc remove the last trailing slash
http.HandleFunc("/cart", cartHandler)
instead of
http.HandleFunc("/cart/", cartHandler)
Or if you want your URL like that, enter it with the slash in POSTMAN and it should work like expected.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论