Search code examples
gowebserver

Why do I get this error/warning related to writing a response header?


I get this error, regardless of which way round I set the content type and write the status code. I can't really figure out why...

It seems to me like a very mundane task - I just want to set the Content-Type and the http status code. The server does actually work, it serves the web page just fine, but it logs that message to the terminal every time I request that endpoint/path.

Error

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

Code

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")
}

Solution

  • In

    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")
    }
    

    You don't need the w.WriteHeader call. http.ServeFile will set the status based on its success in serving the file.

    If you want to understand how this error message comes to be, look at the implementation of the WriteHeader method and what it does if the header is already written.