web.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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 web
  8. import (
  9. "errors"
  10. "github.com/gorilla/mux"
  11. "html/template"
  12. "log"
  13. "net/http"
  14. "net/url"
  15. "path"
  16. "path/filepath"
  17. "strconv"
  18. )
  19. // Route names.
  20. const (
  21. RouteGetRoot = "kurz.web.get_root"
  22. RouteGetShort = "kurz.web.get_short"
  23. RoutePostTarget = "kurz.web.post_target"
  24. )
  25. // Content types.
  26. const (
  27. // HtmlType is the MIME HTML type.
  28. HtmlType = "text/html"
  29. // HtmlTypeRegex is a regex matching the MIME HTML type anywhere
  30. HtmlTypeRegex = HtmlType
  31. )
  32. type Globals struct {
  33. AssetsBaseURL string
  34. AssetsVersion int
  35. AssetsPath string
  36. SiteBaseURL string
  37. RefreshDelay int
  38. SiteName string
  39. }
  40. var globals Globals
  41. var tmpl *template.Template
  42. // SetupUI() configures Web UI routes on the passed mux.Router.
  43. func SetupUI(router *mux.Router, configAssetsPath string) {
  44. // Set up asset routes first, for them to have priority over possibly matching short URLs.
  45. setupAssetRoutes(configAssetsPath, router)
  46. setupControllerRoutes(router)
  47. setupTemplates(configAssetsPath)
  48. }
  49. func setupAssetRoutes(configAssetsPath string, router *mux.Router) {
  50. absAssetsDir, err := filepath.Abs(configAssetsPath)
  51. if err != nil {
  52. panic(err)
  53. }
  54. log.Printf("Serving assets from %s\n", absAssetsDir)
  55. fs := http.FileServer(http.Dir(absAssetsDir))
  56. router.Handle("/favicon.ico", fs)
  57. for _, prefix := range []string{"css", "js", "images"} {
  58. router.PathPrefix("/" + prefix).Handler(fs)
  59. }
  60. }
  61. func setupControllerRoutes(router *mux.Router) {
  62. // BUG(fgm): improve Accept header matchers once https://github.com/golang/go/issues/19307 is completed.
  63. router.HandleFunc("/{short}", func(w http.ResponseWriter, r *http.Request) {
  64. handleGetShort(w, r, router)
  65. }).
  66. Methods("GET", "HEAD").
  67. Name(RouteGetShort)
  68. router.HandleFunc("/", handlePostTarget).
  69. HeadersRegexp("Accept", HtmlTypeRegex).
  70. Headers("Content-Type", HtmlType).
  71. Methods("POST").
  72. Name(RoutePostTarget)
  73. router.HandleFunc("/", handleGetRoot).
  74. Methods("GET", "HEAD").
  75. Name(RouteGetRoot)
  76. }
  77. func setupTemplates(configAssetsPath string) {
  78. base, _ := filepath.Abs(configAssetsPath + "/../templates/")
  79. layout := base + "/layout"
  80. funcMap := template.FuncMap{
  81. "asset": URLForAsset,
  82. }
  83. tmpl = template.Must(template.New("kurz").
  84. Funcs(funcMap).
  85. ParseFiles(
  86. base+"/201.gohtml",
  87. base+"/404.gohtml",
  88. base+"/home.gohtml",
  89. layout+"/analytics.gohtml",
  90. layout+"/footer.gohtml",
  91. layout+"/inlinecss.gohtml",
  92. ))
  93. }
  94. func SetupGlobals(c map[string]interface{}) {
  95. // Note: keys in viper are lower-cased.
  96. globals = Globals{
  97. AssetsBaseURL: c["assetsbaseurl"].(string),
  98. AssetsPath: c["assetspath"].(string),
  99. AssetsVersion: c["assetsversion"].(int),
  100. RefreshDelay: c["refreshdelay"].(int),
  101. SiteBaseURL: c["sitebaseurl"].(string),
  102. SiteName: c["sitename"].(string),
  103. }
  104. }
  105. /*
  106. URLFromRoute generates absolute URLs for named routes.
  107. To build URLs for assets, use URLForAsset().
  108. - ns: the assets namespace. One of "js", "css', "images".
  109. - path: the asset path relative to the project root
  110. */
  111. func URLFromRoute(router mux.Router, name string, params map[string]string) string {
  112. return ""
  113. }
  114. /*
  115. URLFromRoute generates absolute URLs for assets.
  116. To build URLs for routes, use URLFromRoute().
  117. - ns: the assets namespace. One of "", "js", "css', "images". "" is only expected
  118. to be used for "favicon.ico".
  119. - path: the asset path relative to the project root
  120. */
  121. func URLForAsset(ns string, assetPath string) (string, error) {
  122. if ns != "" && ns != "css" && ns != "js" && ns != "images" {
  123. return "", errors.New("invalid asset namespace: " + ns)
  124. }
  125. version := globals.AssetsVersion
  126. base, err := url.Parse(globals.AssetsBaseURL)
  127. if err != nil {
  128. panic(err)
  129. }
  130. // Handles "" cleanly, and doesn't use a "\" on windows, unlike filepath.Join.
  131. base.Path = path.Join(base.Path, ns, assetPath)
  132. // No need to url.QueryEscape() since this format is query-clean by construction.
  133. base.RawQuery = "v=" + strconv.Itoa(version)
  134. res := base.String()
  135. return res, nil
  136. }