Affichage de la page d'erreur 404 personnalisée avec le package http standard
shalakhin
En supposant que nous avons:
http.HandleFunc("/smth", smthPage)
http.HandleFunc("/", homePage)
L'utilisateur voit une simple «page 404 introuvable» lorsqu'il essaie une mauvaise URL. Comment puis-je retourner une page personnalisée pour ce cas?
Mise à jour concernant gorilla / mux
La réponse acceptée est correcte pour ceux qui utilisent le package net / http pur.
Si vous utilisez gorilla / mux, vous devriez utiliser quelque chose comme ceci:
func main() {
r := mux.NewRouter()
r.NotFoundHandler = http.HandlerFunc(notFound)
}
Et func notFound(w http.ResponseWriter, r *http.Request)
mettez en œuvre comme vous le souhaitez.
Mostafa
Je fais généralement ceci:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", homeHandler)
http.HandleFunc("/smth/", smthHandler)
http.ListenAndServe(":12345", nil)
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
errorHandler(w, r, http.StatusNotFound)
return
}
fmt.Fprint(w, "welcome home")
}
func smthHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/smth/" {
errorHandler(w, r, http.StatusNotFound)
return
}
fmt.Fprint(w, "welcome smth")
}
func errorHandler(w http.ResponseWriter, r *http.Request, status int) {
w.WriteHeader(status)
if status == http.StatusNotFound {
fmt.Fprint(w, "custom 404")
}
}
Ici, j'ai simplifié le code pour n'afficher que le 404 personnalisé, mais j'en fais plus avec cette configuration: je gère toutes les erreurs HTTP avec errorHandler
, dans lesquelles je consigne des informations utiles et m'envoie des e-mails.