How to generate HTML error pages and handle HTTP errors in Go?

To generate HTML error pages and handle HTTP errors in Go, you can follow these steps:

  1. Define a handler function that accepts an 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>") }
  1. In your main function or where you define your HTTP server, configure the error handler for the desired HTTP error status codes using the http.HandleFunc function.
func main() { // ... http.HandleFunc("/error", errorHandler) http.ListenAndServe(":8080", nil) }
  1. When you encounter an error in your code, return the appropriate HTTP error status code. This will trigger the error handler to generate the HTML error page.
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.