Golang Gorilla Mux NewRouter Handle

Golang Gorilla Mux

Golang has net/http package for managing HTTP. Then Why we need a third-party Golang package Gorilla Mux. The answer is Go’s net/http package offers a lot of features for HTTP requests routing but one thing it doesn’t do very well is Dynamic Routing, which will be achieved by Golang Gorilla Mux NewRouter Handle Function.

Dynamic Routing in Golang can be achieved by using a third-party package i.e gorilla/mux.

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

In this blog, we will be using gorilla/mux to define routes, as we did in the previous blog.

Let’s us first learn how to install and set-up third-party packages in Golang.

Install gorilla/mux using go get command

$  go get github.com/gorilla/mux

The go get Command will install the packages in the $GOPATH/src.

Another way of installing the package is manual. Clone the repository and then manually place it to the $GOPATH/src.

Golang Gorilla Mux NewRouter

package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
)

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

// GetRequest Handler
var GetRequest = http.HandlerFunc(
	func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Get Request Handler")
	},
)

// PostRequest Handler
var PostRequest = http.HandlerFunc(
	func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Post Request Handler")
	},
)

// PathVariable Handler
var PathVariable = http.HandlerFunc(
	func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		name := vars["name"]
		fmt.Fprint(w, "Hello, ", name)
	},
)

func main() {

	router := mux.NewRouter()
	router.Handle("/", GetRequest).Methods("GET")
	router.Handle("/post", PostRequest).Methods("POST")
	router.Handle("/about/{name}", PathVariable).Methods("GET", "PUT")
	http.ListenAndServe(Host+":"+Port, router)

}

Run the Program

$  go run gorilla-mux-handler.go

In the above code in the main function, we registered all the handlers with the gorilla/mux router. The router variable is instantiated by calling the NewRouter() handler of the mux router.

Learn more about Golang Gorilla Mux Router Handle Function from Golang net/http package.

Tags:

Leave a Reply

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