2

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)) } } 
1
  • 2
    In addition to the answers, you can avoid all of the "fragility" around quoting if you marshal your data into JSON from a struct. See here for a minimal example: play.golang.org/p/8lGwkQPYxb - you can modify your makeHttpPostReq function to accept a User instead of two strings. Commented Jun 15, 2015 at 3:31

2 Answers 2

7

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"} 
Sign up to request clarification or add additional context in comments.

Comments

2

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 + "\"}" 

1 Comment

In Go you can avoid all the confusing backslash quoting (\") by using ` (backtick) instead of " (double-quote) for the string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.