I need to have a custom not found html page. Here is what I've tried:
package main
import (
"net/http"
"github.com/julienschmidt/httprouter"
)
func main() {
r := httprouter.New()
r.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
http.ServeFile(w, r, "files/not-found.html")
})
http.ListenAndServe(":8000", r)
}
I have the line w.WriteHeader(404)
to make sure the status code is 404, but the code above gives the error:
http: multiple response.WriteHeader calls
Without the line w.WriteHeader(404)
there are no errors and the page is shown correctly, but the status code is 200. I want it to be 404.
You can simply just write the contents yourself.
Something like:
r.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
contents, err := ioutil.ReadFile("files/not-found.html")
if err != nil {
panic(err) // or do something useful
}
w.WriteHeader(404)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(contents)
})
David's answer worked, and this is another way.
// other header stuff
w.WriteHeader(http.StatusNotFound)
file, err := os.Open("files/not-found.html")
if err != nil {
log.Println(err)
return
}
_, err = io.Copy(w, file)
if err != nil {
log.Println(err)
}
file.Close() // consider defer ^