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.

93 lines
2.0 KiB

4 years ago
4 years ago
  1. package pages
  2. import (
  3. "fmt"
  4. "git.binarythought.com/cdramey/qurl/obj"
  5. "git.binarythought.com/cdramey/qurl/static"
  6. "git.binarythought.com/cdramey/qurl/storage"
  7. "html/template"
  8. "net/http"
  9. )
  10. type RootHandler struct {
  11. Storage storage.Storage
  12. index *StaticContent
  13. css *StaticContent
  14. favi *StaticContent
  15. usage *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. // Initialize the static content object for the index page
  56. ctx.index = &StaticContent{Type: "text/html", Content: static.Index_html}
  57. ctx.index.Init()
  58. // Initialize the static content object for the css
  59. ctx.css = &StaticContent{Type: "text/css", Content: static.Qurl_css}
  60. ctx.css.Init()
  61. // Initialize the static content object favicon
  62. ctx.favi = &StaticContent{Type: "image/x-icon", Content: static.Favicon_ico}
  63. ctx.favi.Init()
  64. // Initialize the api usage instructions
  65. ctx.usage = &StaticContent{Type: "text/html", Content: static.Usage_html}
  66. ctx.usage.Init()
  67. // Initialize submit page template
  68. ctx.submit = template.New("submit.html")
  69. _, err := ctx.submit.Parse(string(static.Submit_html))
  70. if err != nil {
  71. return err
  72. }
  73. return nil
  74. }