a simple url shortener in Go (check it out at qurl.org)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
2.1 KiB

4 months ago
2 years ago
2 years ago
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
  1. package pages
  2. import (
  3. "fmt"
  4. "git.binarythought.com/cdramey/qurl/assets"
  5. "git.binarythought.com/cdramey/qurl/obj"
  6. "git.binarythought.com/cdramey/qurl/storage"
  7. "html/template"
  8. "net/http"
  9. )
  10. type RootHandler struct {
  11. Storage storage.Storage
  12. index *assets.StaticContent
  13. css *assets.StaticContent
  14. favi *assets.StaticContent
  15. usage *assets.StaticContent
  16. submit *template.Template
  17. }
  18. func (ctx *RootHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  19. fname := r.URL.Path
  20. switch fname {
  21. case "/index.html":
  22. fallthrough
  23. case "/":
  24. ctx.index.ServeHTTP(w, r)
  25. case "/submit.html":
  26. ctx.ServeSubmit(w, r)
  27. case "/qurl.css":
  28. ctx.css.ServeHTTP(w, r)
  29. case "/favicon.ico":
  30. ctx.favi.ServeHTTP(w, r)
  31. case "/api/usage.html":
  32. ctx.usage.ServeHTTP(w, r)
  33. case "/api/url":
  34. ctx.ServeAPI(w, r)
  35. default:
  36. id, err := obj.FromString(fname[1:len(fname)])
  37. if err != nil {
  38. http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
  39. return
  40. }
  41. q, err := ctx.Storage.GetQURLByID(id)
  42. if err != nil {
  43. http.Error(w, fmt.Sprintf("Database error: %s", err.Error()),
  44. http.StatusInternalServerError)
  45. return
  46. }
  47. if q == nil {
  48. http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
  49. return
  50. }
  51. http.Redirect(w, r, q.URL, http.StatusPermanentRedirect)
  52. }
  53. }
  54. func (ctx *RootHandler) Init() error {
  55. var err error
  56. // Initialize the static content object for the index page
  57. ctx.index, err = assets.NewStaticContent("index.html", "text/html")
  58. if err != nil {
  59. return err
  60. }
  61. // Initialize the static content object for the css
  62. ctx.css, err = assets.NewStaticContent("qurl.css", "text/css")
  63. if err != nil {
  64. return err
  65. }
  66. // Initialize the static content object favicon
  67. ctx.favi, err = assets.NewStaticContent("favicon.ico", "image/x-icon")
  68. if err != nil {
  69. return err
  70. }
  71. ctx.usage, err = assets.NewStaticContent("usage.html", "text/html")
  72. if err != nil {
  73. return err
  74. }
  75. // Initialize submit page template
  76. data, err := assets.ReadFile("submit.html")
  77. if err != nil {
  78. return err
  79. }
  80. ctx.submit = template.New("submit.html")
  81. _, err = ctx.submit.Parse(string(data))
  82. if err != nil {
  83. return err
  84. }
  85. return nil
  86. }