httpui.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package megauploader
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "html/template"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. rice "github.com/GeertJohan/go.rice"
  11. "github.com/gorilla/mux"
  12. )
  13. //go:generate rice embed-go
  14. // loadTmpl return the required template
  15. // It is provided to centralize handling of templates; it will care about
  16. // riceboxes and other quirks that templates might need
  17. func (mu *MegaUploader) loadTmpl(tmplname string) (*template.Template, error) {
  18. str := rice.MustFindBox("res/templates").MustString(tmplname)
  19. tmpl := template.Must(
  20. template.New(strings.Split(tmplname, ".")[0]).Funcs(template.FuncMap{
  21. "pretty": func(data interface{}) string {
  22. var out bytes.Buffer
  23. enc := json.NewEncoder(&out)
  24. enc.SetIndent("", " ")
  25. err := enc.Encode(data)
  26. if err != nil {
  27. panic(err)
  28. }
  29. return out.String()
  30. },
  31. }).Parse(str),
  32. )
  33. str = rice.MustFindBox("res/templates").MustString("base.html.tmpl")
  34. tmpl = template.Must(tmpl.Parse(str))
  35. return tmpl, nil
  36. }
  37. func (mu *MegaUploader) home(w http.ResponseWriter, r *http.Request) {
  38. tmpl, err := mu.loadTmpl("index.html.tmpl")
  39. if err != nil {
  40. http.Error(w, err.Error(), 500)
  41. return
  42. }
  43. user, _ := getUser(r)
  44. shares := mu.Conf.GetAuthShares(user)
  45. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  46. tmpl.Execute(w, map[string]interface{}{
  47. "Prefix": mu.Conf.Global.RoutePrefix,
  48. "Shares": shares,
  49. })
  50. }
  51. func (mu *MegaUploader) uploadUI(w http.ResponseWriter, r *http.Request) {
  52. user, _ := getUser(r) // user is set: checked by middleware
  53. sharename := mux.Vars(r)["share"]
  54. share, err := mu.Conf.GetAuthShare(sharename, user)
  55. if err != nil {
  56. http.Error(w, fmt.Sprintf("Share '%s' not found", sharename), http.StatusNotFound)
  57. return
  58. }
  59. tmpl, err := mu.loadTmpl("upload.html.tmpl")
  60. if err != nil {
  61. http.Error(w, err.Error(), http.StatusInternalServerError)
  62. return
  63. }
  64. viewurl, err := mu.Conf.GetShareURL(sharename)
  65. if err != nil {
  66. viewurl = url.URL{}
  67. }
  68. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  69. tmpl.Execute(w, map[string]interface{}{
  70. "Prefix": mu.Conf.Global.RoutePrefix,
  71. "Share": share,
  72. "ViewURL": viewurl.String(),
  73. })
  74. }