【问题标题】:Why do I get this error/warning related to writing a response header?为什么我会收到与编写响应标头相关的错误/警告?
【发布时间】:2021-02-14 14:37:04
【问题描述】:

无论我设置内容类型并编写状态代码,我都会收到此错误。我真的不知道为什么......

在我看来这是一项非常平凡的任务——我只想设置 Content-Type 和 http 状态代码。服务器确实可以正常工作,它可以很好地为网页提供服务,但是每次我请求该端点/路径时,它都会将该消息记录到终端。

错误

http: superfluous response.WriteHeader call from main.indexHandler (server.go:49)

代码

package main

import (
    "context"
    "log"
    "net/http"
    "os"
    "os/signal"
    "time"

    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()

    fs := http.FileServer(http.Dir("./static"))
    r.PathPrefix("/assets/").Handler(http.StripPrefix("/assets/", fs))

    r.HandleFunc("/", indexHandler).Methods("GET")

    server := &http.Server{
        Addr:    "0.0.0.0:8080",
        Handler: r,
    }

    go func() {
        if err := server.ListenAndServe(); err != nil {
            log.Fatal("Unable to start the server")
        }
    }()

    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt)

    <-c

    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    if err := server.Shutdown(ctx); err != nil {
        log.Fatal("Unable to gracefully shutdown the server")
    }
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html")
    w.WriteHeader(http.StatusOK)

    http.ServeFile(w, r, "./static/index.html")
}

【问题讨论】:

标签: go web server


【解决方案1】:

func indexHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html")
    w.WriteHeader(http.StatusOK)

    http.ServeFile(w, r, "./static/index.html")
}

您不需要w.WriteHeader 电话。 http.ServeFile 将根据其成功提供文件来设置状态。

如果您想了解此错误消息是如何产生的,请查看WriteHeader 方法的实现以及如果标头已写入,它会做什么。

【讨论】:

  • 啊,这很有意义。谢谢。我可以在第 297 行的“fs.go”中看到它确实通过调用“WriteHeader(code)”来设置状态代码。
  • @SamWood:是的,并且代码有一个聪明的relevantCaller 函数,它会进行一些堆栈遍历以找到真正的罪魁祸首
  • 其实反之亦然,WriteHeader发送的header是不能被覆盖的,ServeFileheader就变得多余了,意味着它无法指示其他任何状态超过 200
  • @JimB:感谢您的评论,您是对的。我从答案中删除了令人困惑的句子。
猜你喜欢
  • 2011-11-10
  • 2015-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
相关资源
最近更新 更多