Home > other >  Post Request with strings.NewReader Containing Escape Sequence
Post Request with strings.NewReader Containing Escape Sequence

Time:09-13

I'm trying to retrieve a response from a POST endpoint which accepts a payload.

For curl request:

curl --request POST \
  --url https://api.io/v1/oauth/token \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{
      "userToken": "[email protected]:MyUserProfileToken"
    }'

I can do this with:

func GetJWT() string {

    endpoint := "https://api.io/v1/oauth/token"

    payload := strings.NewReader(`{
      "userToken":"[email protected]:MyUserProfileToken"
}`)

    req, _ := http.NewRequest("POST", endpoint, payload)

    req.Header.Add("Accept", "application/json")
    req.Header.Add("Content-Type", "application/json")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    return string(body)
}

and

    payload := strings.NewReader("{\n  \"userToken\": \"[email protected]:MyUserProfileToken\"\n}")

However, when I try to pass string pointers for email and token, and declare the payload like

func GetJWT(userEmail, userToken *string) string {

    endpoint := "https://api.io/v1/oauth/token"

    payload := strings.NewReader("{\n  \"userToken\": \*userEmail\":\"\*userToken\n}")

    req, _ := http.NewRequest("POST", endpoint, payload)

    req.Header.Add("Accept", "application/json")
    req.Header.Add("Content-Type", "application/json")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    return string(body)
}

an error is returned for unknown escape (column 53 on payload declaration).

How can I escape string pointers so that I can concatenate userEmail, ":", and userToken

CodePudding user response:

I see a couple problems here.

First: I think the "unknown escape" error message is caused by \* since \* is not a legitimate escape character.

Second: Golang does not support string interpolation. So the userEmail and userToken variables are actually never used in your GetJWT function.

You can format variables into a string using Sprintf from the standard library fmt package. That would look like this:

fmt.Sprintf("{\n  \"userToken\" : \"%s:%s\" \n}", *userEmail, *userToken)
  • Related