How do I route URL?

17/02/2019 14:14 GMT

That very easy, all I used was constant variable in it’s own package, just reference the constant variable inside the router or sprintf if you’re doing reverse URL. Here an example of the constant variable I used for URL routing.

package frontUrl

const (
	BlogIndex      = "/"
	BlogAjaxIndex  = "/blogajax"
	BlogIndexPage  = "/p/:page"
	BlogIndexPageF = "/p/%d"
	BlogEntry      = "/blogentry/:idSlug"
	BlogEntryF     = "/blogentry/%d-%s"
	BlogFeed       = "/feed.json"

	FontsFiles       = "/fonts/*filepath"
	JavascriptsFiles = "/javascripts/*filepath"
	StylesheetFiles  = "/stylesheets/*filepath"
	ImagesFiles      = "/images/*filepath"
	FaviconFiles     = "/favicon/*filepath"
	DynImg           = "/dyn-img/:name"
	DynImgF          = "/dyn-img/%s"
	Style            = "/generated.css"

An example of using a constant variable inside the router.

func (b controllerBootKit) entry() {
	b.router.GET(frontUrl.BlogEntry, func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) {
		context := ctx.GetContext(request)
		b.controller.BlogEntry(context, b.idSlugValidator.GetIdSlugData(params))

Yes, I got full control of what goes on between the router and the controller, it’s wonderful, it’s also the best place to apply user restrictions (permission, csrf, you name it), many framework tries to hide this control from you, it’s feels wrong to me.

How did I use it inside the template?

With the template you can’t reference the constant variable, but you can use functions to pass in the map, here an example.

func buildExampleTemplate() *template.Template {
	m := template.FuncMap{}

	urlMap := map[string]string{
		"indexPage": BlogIndexPage,
	m["url"] = func() map[string]string { return urlMap }

	return template.Must(template.New("Test").Funcs(m).Parse(`{{ $url := url }}{{ printf $url.indexPage 1 }}`))

You can use global maps, but I wouldn’t recommend it, can cause side effects; it’s better to have a template with it’s own url map.

The constant variable can be used for html template or sql statement, but I would use a tool for that, embedder for example.

| |