Post

Go NotFoundHandler()

How to use http.NotFoundHandler in Go to return a 404 response for specific routes like favicon.ico.

This program demonstrates http.NotFoundHandler() in Go. The NotFoundHandler returns a handler that responds with a 404 Not Found status. It is commonly used to suppress browser requests for /favicon.ico that would otherwise be caught by the root / handler and clutter server logs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
	"fmt"
	"io"
	"net/http"
)

func main() {

	http.HandleFunc("/", index)

	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.ListenAndServe(":8080", nil)
}

func index(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("requested url: %v\n", r.URL)
	io.WriteString(w, "Hello from Go dude!")
}

This post is licensed under CC BY 4.0 by the author.