Reputation: 1703
When i make the POST request using the below GO Function. I get a invalid json
on the server side.
If i send static json for example
var jsonprep = []byte(`{"username":"[email protected]","password":"xyz123"}`)
it does work instead of
var jsonprep string = "`{username:"+username+",password:"+password+"}`"
.
func makeHttpPostReq(url string, username string, password string){
client := http.Client{}
var jsonprep string = "`{username:"+username+",password:"+password+"}`"
var jsonStr = []byte(jsonprep)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
fmt.Println("Unable to reach the server.")
} else {
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("body=", string(body))
}
}
Upvotes: 2
Views: 12703
Reputation: 7990
If you use
var jsonprep string = "`{username:"+username+",password:"+password+"}`"
the server will get the data like this:
`{username:your_username,password:yourpassword}`
because the string in back quotes `` which is in the double quotes is not raw string literals, of course it's invalid json. you can compose the json string manually:
var jsonprep string = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}"
Upvotes: 2
Reputation: 299265
You've got your quoting wrong:
http://play.golang.org/p/PueWyQ1atq
var jsonprep string = "`{username:"+username+",password:"+password+"}`"
===> `{username:Bob,password:pass}`
You meant:
http://play.golang.org/p/LMuwxArf8G
var jsonprep string = `{"username":"`+username+`","password":"`+password+`"}`
===> {"username":"Bob","password":"pass"}
Upvotes: 7