Search code examples
jsongogo-http

JSON body for POST request


I am building a body for a POST request

relativeurl := "this-is-a-test-url"

postBody := fmt.Sprintf("{\"requests\": [{\"httpMethod\": \"GET\",\"relativeUrl\": \"%s\"}]}", relativeurl)

When I do a fmt.Println of postBody, I see:

{
"requests": [
    {
        "httpMethod": "GET",
        "relativeUrl": "this-is-a-test-url"}]}

but the url is expecting a JSON:

{
    "requests": [
        {
            "httpMethod": "GET",
            "relativeUrl": "this-is-a-test-url"
        }
]
}

Is the way I build the post body wrong?


Solution

  • Just to mention another way to correctly escape a JSON string :

    // call the json serializer just on the string value :
    escaped, _ := json.Marshal(relativeUrl)
    // the 'escaped' value already contains its enclosing '"', no need to repeat them here :
    body := fmt.Sprintf("{\"requests\": [{\"httpMethod\": \"GET\",\"relativeUrl\": %s}]}", escaped)
    

    https://play.golang.org/p/WaT-RCnDQuK