gpt4 book ai didi

go - 如何在 http.ResponseWriter 上设置 HTTP 状态码

转载 作者:IT老高 更新时间:2023-10-28 12:57:53 25 4
gpt4 key购买 nike

如何在 http.ResponseWriter 上设置 HTTP 状态码(例如设置为 500 或 403)?

我可以看到请求通常附加一个状态码 200。

最佳答案

使用 http.ResponseWriter.WriteHeader .来自文档:

WriteHeader sends an HTTP response header with 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.

例子:

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Something bad happened!"))
}

关于go - 如何在 http.ResponseWriter 上设置 HTTP 状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40096750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com