To generate HTML error pages and handle HTTP errors in Go, you can follow these steps:
http.ResponseWriter
and an http.Request
as parameters. This handler function will be responsible for generating the HTML error page.func errorHandler(w http.ResponseWriter, r *http.Request) {
// Generate HTML error page
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "<h1>Error</h1>")
fmt.Fprintf(w, "<p>Something went wrong.</p>")
}
http.HandleFunc
function.func main() {
// ...
http.HandleFunc("/error", errorHandler)
http.ListenAndServe(":8080", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
// Example code that may produce an error
err := someFunction()
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// ...
}
In the above example, when someFunction
returns an error, we return a 500 Internal Server Error
status code. This will trigger the errorHandler
function to generate and display the HTML error page.
You can customize the HTML error page generated in the errorHandler
function to match your specific requirements.