web.go 5.1 KB

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