英文:
Changing HTTP code with http.ServeFile
问题
我正在使用Go编写一个服务器,目前正在实现错误页面(404、500等)。我有一些可以用于这些错误的文件,但是如果我使用http.ServeFile
,那么我得到的是HTTP代码200,而不是适当的代码。
有没有办法更改状态码,或者我需要为这种情况重写http.ServeFile
?
英文:
I'm writing a server in Go, and I'm currently implementing error pages (404, 500, etc.) I have files which can be served for these errors, but if I use http.ServeFile
then I get HTTP code 200 instead of the appropriate code.
Is there a way to change the status code, or do I need to rewrite http.ServeFile
for this use case?
答案1
得分: 3
从阅读源代码中,我没有看到任何改变状态码的方法(除非方法失败,这意味着您将无法获取错误页面)。我认为如果文件被提供,则暗示着它是一个HTTP 200
,这并不完全不合理。
我建议将错误页面文件读入字符串,然后使用这个方法:https://golang.org/pkg/net/http/#Error
编辑:实际上,这可能对您来说还不够具体。它希望将错误消息作为纯文本,所以我建议的可能是一种误用。在这种情况下,您将无法使用任何有用的抽象来实现您想要的功能。
回应评论,我个人更喜欢以下方式:
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
resp := &http.Response{
StatusCode: 404,
}
resp.Write(w)
})
}
但是如果您喜欢的话,您也可以使用w.WriteHeader(http.StatusForbidden)
或其他任何方法。选择更适合您需求的方式。根据我的经验,我更喜欢在与mux不同的作用域中准备响应对象,因此我更喜欢上面的代码片段(它比让辅助方法返回非结构化数据然后写入响应写入器更有意义)。
英文:
From reading the source I don't see any way to change the status code (other than the method failing which means you won't get your error page served). I think it's implied that if the files is served then it was an HTTP 200
which isn't entirely unreasonable.
I recommend reading the error page file into a string then using this method; https://golang.org/pkg/net/http/#Error
EDIT: That may actually not be specific enough for you even. It wants the error message as plain text so what I suggested is likely a misuse. In which case you're left with no useful abstractions to do what you want.
In response to comment, my personal preference would be something more along the line of;
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
resp := &http.Response{
StatusCode: 404,
}
resp.Write(w)
})
}
but you could also just use w.WriteHeader(http.StatusForbidden)
or whatever if that's your preference. Whatever better suites you needs. My experience would be with preparing response object in a scope different than that of the mux so for that reason I think I prefer the bit above (it makes more sense than having helper methods return unstructured data you then write in to the responsewriter).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论