英文:
Serving Static Files with a HTTP 500 Status
问题
在Go语言中,有没有一种方法可以使用自定义状态码通过HTTP提供静态文件(而不需要重写大量私有代码)?
从我所了解的情况来看:
- http.ServeFile 调用了辅助函数 http.serveFile。
- 然后,在确定文件/目录的修改时间和大小(以及是否存在)后,它调用了 http.ServeContent。
- 最后,调用了 http.serveContent,该函数设置了正确的头部(Content-Type、Content-Length)并设置了一个
http.StatusOK
头部 这里。
我想我已经知道这个问题的答案了,但如果有人有其他解决方案,那将会很有用。
使用案例是提供 500.html、404.html 等文件。通常我会使用 nginx 来捕获 Go 的常规纯文本 http.Error
响应,并让 nginx 从磁盘上提供文件,但我处于一个无法使用 nginx 的环境中。
英文:
Is there a way to serve static files over HTTP in Go with a custom status code (without re-writing a significant amount of private code)?
From what I can see:
- http.ServeFile calls the helper function http.serveFile
- It then calls http.ServeContent after determining the mod time and size of the file/dir (and if it exists)
- Finally, http.serveContent is called, which sets the correct headers (Content-Type, Content-Length) and sets a
http.StatusOK
header here.
I think I already know the answer for this, but if someone has an alternative solution it'd be useful.
The use case is serving 500.html, 404.html, et. al files. I'd normally use nginx to catch Go's usual plain http.Error
responses and have nginx serve the file off disk, but I'm in an environment where that's not an option.
答案1
得分: 7
包装http.ResponseWriter
:
type MyResponseWriter struct {
http.ResponseWriter
code int
}
func (m MyResponseWriter) WriteHeader(int) {
m.ResponseWriter.WriteHeader(m.code)
}
然后(用于HTTP 500错误):
http.ServeFile(MyResponseWriter{rw, 500}, rq, "file.name")
其中rw
是实际的http.ResponseWriter
,rq
是*http.Request
对象。
英文:
Wrap http.ResponseWriter
:
type MyResponseWriter struct {
http.ResponseWriter
code int
}
func (m MyResponseWriter) WriteHeader(int) {
m.ResponseWriter.WriteHeader(m.code)
}
And then (for an HTTP 500):
http.ServeFile(MyResponseWriter{rw, 500}, rq, "file.name")
Where rw
is the "actual" http.ResponseWriter
and rq
is the *http.Request
object.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论