Search code examples
restgoget

HTTP GET fails when adding array in param, but will success using postman


I have a URL that contains an array. When I print the URL, I get:

https://myurl.com?args=["2019-11-06T19:20:00Z", "2019-11-06T22:30:00Z"]

When I make a GET with postman, I can get a successful status code: Success 200

But when I do it with Go, I receive a status code: 502 Bad request

client := http.Client{}
    token := GetJWTToken()
    bearer := "Bearer " + token

    url := "https://myurl.com?args=[" + start.Format(time.RFC3339) + ", " + end.Format(time.RFC3339) + "]"

    req, err := http.NewRequest("GET", url, nil)
    if req != nil {
        req.Header.Add("Authorization", bearer)
        req.Header.Set("Content-Type", "application/json")
    }
    resp, err := client.Do(req)
    bodyBytes, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }
    bodyString := string(bodyBytes)
    log.Info(bodyString) // Prints 502 Bad Gateway

I printed the 2 URLs, and they are exactly the same.

I tried to remove the "array" in the url, and it fails, obviously, because API is expecting this param, but it can reach the API.

So, I know where is the issue, but don't know how to fix it, I don't own the API, so I can't change it.

It seems postman is doing something under the hood, or what should be the difference between my code and postman request?


Solution

  • It's probably best not to build your URL manually. Use the proper tools:

    addr, _ := url.Parse("https://myurl.com")
    query := url.Values{}
    query.Add("args", "[" + start.Format(time.RFC3339) + ", " + end.Format(time.RFC3339) + "]")
    addr.RawQuery = query.Encode()
    
    req, err := http.NewRequest("GET", addr.String(), nil)