Menu Close

Go – HTTP NotFound Function in Go

In this article, we will explore the http NotFound function in Go net/http package in detail, along with examples.

Introduction:

The Go programming language, often referred to as Golang, is a statically typed and compiled language designed for efficient software development. One of its strengths is building web servers and handling HTTP requests. The http.NotFound function is a handy built-in utility in the Go’s net/http package, which is used to send a 404 Not Found status code and a custom error message to the client when a requested resource is not found. This article will delve into the details and usage of the http.NotFound function with examples.

Understanding the http.NotFound function

The http.NotFound function is part of the net/http package in Go, which provides HTTP client and server implementations. The function signature is as follows:

syntax

func NotFound(w ResponseWriter, r *Request)

Parameters:

  • w: An http.ResponseWriter object that represents the server’s response to the client.
  • r: A pointer to an http.Request object that contains the details of the incoming HTTP request.

When the NotFound function is called, it sets the HTTP status code to 404 and writes a default “404 page not found” message to the response body. It is typically used as a fallback when none of the defined routes match the incoming request.

Example Usage

Let’s build a simple web server using Go and demonstrate the http.NotFound function in action.

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/about", aboutHandler)

	fmt.Println("Server running on :8080")
	http.ListenAndServe(":8080", nil)
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	fmt.Fprint(w, "Welcome to the Home Page!")
}

func aboutHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/about" {
		http.NotFound(w, r)
		return
	}
	fmt.Fprint(w, "This is the About Page!")
}

In this example, we have created a simple web server that listens on port 8080 and handles two routes: “/” for the home page and “/about” for the about page. When a request arrives at a route handler, we first check if the request’s URL path matches the expected path. If not, we call the NotFound function, which sends a 404 response to the client.

Customizing the NotFound Function

In some cases, you may want to customize the 404 response with your own error message or HTML template. You can create a custom NotFound function like this:

func customNotFound(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusNotFound)
	fmt.Fprint(w, "Oops! The resource you are looking for cannot be found.")
}

Replace the default http.NotFound(w, r) calls with customNotFound(w, r) in the route handlers to use the custom 404 response.

Conclusion

The http.NotFound function in Go is an essential tool for handling 404 Not Found errors in web servers. It provides a convenient way to inform the client that the requested resource is not available. With a basic understanding of its usage and the ability to customize the response, you can build more robust and user-friendly web applications in Go.

To check more Go related articles. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

Posted in golang, net, packages

Leave a Reply

Your email address will not be published. Required fields are marked *