Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
06 Oct 2023 · 2 min read ·Article 65 / 119
Go

06 Handle Not Found Page

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

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

go
1router.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.

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

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

go
1router.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.

bash
1go build && ./learn-golang-httprouter

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

bash
1➜  santekno-hugo git:(main) ✗ curl --location --request GET 'http://localhost:8080/haha' 
2404 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.

bash
1➜  santekno-hugo git:(main) ✗ curl --location --request GET 'http://localhost:8080/haha'
2halaman tidak ditemukan%  

Related Articles

💬 Comments