Routing in Go using Gorilla Mux

The net/http package has a lot of functionalities. The gorilla/mux comes with more routing features. In this article, we’re going to use gorilla mux for routing in Go. Let’s start:

Table of Contents

  1. Install Gorilla Mux Package
  2. Features of Gorilla Mux
  3. A Complete Example

Install Gorilla Mux Package

We can install gorilla/mux using go get  command:

go get -u

Features of Gorilla Mux

I’m going to share some features of the Gorilla Mux package.

The routing syntax:

r := mux.NewRouter()

Restrict the request: We’re able to restrict to specific domain/subdomain:

r.HandleFunc("/posts/{slug}", BookHandler).Host("")

Prefixes & Subrouters: We can set prefix and sub router like this:

bookrouter := r.PathPrefix("/posts").Subrouter()
bookrouter.HandleFunc("/", AllPosts)
bookrouter.HandleFunc("/{slug}", GetSinglePost)

HTTP methods: We can set specific method to routes:

r.HandleFunc("/posts/{slug}", CreatePost).Methods("POST")
r.HandleFunc("/posts/{slug}", ReadPost).Methods("GET")
r.HandleFunc("/posts/{slug}", UpdatePost).Methods("PUT")
r.HandleFunc("/posts/{slug}", DeletePost).Methods("DELETE")

Schemes: We’re able to set HTTP/HTTPS protocol restriction in route:

r.HandleFunc("/route1", HandlerInsecure).Schemes("http")
r.HandleFunc("/route2", HandlerSecure).Schemes("https")

A Complete Example

Let’s see a full example routing using gorilla mux:

package main

import (

func index(w http.ResponseWriter, req *http.Request)  {
    fmt.Fprintf(w, "Welcome to MyNotePaper!")

func posts(w http.ResponseWriter, req *http.Request)  {
    vars := mux.Vars(req)
    post_id := vars["id"]

    fmt.Fprintf(w, "The requested post ID: %s\n", post_id)

func main() {
    r := mux.NewRouter()

    // routes
    r.HandleFunc("/", index)
    r.HandleFunc("/posts/{id}", posts)

    // listen port 80
    http.ListenAndServe(":80", r)

I hope this article will help you.

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.