E
E
Eugene2020-01-30 20:23:48
go
Eugene, 2020-01-30 20:23:48

How to describe the structure of the input data?

When sending a request, json with data or an error may be returned in response. How to describe the resp.Body structure in this case?

resp, err := http.Get(requestURL)
if err != nil {
      // ...
}

defer resp.Body.Close()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladislav, 2020-01-30
@you_are_enot

resp.Body contains only bytes and nothing else.
You can, depending on the status of the resp.Status server response, choose how you process the data.
For example, in my projects it is done like this:
When the request status is 200, I decode it as usual.
If the status is different, I expect it to contain another structure containing the description of the error, and I try to decode it into this structure and return it as an error.
But if error decoding fails, then I simply return an error containing the Body text.

A
Alexey〒., 2020-01-30
@axifive

The Content-Type key in the header describes what the data in the body is. For json: application/json
type := resp.Header.Get("Content-Type")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question