How to match a string with a url pattern just like in a gorilla/mux router?

Basically I have this code:

package main

import (
	"github.com/gorilla/mux"
	[...]
)

func main(){
	[...]
	router := mux.NewRouter()

	router.HandleFunc("/", handler.ViewAllPosts).Methods(http.MethodGet)
	router.HandleFunc("/events", handler.ViewEvents).Methods(http.MethodGet)
	router.HandleFunc("/about", handler.ViewAbout).Methods(http.MethodGet)
	router.HandleFunc("/blog/{URLTitle}", handler.ViewPost).Methods(http.MethodGet)
	[...]
}

And I’d like to do something like this:

switch urlStringVar {
	case "/":
		fmt.Println("ViewAllPosts")
	case "/events":
		fmt.Println("ViewEvents")
	case "/about":
		fmt.Println("ViewAbout")
	case "/blog/{URLTitle}":
		fmt.Println("ViewPost")
}

The detail (if possible) is that it must match exactly the same as it would with “gorilla/mux”, is there any way to achieve this? or what other option do you recommend?

It is simple to do this with ONE level. I have not tested with several levels. But you can get some hints from here.

@ Sibert

That I can do, my problem is with the wildcards:
case "/blog/{URLTitle}":

You can extract parts (wildcards) of the url path in 2 levels down (in this example) using this function. This may need extra code to be fully functional.

func getpath(r *http.Request) (string, string) {
	path := strings.Split(r.URL.String(), "/")
	switch len(path) {
	case 2:
		return path[1], "", ""
	default:
		return "", "", ""
	}
}

Pseudo code:

path1, path2 = getpath(r)

switch levels {
	case path2='':
		Open page path1
	default:
		Open page "blog/" + path2
}

if page not exist open 404.html

This reduces the case levels

Look into gorilla/mux code.

Another option would be to check out the code for julienschmidt/httprouter. It is only a router, and has far fewer lines of code than gorilla/mux. Might be easier to understand the salient bits.

1 Like