提供HTTP 500状态的静态文件

eli*_*rar 4 go

有没有办法通过自定义状态代码在Go中通过HTTP提供静态文件(不重写大量私有代码)?

从我所看到的:

  1. http.ServeFile调用辅助函数http.serveFile
  2. 然后在确定文件/目录的mod时间和大小后调用http.ServeContent(如果存在)
  3. 最后,调用http.serveContent,它设置正确的标题(Content-Type,Content-Length)并在此处设置http.StatusOK标题.

我想我已经知道了答案,但如果有人有替代解决方案,那就很有用了.

该用例正在服务500.html,404.html等.al文件.我通常使用nginx来捕获Go常用的简单http.Error响应并让nginx将文件提供给磁盘,但我处于一个不可选的环境中.

thw*_*hwd 7

换行http.ResponseWriter:

type MyResponseWriter struct {
    http.ResponseWriter
    code int
}

func (m MyResponseWriter) WriteHeader(int) {
    m.ResponseWriter.WriteHeader(m.code)
}
Run Code Online (Sandbox Code Playgroud)

然后(对于HTTP 500):

http.ServeFile(MyResponseWriter{rw, 500}, rq, "file.name")
Run Code Online (Sandbox Code Playgroud)

rw"实际" 在哪里http.ResponseWriter,rq*http.Request对象.

  • 不错,简单干净.+1 (2认同)