Mainly I’ve this code:
package deal fundamental
import (
"github.com/gorilla/mux"
[...]
)
func fundamental(){
[...]
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 attainable) is that it should match precisely the identical as it could with “gorilla/mux”, is there any approach 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 possibly can get some hints from right here.
@ Sibert
That I can do, my drawback is with the wildcards:case "/weblog/{URLTitle}":
You’ll be able to extract components (wildcards) of the url path in 2 ranges down (on this instance) utilizing this operate. This will want further code to be absolutely useful.
func getpath(r *http.Request) (string, string) {
path := strings.Break 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.
An alternative choice could be to take a look at the code for julienschmidt/httprouter. It’s solely a router, and has far fewer strains of code than gorilla/mux. Is perhaps simpler to know the salient bits.