Friday, April 26, 2024
HomeGolangTips on how to match a string with a url sample identical...

Tips on how to match a string with a url sample identical to in a gorilla/mux router? – Getting Assist


Principally I’ve this code:

package deal most important

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

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

	router.HandleFunc("https://discussion board.golangbridge.org/", handler.ViewAllPosts).Strategies(http.MethodGet)
	router.HandleFunc("/occasions", handler.ViewEvents).Strategies(http.MethodGet)
	router.HandleFunc("/about", handler.ViewAbout).Strategies(http.MethodGet)
	router.HandleFunc("/weblog/{URLTitle}", handler.ViewPost).Strategies(http.MethodGet)
	[...]
}

And I’d love to do one thing like this:

swap urlStringVar {
	case "https://discussion board.golangbridge.org/":
		fmt.Println("ViewAllPosts")
	case "/occasions":
		fmt.Println("ViewEvents")
	case "/about":
		fmt.Println("ViewAbout")
	case "/weblog/{URLTitle}":
		fmt.Println("ViewPost")
}

The element (if potential) is that it should match precisely the identical as it might with “gorilla/mux”, is there any solution to obtain this? or what different possibility do you advocate?

It’s easy to do that with ONE stage. I’ve not examined with a number of ranges. However you may get some hints from right here.

@ Sibert

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

You may extract components (wildcards) of the url path in 2 ranges down (on this instance) utilizing this perform. This will likely want further code to be totally useful.

func getpath(r *http.Request) (string, string) {
	path := strings.Cut up(r.URL.String(), "https://discussion board.golangbridge.org/")
	swap len(path) {
	case 2:
		return path[1], "", ""
	default:
		return "", "", ""
	}
}

Pseudo code:

path1, path2 = getpath(r)

swap ranges {
	case path2='':
		Open web page path1
	default:
		Open web page "weblog/" + path2
}

if web page not exist open 404.html

This reduces the case ranges

Look into gorilla/mux code.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments