doubi1624 2015-12-03 18:19
浏览 140
已采纳

使用http.ServeFile更改HTTP代码

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条回答 默认 最新

  • duadlkc5762218 2015-12-03 18:27
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码