检测到的HTTP请求将POST识别为GET。

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

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.

huangapple
  • 本文由 发表于 2016年1月29日 20:46:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/35084919.html
匿名

发表评论

匿名网友

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

确定