Golang HTTP HandleFunc | Request Routing

Share this blog with others!

Web Development is all about multiple routing, so we have to define more than one URL route in a Go Web Application using Golang net/http HandleFunc to enable multiple Request Routing. This also includes mapping of the path to the respective Handlers and resources.

In this example, we are going to make three endpoints, such as '/', '/about', '/services' along with their handlers.

If you don’t know how to create a simple HTTP Server in Golang must Read to understand it better.

Golang HTTP HandleFunc

package main

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

const (
	// Host name of the HTTP Server
	Host = "localhost"
	// Port of the HTTP Server
	Port = "8080"
)

func home(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "HOME Page")
}

func about(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "ABOUT Page")
}

func services(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "SERVICES Page")
}

func main() {
	http.HandleFunc("/", home)
	http.HandleFunc("/about", about)
	http.HandleFunc("/services", services)
	err := http.ListenAndServe(Host+":"+Port, nil)
	if err != nil {
		log.Fatal("Error Starting the HTTP Server : ", err)
		return
	}

}

Run the Program

$  go run http-request-routing.go

Output:

Open the browser and go to http://localhost:8080, then add /about to the URL, and after all, go to /services URL. The browser will render the messages defined in the respective handlers.

This is the extension of the previous blog where we learned about the creation of a simple HTTP Server in Golang. Previously we were had one handler i.e '/' but in this blog, we have multiple endpoints.

Learn more about Golang HTTP Request Routing from the net/http package.

0 0 votes
Article Rating

Share this blog with others!
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top