登录
首页 >  Golang >  Go问答

在Go中如何将HTTP状态码传递给处理程序

来源:stackoverflow

时间:2024-02-25 13:12:20 360浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《在Go中如何将HTTP状态码传递给处理程序》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

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

正确答案


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

今天关于《在Go中如何将HTTP状态码传递给处理程序》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>