Adding namespace feature to Golang -httprouter

https://github.com/julienschmidt/httprouter is lightweight and high performance Http router for golang. In this article, I would like to add namespace feature for httprouter.

You cannot use namespace in httprouter. Normally, You can use httprouter as follow:

package main

import (
"fmt"
"github.com/julienschmidt/httprouter"
"net/http"
"log"
)

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Welcome!\n")
}

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}

func main() {
router := httprouter.New()
router.GET("/", Index)
router.GET("/hello/:name", Hello)

log.Fatal(http.ListenAndServe(":8080", router))
}

But, sometime you might need namespace feature as follow.

api/v1/route1
api/v1/route1
api/v1/route2

So, you have to write the prefix in every route’s function.

For my personal requirements, I added namespace to httprouter as value added feature in my repo https://github.com/kyawmyintthein/httprouter. Usage will be different. To be honest, I have no idea about the performance of the httprouter of my version. I hope it will be still heigh performance.

If you want to use namespace feature, you can use from my repo https://github.com/kyawmyintthein/httprouter. I also support nested namespace such as api/v1, api/v2 and etc.

Here is the usage for nested namespace,

package main

import (
"fmt"
"github.com/kyawmyintthein/httprouter"
"github.com/kyawmyintthein/httprouter/namespace"
"net/http"
"log"
)

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Welcome!\n")
}

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}

func main() {
router := httprouter.New()

root := namespace.New("/api")
root.RouteTo("GET", "/", Index)

v1 := root.Use("/v1")
v1.RouteTo("GET","/hello/:name", Hello)

root.Handle(router)

log.Fatal(http.ListenAndServe(":8080", router))
}

You can use multiple nested namespace with httprouter. httprouter is awesome lib. I hope it will better.