Go (GoLang) Gorilla/Mux 设置响应代码

Go (GoLang) Gorilla/Mux Set Response Code

我在尝试为 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")

它似乎工作正常并且 returns 状态为 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")