// Package to manage routing of urls in net/http // URLs type is the main thing of interest package gispatcho import ( "fmt" "net/http" "regexp" ) // Represent a single URL with a name, a pattern and supported protocol type URL struct { Handler func(http.ResponseWriter, *http.Request) Path string Protocol string } // Return the corresponding net/http pattern for a URL func (url *URL) GetPattern() string { return fmt.Sprintf("%s %s", url.Protocol, url.Path) } // Represent a set of URLs at a prefix type URLs struct { URLs map[string]URL Prefix string } type Repl map[string]string // Given a name and replacements, return a rendered path component of a URL func (urls URLs) Reverse(name string, replacements Repl) string { pattern := urls.URLs[name].Path for key, val := range replacements { re := regexp.MustCompile("{" + key + "}") pattern = re.ReplaceAllString(pattern, val) } return urls.Prefix + pattern } // Return router for the urls func (urls URLs) GetRouter() *http.ServeMux { router := http.NewServeMux() for _, url := range urls.URLs { router.HandleFunc(url.GetPattern(), url.Handler) } return router }