Home > Articles

  • Print
  • + Share This
This chapter is from the book

Handling 404s

The behavior of the default Handler is to pass any request that does not have a handler function defined to /. Returning to the first example, if a request is made to a non-existent page, the handler function for / is called, and a 200 along with the “Hello World” response is returned.

curl -is http://localhost:8000/asdfa
HTTP/1.1 200 OK
Date: Thu, 17 Nov 2016 09:07:51 GMT
Content-Length: 12
Content-Type: text/plain; charset=utf-8

As the route does not exist, a 404 Page Not Found should be returned. On the default route, a check can be added to return a 404 if the path is not / (see Listing 18.2).

LISTING 18.2 Adding a 404 Response

 1:  package main
 2:
 3:  import (
 4:     "net/http"
 5:  )
 6:
 7:  func helloWorld(w http.ResponseWriter, r *http.Request) {
 8:     if r.URL.Path != "/" {
 9:              http.NotFound(w, r)
10:              return
11:     }
12:     w.Write([]byte("Hello World\n"))
13:  }
14:
15:  func main() {
16:      http.HandleFunc("/", helloWorld)
17:      http.ListenAndServe(":8000", nil)
18:  }

The modifications to the initial Hello World web server may be explained as follows:

  • In the helloWorld handler function, the path is checked to see if it is /.

  • If it is not, the NotFound method from the http package is called, passing the response and request. This writes a 404 response to the client.

  • If the path does match /, then the if statement is ignored and the Hello World response is sent.

  • + Share This
  • 🔖 Save To Your Account