【问题标题】:How to return status code to handler in Go如何在 Go 中将状态码返回给处理程序
【发布时间】:2021-07-27 19:45:23
【问题描述】:

我有一个简单的 rest 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)
    }
}

【问题讨论】:

    标签: json go rest


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-19
      • 2018-12-21
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多