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.

103 lines
2.0 KiB

  1. package pages
  2. import (
  3. "fmt"
  4. "html/template"
  5. "net/http"
  6. "qurl/static"
  7. "qurl/storage"
  8. "qurl/qurl"
  9. )
  10. type RootHandler struct {
  11. Storage storage.Storage
  12. index *static.StaticContent
  13. css *static.StaticContent
  14. favi *static.StaticContent
  15. usage *static.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 := qurl.FromString(fname[1:len(fname)])
  37. if err != nil {
  38. http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
  39. }
  40. q, err := ctx.Storage.GetQURLByID(id)
  41. if err != nil {
  42. http.Error(w, fmt.Sprintf("Database error: %s", err.Error()),
  43. http.StatusInternalServerError)
  44. return
  45. }
  46. http.Redirect(w, r, q.URL, http.StatusPermanentRedirect)
  47. }
  48. }
  49. func (ctx *RootHandler) Init() error {
  50. // Initialize the static content object for the index page
  51. index := &static.StaticContent{Content: "index.html"}
  52. err := index.Init()
  53. if err != nil {
  54. return err
  55. }
  56. ctx.index = index
  57. // Initialize the static content object for the css
  58. css := &static.StaticContent{Content: "qurl.css"}
  59. err = css.Init()
  60. if err != nil {
  61. return err
  62. }
  63. ctx.css = css
  64. // Initialize the static content object favicon
  65. favi := &static.StaticContent{Content: "favicon.ico"}
  66. err = favi.Init()
  67. if err != nil {
  68. return err
  69. }
  70. ctx.favi = favi
  71. // Initialize the api usage instructions
  72. usage := &static.StaticContent{Content: "usage.html"}
  73. err = usage.Init()
  74. if err != nil {
  75. return err
  76. }
  77. ctx.usage = usage
  78. // Initialize submit page template
  79. ctx.submit = template.New("submit.html")
  80. _, err = ctx.submit.Parse(string(static.Assets["submit.html"]))
  81. if err != nil {
  82. return err
  83. }
  84. return nil
  85. }