Initial commit with cru (no delete) of notes
This commit is contained in:
commit
1e1174f9ca
11 changed files with 244 additions and 0 deletions
47
internal/urls/urls.go
Normal file
47
internal/urls/urls.go
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
// Package to manage routing of urls in net/http
|
||||
// URLs type is the main thing of interest
|
||||
package urls
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// Given a name and replacements, return a rendered path component of a URL
|
||||
func (urls URLs) Reverse(name string, replacements map[string]string) 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
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue