How to Get Dynamic Params in Golang Routes Using net/http

Robin
Updated on December 14, 2023

Golang net/http package doesn't provide any built-in method to get dynamic params from your route URL. But still, you can extract the dynamic parameter value.

Inside your route handle, you can get the route path from r.URL.Path and get the dynamic part from it.

Setup Golang Routes to Accept Dynamic Parameters

If you want to accept a dynamic parameter in your route, you must define it slightly differently. Because when you define a route for "/users", this will only handle exactly "/users" path.

For example:

          http.HandleFunc("/users", usersHandler)
        

This route will only work if you request the /users path. But if you request a path like /users/username, this route won't handle it.

Because by default, the net/http package works for exact match routes.

Therefore, when you want to define a route that takes a dynamic part, you must add a slash (/) at the end of it.

          http.HandleFunc("/users/", usersHandler)
        

I have added an extra slash at the end of my /users/ route. Now, if you request to /users/john_doe path, this route will handle the request.

You can write anything after /users/ and it will match this route. Let's see how you can get this dynamic part inside your route handler function.

Also Read: How to Get Query Params in Golang Routes Using net/http


Get Dynamic Params From Golang Routes

Suppose you want to define a route that will return individual user details. For that, users will send requests to the /users/[username] route.

This route will return information based on the username from the URL. That means this username is a dynamic parameter.

          package main

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

func main() {
	http.HandleFunc("/users/", usersHandler)

	// Start the server on port 8080
	fmt.Println("Server is running on port 8000")
	http.ListenAndServe(":8000", nil)
}

func usersHandler(w http.ResponseWriter, r *http.Request) {
	values := strings.Split(r.URL.Path, "/")

	username := values[2]
	
	if username == "" {
		http.NotFound(w, r)
		return
	}
	
	fmt.Println(username)
	// john_doe

	fmt.Fprintln(w, "Users page")
}

        

Inside the usersHandler() function, you can get the request path from r.URL.Path.

When you send a request to http://localhost:8000/users/john_doe URL, the r.URL.Path will return "/users/john_doe".

You can split the path by the slash (/) using strings.Split() method. It will return a slice of strings.

          [ users john_doe]
        

When you split the path by slash (/), the first item will be an empty string in the slice. So, the username will be at index 2.

If you don't provide a username in your URL, it will be an empty string.

So, you can check if it is an empty string or not, and then you can use it according to your requirements.

Related Posts