Reputation: 1
I have a simple rest API and i need to transfer status code from getAPI function to handler. I suppose that problem is that NewDecoder handle only response body. But how can i solve this problem and transfer not only body, but status code
here i want to choose, if i have status code 404 it will be one response, if i have status 200 code it will be another
func handler(w http.ResponseWriter, r *http.Request) {
switch h.Data["action"].(string) {
case "catalogue":
url := "https:...."
resp.getAPI(url)
if resp.StatusCode == 404 {
h.Speech = append(h.Speech, "Call another code.")
} else {
h.Speech = []string{resp.Material.Url}
}
}
here i send request and here i need to transfer res.StatusCode to handler
func (resp *api) getAPI(url string) {
req, err := http.NewRequest(http.MethodGet, url, nil)
res, err := client.Do(req)
defer res.Body.Close()
err = json.NewDecoder(res.Body).Decode(&resp)
if err != nil {
log.Println("decode body", err)
}
}
Upvotes: 0
Views: 1324
Reputation: 2625
you probably want to use WriteHeader on ResponseWriter
// WriteHeader sends an HTTP response header with the provided
// status code.
//
// If WriteHeader is not called explicitly, the first call to Write
// will trigger an implicit WriteHeader(http.StatusOK).
// Thus explicit calls to WriteHeader are mainly used to
// send error codes.
//
// The provided code must be a valid HTTP 1xx-5xx status code.
// Only one header may be written. Go does not currently
// support sending user-defined 1xx informational headers,
// with the exception of 100-continue response header that the
// Server sends automatically when the Request.Body is read.
WriteHeader(statusCode int)
Upvotes: 3