Not Found Page - Go

Page Not Found - Go

In my previous TIL post about custom routing, I did not specify any page or message once a request is asking for a resource that is not found in the server. Below is the way how it could be added:


package main

import (
	"fmt"
	"net/http"
)

func homeHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Header().Add("Fake", "my fake header")
	fmt.Fprint(w, "<h1> Welcome to my site </h1>")
}

func contactHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprint(w, "<h1>  Contact Page </h1><p> To get in touch, email me at <a href=\"mailto:rabocse@alexrabocse.me\"> rabocse@alexrabocse.me </a>.")
}

func pathHandler(w http.ResponseWriter, r *http.Request) {
	switch r.URL.Path {
	case "/":
		homeHandler(w, r)
	case "/contact":
		contactHandler(w, r)
	default:
		// http.Error(w, "Page Not Found... ", http.StatusNotFound)
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprint(w, "Page Not Found")
	}
}

func main() {

	http.HandleFunc("/", pathHandler)
	fmt.Println("Starting the server on :3000...")
	http.ListenAndServe(":3000", nil)

}

Notice that the source code is showing two ways to acomplish it:

  1. fmt.Fprint and w.WriteHeader.
  2. http.Error.

The second one is of course commented out but any of those could be used.


Here I can see the results:

❯ curl localhost:3000/contact
<h1>  Contact Page </h1><p> To get in touch, email me at <a href="mailto:rabocse@alexrabocse.me"> rabocse@alexrabocse.me </a>.%

❯ curl localhost:3000/kkkkkk
Page Not Found%

 Share!

 
comments powered by Disqus