programming

06 Handle Not Found Page

Understanding Not Found Handler

Apart from the Router being able to control panic, it can also have a handler for pages not found or what we often call pages that cannot be accessed. The Not Found handler is a handler that is executed when a client tries to make a request for a page or URL of our website that is not in our Router service. By default, if there is no route it will not be found, but the Router will continue the request to http.NotFound, but we can also change it to a specific router page by changing

router.NotFound = http.Handler

How to Implement

We will try to implement a handler to redirect pages that do not have a route or page in our service. OK, let’s try opening the handler.go file then add the not found handler which was explained above and looks like this.

func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "halaman tidak ditemukan")
}

After that, we call the NotFoundhandler function in the main function in the main.go file.

router.NotFound = http.HandlerFunc(NotFoundHandler)

So, we have implemented a page not found on our service router. Next we will try to test it, so first we rerun our program or service with this command.

go build && ./learn-golang-httprouter

If we compare it with before using the previous not found custom router it will display a page like this.

➜  santekno-hugo git:(main) ✗ curl --location --request GET 'http://localhost:8080/haha' 
404 page not found

then after we use the custom handler not found then we try to access any page using the cURL command below and it will display the page according to what we have created on the router above.

➜  santekno-hugo git:(main) ✗ curl --location --request GET 'http://localhost:8080/haha'
halaman tidak ditemukan%  
comments powered by Disqus