Skip to content

Instantly share code, notes, and snippets.

@farhany
Created April 24, 2019 03:55
Show Gist options
  • Save farhany/36bd01bf35addd5fc87edf11ce7f8381 to your computer and use it in GitHub Desktop.
Save farhany/36bd01bf35addd5fc87edf11ce7f8381 to your computer and use it in GitHub Desktop.
Custom Error Pages in Go
// Source: https://stackoverflow.com/questions/9996767/showing-custom-404-error-page-with-standard-http-package
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")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment