gpt4 book ai didi

go - 提供具有 HTTP 500 状态的静态文件

转载 作者:IT王子 更新时间:2023-10-29 00:39:26 25 4
gpt4 key购买 nike

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

据我所知:

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

我想我已经知道了这个问题的答案,但如果有人有替代解决方案,那将会很有用。

用例服务于 500.html、404.html 等。文件。我通常会使用 nginx 来捕捉 Go 常见的普通 http.Error 响应,并让 nginx 从磁盘上提供文件,但我所处的环境无法做到这一点。

最佳答案

包装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 对象.

关于go - 提供具有 HTTP 500 状态的静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30911527/

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