web.go 3.8 KB

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