首页 > 解决方案 > 如何在 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)
    }
}

标签: jsongorest

解决方案


您可能想在 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)

推荐阅读