The following is the approach that I choose. It is based on a piece of code that I can’t confirm because I’ve lost my browser bookmark.
Code example: (I put it in my main package)
type hijack404 struct { http.ResponseWriter R *http.Request Handle404 func (w http.ResponseWriter, r *http.Request) bool } func (h *hijack404) WriteHeader(code int) { if 404 == code && h.Handle404(h.ResponseWriter, hR) { panic(h) } h.ResponseWriter.WriteHeader(code) } func Handle404(handler http.Handler, handle404 func (w http.ResponseWriter, r *http.Request) bool) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){ hijack := &hijack404{ ResponseWriter:w, R: r, Handle404: handle404 } defer func() { if p:=recover(); p!=nil { if p==hijack { return } panic(p) } }() handler.ServeHTTP(hijack, r) }) } func fire404(res http.ResponseWriter, req *http.Request) bool{ fmt.Fprintf(res, "File not found. Please check to see if your URL is correct."); return true; } func main(){ handler_statics := http.StripPrefix("/static/", http.FileServer(http.Dir("/Path_To_My_Static_Files"))); var v_blessed_handler_statics http.Handler = Handle404(handler_statics, fire404); http.Handle("/static/", v_blessed_handler_statics);
Please configure func fire404 to display its own version of the message for 404 error.
If you are using Gorilla Mux, you can replace the main function below:
func main(){ handler_statics := http.StripPrefix("/static/", http.FileServer(http.Dir("/Path_To_My_Static_Files"))); var v_blessed_handler_statics http.Handler = Handle404(handler_statics, fire404); r := mux.NewRouter(); r.PathPrefix("/static/").Handler(v_blessed_handler_statics); // add other handlers with r.HandleFunc() if necessary... http.Handle("/", r); log.Fatal(http.ListenAndServe(":8080", nil)); }
Please feel free to correct the code if it is incorrect, as I am only new to Go. Thank.
zelda Sep 15 '14 at 9:00 2014-09-15 09:00
source share