POST with Go fails but works with curl

1.2k views Asked by At

I've tested the following curl command against my app, and it returns successfully:

curl --data "username=john&password=acwr6414" http://127.0.0.1:5000/api/login

However trying to replicate the above in go has proven quite a challenge, I keep getting a 400 Bad Request error from the server, here's the code:

    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)

I'm using the goreq package, I've tried at least 3 or 4 other packages with no difference. The error I get is:

<!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>
1

There are 1 answers

0
JimB On BEST ANSWER

You're sending a json body with your Go code, but an application/x-www-form-urlencoded body with curl.

You can encode the string manually as you've done with curl:

Body:      "password=acwr6414&user=john",

Or you can use a url.Values to properly encode the body:

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()