Error code for a response is 400 but i get 200 as status

(Mrk) #1

hello i am a newbie to golang,

when i hit an api i get response with the following code. but i am not getting the header values and status code in postman . how can i get all the values . i.e headers and status code .
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
bodynew, _ := ioutil.ReadAll(resp.Body)
fmt.Fprintf(w, “%s”, bodynewPreformatted text)


(Anik Hasibul) #2
fmt.Println(r.StatusCode, r.StatusCode, r.Header.Get())

I hope you got the idea!

(Mrk) #3

hello AnikHasibul ,
is r.StatusCode, r.StatusCode required 2 times ?

(Anik Hasibul) #4

Nope. I made it mistakenly :frowning:

r.StatusCode returns only status code i.e 200, 404, 403

(Jos) #5

Perhaps you can improve your code a bit by also checking for the possible error that http.DefaultClient.Do() returns.

For example:

resp, err := http.DefaultClient.Do(req)
if err != nil {
	log.Fatalf("Failed to get API resource: %s", err)
} else if resp.StatusCode >= 400 {
	log.Fatalf("API errored. Code: %d", resp.StatusCode)
defer resp.Body.Close()

Then you better know what caused the error: failure to get an API response or succeeding to contact the online resource, but getting an error code in returns.

Hope this helps.

(system) #6

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.