我收到此錯誤,無論我以哪種方式設置內容類型并編寫狀態代碼。我真的不知道為什么...在我看來,這是一項非常平凡的任務 - 我只想設置內容類型和http狀態代碼。服務器確實可以正常工作,它為網頁提供服務很好,但是每次我請求該端點/路徑時,它都會將該消息記錄到終端。錯誤http: superfluous response.WriteHeader call from main.indexHandler (server.go:49)法典package mainimport ( "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")}
1 回答

茅侃侃
TA貢獻1842條經驗 獲得超21個贊
在
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.WriteHeaderhttp.ServeFile
如果要了解此錯誤消息是如何產生的,請查看該方法的實現以及如果標頭已寫入,它的作用。WriteHeader
- 1 回答
- 0 關注
- 128 瀏覽
添加回答
舉報
0/150
提交
取消