Search code examples
httpgogetcontent-type

How to perform a GET request with application/x-www-form-urlencoded content-type in Go?


Basically, I need to implement the following method in Go - https://api.slack.com/methods/users.lookupByEmail.

I tried doing it like this:

import (
    "bytes"
    "encoding/json"
    "errors"
    "io/ioutil"
    "net/http"
)

type Payload struct {
    Email string `json:"email,omitempty"` 
}

// assume the following code is inside some function

client := &http.Client{}
payload := Payload{
    Email: "[email protected]",
}

body, err := json.Marshal(payload)
if err != nil {
    return "", err
}

req, err := http.NewRequest("GET", "https://slack.com/api/users.lookupByEmail", bytes.NewReader(body))
if err != nil {
    return "", err
}

req.Header.Add("Authorization", "Bearer "+token)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

resp, err := client.Do(req)
if err != nil {
    return "", err
}

defer resp.Body.Close()
if resp.StatusCode != 200 {
    t, _ := ioutil.ReadAll(resp.Body)
    return "", errors.New(string(t))
}

responseData, err := ioutil.ReadAll(resp.Body)
if err != nil {
    return "", err
}

return string(responseData), nil

But I get an error that "email" field is missing, which is obvious because this content-type does not support JSON payload: {"ok":false,"error":"invalid_arguments","response_metadata":{"messages":["[ERROR] missing required field: email"]}} (type: string)

I couldn't find how to include a post form with the GET request - there is no available post form argument neither to http.NewRequest, nor to http.Client.Get; http.Client.PostForm issues a POST request but GET is needed in this case. Also, I think I have to use http.NewRequest here (unless another approach exists) because I need to set the Authorization header.


Solution

  • You misunderstand the application/x-www-form-urlencoded header, you should pass an URL parameters here. Check out an example:

    import (
      ...
      "net/url"
      ...
    )
    
    data := url.Values{}
    data.Set("email", "[email protected]")
    data.Set("token", "SOME_TOKEN_GOES_HERE")
    
    
    r, _ := http.NewRequest("GET", "https://slack.com/api/users.lookupByEmail", strings.NewReader(data.Encode()))
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))