登录
首页 >  Golang >  Go问答

使用Go (GoLang) Gorilla/Mux来设置HTTP响应状态码

来源:stackoverflow

时间:2024-02-10 18:45:21 226浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《使用Go (GoLang) Gorilla/Mux来设置HTTP响应状态码》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我在尝试在 go 中设置 gorilla mux 路由的响应代码时遇到困难。如果我有一条非常简单的路线设置为

// dummy test route
router.handlefunc("/test", func(w http.responsewriter, r *http.request) {
    w.header().set("access-control-allow-headers", "*")
    w.header().set("access-control-allow-origin", "*")
    w.header().set("access-control-allow-methods", "post, get")
    w.header().set("content-type", "application/json")
    fmt.fprintf(w, "{\"message\":\"ok\"}")
}).methods("post")

它似乎工作正常并返回 200 的状态,这很好,但如果我尝试像下面这样手动设置响应代码。

// dummy test route
router.handlefunc("/test", func(w http.responsewriter, r *http.request) {
    w.writeheader(http.statusok) // added this to test
    w.header().set("access-control-allow-headers", "*")
    w.header().set("access-control-allow-origin", "*")
    w.header().set("access-control-allow-methods", "post, get")
    w.header().set("content-type", "application/json")
    fmt.fprintf(w, "{\"message\":\"ok\"}")
}).methods("post")

然后它似乎已将响应代码设置为 200,但在发出 rest 请求时仍然出现错误

POST *url*/test net::ERR_FAILED 200

我不确定为什么会这样,但这不是设置响应代码的正确方法吗?


正确答案


您必须在 writeheader 函数写入响应并刷新它时最后编写状态代码。

// dummy test route
router.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Headers", "*")
        w.Header().Set("Access-Control-Allow-Origin", "*")
        w.Header().Set("Access-Control-Allow-Methods", "POST, GET")
        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusOK) // Set your code here, after setting your headers
        fmt.Fprintf(w, "{\"message\":\"OK\"}")
}).Methods("POST")

本篇关于《使用Go (GoLang) Gorilla/Mux来设置HTTP响应状态码》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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