web.go 4.7 KB

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