json - 如何在 Go 中将状态码返回给处理程序
问题描述
我有一个简单的休息 API,我需要将状态代码从 getAPI 函数传输到处理程序。我想这个问题是 NewDecoder 只处理响应体。但是我怎样才能解决这个问题,不仅传输正文,而且传输状态码
在这里我要选择,如果我有状态码 404 它将是一个响应,如果我有状态码 200 它将是另一个响应
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}
}
}
在这里我发送请求,在这里我需要将 res.StatusCode 传输到处理程序
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)
}
}
解决方案
您可能想在 ResponseWriter 上使用 WriteHeader
// 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)
推荐阅读
- javascript - 如何在 JavaScript 中将下载的画布图像的背景颜色设为白色?
- pine-script - 在 strategy.exit 之后等待
- bash - While 循环中的模数结果为假,但如果在循环外计算则不是
- java - JSON 对象在数组中意外重复
- javascript - 如何在不刷新整个页面的情况下更改 URL
- go - 如何在 Go Playground 中定义不同的文件或包?
- database - 将数据库数据共享给其他团队的好方法是什么?- Rest API 或 Database Direct Access
- html - HTML 与 CSS 背景图像
- excel - 如何在根据同一标题列中的单元格值排序的单元格中输入条件标题列表?
- javascript - 如何在 JavaScript 练习中计算形状的总周长并编写正确的函数