使用HTTP 500状态提供静态文件

huangapple go评论81阅读模式
英文:

Serving Static Files with a HTTP 500 Status

问题

在Go语言中,有没有一种方法可以使用自定义状态码通过HTTP提供静态文件(而不需要重写大量私有代码)?

从我所了解的情况来看:

  1. http.ServeFile 调用了辅助函数 http.serveFile
  2. 然后,在确定文件/目录的修改时间和大小(以及是否存在)后,它调用了 http.ServeContent
  3. 最后,调用了 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:

  1. http.ServeFile calls the helper function http.serveFile
  2. It then calls http.ServeContent after determining the mod time and size of the file/dir (and if it exists)
  3. 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.ResponseWriterrq*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.

huangapple
  • 本文由 发表于 2015年6月18日 17:27:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/30911527.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定