web.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. /*
  2. The Kurz Web UI exposes HTTP routes for browsers, route names to access them, and types for the requests.
  3. These routes are exposed by running SetupUI(listenAddress), which is enough to
  4. configure the Kurz domain API. Be sure to also configure the domain SPI to have
  5. a complete application.
  6. */
  7. package ui
  8. import (
  9. "errors"
  10. "fmt"
  11. "html/template"
  12. "log"
  13. "net/http"
  14. "net/url"
  15. "path"
  16. "path/filepath"
  17. "strconv"
  18. "strings"
  19. "github.com/gorilla/mux"
  20. "github.com/gorilla/sessions"
  21. "github.com/spf13/cast"
  22. )
  23. // Route names.
  24. const (
  25. RouteGetRoot = "kurz.web.get_root"
  26. RouteGetShort = "kurz.web.get_short"
  27. RoutePostTarget = "kurz.web.post_target"
  28. )
  29. // Content types.
  30. const (
  31. HtmlFormType = "application/x-www-form-urlencoded"
  32. // HtmlType is the MIME HTML type.
  33. HtmlType = "text/html"
  34. // HtmlTypeRegex is a regex matching the MIME HTML type anywhere
  35. HtmlTypeRegex = HtmlType
  36. )
  37. type Globals struct {
  38. AssetsBaseURL string
  39. AssetsVersion int
  40. AssetsPath string
  41. SessionKey []byte
  42. SessionName string
  43. SiteBaseURL string
  44. RefreshDelay int
  45. SiteName string
  46. }
  47. var globals Globals
  48. var router mux.Router
  49. var store *sessions.CookieStore
  50. var tmpl *template.Template
  51. // SetupUI() configures Web UI routes on the passed mux.Router.
  52. func SetupUI(router *mux.Router, configAssetsPath string) {
  53. // Set up asset routes first, for them to have priority over possibly matching short URLs.
  54. setupAssetRoutes(configAssetsPath, router)
  55. setupControllerRoutes(router)
  56. setupTemplates(configAssetsPath)
  57. }
  58. func setupAssetRoutes(configAssetsPath string, router *mux.Router) {
  59. absAssetsDir, err := filepath.Abs(configAssetsPath)
  60. if err != nil {
  61. panic(err)
  62. }
  63. log.Printf("Serving assets from %s\n", absAssetsDir)
  64. fs := http.FileServer(http.Dir(absAssetsDir))
  65. router.Handle("/favicon.ico", fs)
  66. for _, prefix := range []string{"css", "js", "images"} {
  67. router.PathPrefix("/" + prefix).Handler(fs)
  68. }
  69. }
  70. func setupControllerRoutes(gmux *mux.Router) {
  71. router = *gmux
  72. // BUG(fgm): improve Accept header matchers once https://github.com/golang/go/issues/19307 is completed.
  73. gmux.HandleFunc("/{short}", func(w http.ResponseWriter, r *http.Request) {
  74. handleGetShort(w, r, gmux)
  75. }).
  76. Methods("GET", "HEAD").
  77. Name(RouteGetShort)
  78. gmux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  79. handlePostTarget(w, r, gmux)
  80. }).
  81. HeadersRegexp("Accept", HtmlTypeRegex).
  82. Headers("Content-Type", HtmlFormType).
  83. Methods("POST").
  84. Name(RoutePostTarget)
  85. gmux.HandleFunc("/", handleGetRoot).
  86. Methods("GET", "HEAD").
  87. Name(RouteGetRoot)
  88. }
  89. func setupTemplates(configAssetsPath string) {
  90. base, _ := filepath.Abs(configAssetsPath + "/../templates/")
  91. layout := base + "/layout"
  92. funcMap := template.FuncMap{
  93. "asset": URLForAsset,
  94. "path": urlFromRouteVariadic,
  95. }
  96. tmpl = template.Must(template.New("kurz").
  97. Funcs(funcMap).
  98. ParseFiles(
  99. base+"/201.gohtml",
  100. base+"/404.gohtml",
  101. base+"/409.gohtml",
  102. base+"/home.gohtml",
  103. layout+"/analytics.gohtml",
  104. layout+"/flashes.gohtml",
  105. layout+"/footer.gohtml",
  106. layout+"/inlinecss.gohtml",
  107. ))
  108. }
  109. func SetupGlobals(c map[string]interface{}) {
  110. // Note: keys in viper are lower-cased.
  111. globals = Globals{
  112. AssetsBaseURL: strings.Trim(c["assetsbaseurl"].(string), "/"),
  113. AssetsPath: c["assetspath"].(string),
  114. AssetsVersion: c["assetsversion"].(int),
  115. RefreshDelay: c["refreshdelay"].(int),
  116. SessionKey: []byte(c["sessionkey"].(string)),
  117. SessionName: c["sessionname"].(string),
  118. SiteBaseURL: strings.Trim(c["sitebaseurl"].(string), "/"),
  119. SiteName: c["sitename"].(string),
  120. }
  121. store = sessions.NewCookieStore(globals.SessionKey)
  122. }
  123. /*
  124. URLFromRoute generates absolute URLs for named routes.
  125. To build URLs for assets, use URLForAsset().
  126. - ns: the assets namespace. One of "js", "css', "images".
  127. - path: the asset path relative to the project root
  128. */
  129. func URLFromRoute(router *mux.Router, name string, params map[string]string) (string, error) {
  130. route := router.Get(name)
  131. if route == nil {
  132. err := errors.New(fmt.Sprintf("Error building unregistered route %s\n", name))
  133. return "", err
  134. }
  135. pairs := mapToPairs(params)
  136. url, err := route.URL(pairs...)
  137. if err != nil {
  138. err = errors.New(fmt.Sprintf("Error building route %s: %s\n", name, err))
  139. return "", err
  140. }
  141. // Don't use path.Join, it would clobber the scheme://domain format.
  142. // SiteBaseURL is "/"-trimmed on setup.
  143. fqsu := globals.SiteBaseURL + url.String()
  144. return fqsu, nil
  145. }
  146. func urlFromRouteVariadic(name string, paramPairs ...interface{}) (string, error) {
  147. if len(paramPairs)%2 != 0 {
  148. return "", errors.New("needs an even number of arguments")
  149. }
  150. var params = make(map[string]string, len(paramPairs)/2)
  151. var k string
  152. for i, r := range paramPairs {
  153. if i%2 == 0 {
  154. // If i is even, this is the key for the next value.
  155. k = r.(string)
  156. } else {
  157. // Else it is a value, so store it with the key we just got previously.
  158. params[k] = cast.ToString(r)
  159. }
  160. }
  161. return URLFromRoute(&router, name, params)
  162. }
  163. /*
  164. URLForAsset generates absolute URLs for assets.
  165. To build URLs for routes, use URLFromRoute().
  166. - ns: the assets namespace. One of "", "js", "css', "images". "" is only expected
  167. to be used for "favicon.ico".
  168. - path: the asset path relative to the project root
  169. */
  170. func URLForAsset(ns string, assetPath string) (string, error) {
  171. if ns != "" && ns != "css" && ns != "js" && ns != "images" {
  172. return "", errors.New("invalid asset namespace: " + ns)
  173. }
  174. version := globals.AssetsVersion
  175. base, err := url.Parse(globals.AssetsBaseURL)
  176. if err != nil {
  177. panic(err)
  178. }
  179. // Handles "" cleanly, and doesn't use a "\" on windows, unlike filepath.Join.
  180. base.Path = path.Join(base.Path, ns, assetPath)
  181. // No need to url.QueryEscape() since this format is query-clean by construction.
  182. base.RawQuery = "v=" + strconv.Itoa(version)
  183. res := base.String()
  184. return res, nil
  185. }