0

I am trying to make an API call to Twilio with Go's HTTP package and it appears the right data is not getting to Twilio.

Request:

func startVerification() (string, error) {
    url := fmt.Sprintf("https://verify.twilio.com/v2/Services/%s/Verifications", internal.Config.TwilioServiceSID)
    xx := "Locale=es&To=+1234567890&Channel=sms"
    payload := strings.NewReader(xx)

    log.Println(fmt.Sprintf("Payload = %v", xx))
    client := &http.Client{}
    req, err := http.NewRequest("POST", url, payload)

    if err != nil {
        return "", fmt.Errorf("error occured while creating request %v", err)
    }
    req.SetBasicAuth(internal.Config.TwilioSD, internal.Config.TwilioAuthToken)
    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

    res, err := client.Do(req)
    if err != nil {
        return "", fmt.Errorf("error occured while doing %v", err)
    }
    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        return "", fmt.Errorf("error occured while reading %v", err)
    }
    return string(body), nil
}

But Twilio is complaining is that:

{ "code": 60200, "message": "Invalid parameter To: 1234567890", "more_info": "https://www.twilio.com/docs/errors/60200", "status": 400 }

However, if I send the request from Postman, it works.

I am suspecting the "+" before the number is being stripped out but I am not sure as I am pretty new to Go and don't understand its nuances.

Please, note that +1234567890 is just a dummy number I am using for this question.

X09
  • 3,827
  • 10
  • 47
  • 92
  • 1
    The `+` is being converted to a space, because that's how URL encoding works. Either use `net/url` to handle your URL, or encode it properly yourself in the string. – Adrian Oct 26 '20 at 21:17
  • @Adrian, how do I handle the URL or encode it properly? Please, can you point me to a post or something? Thanks. – X09 Oct 26 '20 at 21:19
  • @Adrian why not submit your comment as an answer? – maerics Oct 26 '20 at 21:23

1 Answers1

3

You probably want to use url.Values for this:

params := url.Values{}
params.Add("Locale", "es")
params.Add("To", "+1234567890")
params.Add("Channel", "sms")
payload := strings.NewReader(params.Encode())

https://play.golang.org/p/qAF3qlLIYPP

dave
  • 62,300
  • 5
  • 72
  • 93
  • 1
    @X09 see https://en.wikipedia.org/wiki/Percent-encoding, aka "URL Encoding", which is used by the MIME type `application/x-www-form-urlencoded`. – maerics Oct 26 '20 at 21:31