Menu Close

Go – How to get URL params in Gorilla Mux in Go

Here, we will learn How to get URL params in Gorilla Mux in go. To get params, we use mux.Vars(r *http.Request) function of gorilla mux.

Let’s register route first.

r := mux.NewRouter()

r.HandleFunc("/api/v1/users/{id}", handle_user_get).Methods("GET")

Above, You have defined GET API route with id as param. Now, pass 10 as id value in URL.

http://127.0.0.1:8000/api/v1/users/10

We will see how to get id value from the URL using gorilla mux in Go code.

func handle_user_get_oper(w http.ResponseWriter, r *http.Request) {

	user_id := mux.Vars(r)["id"] // Get id value

	fmt.Println("user_id: ", user_id)
}

Output:

user_id: 10

How to get URL params in Gorilla Mux in Go code:

package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
)

func handle_user_get(w http.ResponseWriter, r *http.Request) {

	user_id := mux.Vars(r)["id"]

	fmt.Println("user_id", user_id)

	w.Write([]byte(fmt.Sprintf("User ID: %s", user_id)))
}

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

    // register handle func
	r.HandleFunc("/api/v1/users/{id}", handle_user_get).Methods("GET")

	fmt.Println("listening on : 127.0.0.1:8000")
	
	http.ListenAndServe("127.0.0.1:8000", r)
}

You can use get API either by Postman or Curl:

curl -v http://127.0.0.1:8000/api/v1/users/20

Output:

User ID: 20

To learn more about golang, Please refer given below link:

References:

https://golang.org/pkg/

Posted in golang, gorilla mux, packages, strconv

Leave a Reply

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

Contact Us