httpui.go 2.0 KB

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