Recently i used Gorilla Mux as my http router in Go. For your information, gorilla mux is one of the popular http router in Go Programming Language.

It happens when i’m trying to write a new microservice in go, and i’m ended up using go-kit. Go-Kit is a great tools when it comes to Microservices, especially in Go.

The microservices is still using REST as the communication mechanism, thats why the service itself served using gorilla.

The services works fine, i just need to address the http request from client to see a more human message with json style response.

All i need to do, is wrap up a new handlerfunc and pass it to NotFoundHandler of the router

import (
	...
	"net/http"
	...
)

r := mux.NewRouter()

...

r.NotFoundHandler = http.HandlerFunc(func (w http.ResponseWriter, req *http.Request) {
	w.Header.Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(http.StatusNotFound)
	json.NewEncoder(w).Encode(map[string]interface{}{
		"message": "request not found",
	})
})

...