Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set headers in JSON get request

Tags:

json

go

I'm getting JSON resonse from an external API with the following way:

func Request(url string, contentType string) []byte {
    resp, err := http.Get(url)
    resp.Header.Set("Content-Type", contentType)
    if err != nil {
        log.Fatal(err)
    }

    body, err := ioutil.ReadAll(resp.Body)
    resp.Body.Close()
    if err != nil {
        log.Fatal(err)
    }

    return body
}

url := fmt.Sprintf("https://example.com/api/category/%s", category)
contentType := "application/json"
body := Request(url, contentType)

res := &JSONRespStruct{}
err := json.Unmarshal([]byte(body), res)
if err != nil {
    log.Fatal(err)
}

The problem if I start to benchmark my site with go-wrk, the server crashes with the following error message:

2018/01/02 12:13:35 invalid character '<' looking for beginning of value

I think the code try to parse the JSON response as HTML. How I can force to get the response as a JSON?

like image 359
Lanti Avatar asked Jan 04 '23 00:01

Lanti


1 Answers

You probably want to set the header on the request. Setting the header on the response has no impact.

func Request(url string, contentType string) []byte {
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        log.Fatal(err)
    }
    req.Header.Set("Content-Type", contentType)
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }
    return body
}
like image 131
Bayta Darell Avatar answered Jan 05 '23 15:01

Bayta Darell