使用Go的POST失败但是使用curl

Jon*_*han 0 curl go gorequest

我已经针对我的应用测试了以下curl命令,并且它成功返回:

curl --data "username=john&password=acwr6414" http://127.0.0.1:5000/api/login
Run Code Online (Sandbox Code Playgroud)

然而,尝试在go中复制上述内容已经证明是一个相当大的挑战,我不断从服务器获得400 Bad Request错误,这里是代码:

    type Creds struct {
        Username string `json:"username"`
        Password string `json:"password"`
    }

user := "john"
pass := "acwr6414"

    creds := Creds{Username: user, Password: pass}
    res, err := goreq.Request{
        Method:    "POST",
        Uri:       "http://127.0.0.1:5000/api/login",
        Body:      creds,
        ShowDebug: true,
    }.Do()
    fmt.Println(res.Body.ToString())
    fmt.Println(res, err)
Run Code Online (Sandbox Code Playgroud)

我正在使用goreq包,我已经尝试了至少3或4个其他包没有区别.我得到的错误是:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>
Run Code Online (Sandbox Code Playgroud)

Jim*_*imB 6

你发送了一个带有Go代码的json主体,但是有一个application/x-www-form-urlencoded卷曲的主体.

您可以像使用curl一样手动编码字符串:

Body:      "password=acwr6414&user=john",
Run Code Online (Sandbox Code Playgroud)

或者您可以使用a url.Values来正确编码正文:

creds := url.Values{}
creds.Set("user", "john")
creds.Set("password", "acwr6414")

res, err := goreq.Request{
    ContentType: "application/x-www-form-urlencoded",
    Method:      "POST",
    Uri:         "http://127.0.0.1:5000/api/login",
    Body:        creds.Encode(),
    ShowDebug:   true,
}.Do()
Run Code Online (Sandbox Code Playgroud)