This is my new blog CMS https://jlelse.blog
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.

64 lines
1.3 KiB

6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
  1. package main
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "strconv"
  8. "github.com/go-chi/chi/v5"
  9. )
  10. func (db *database) shortenPath(p string) (string, error) {
  11. if p == "" {
  12. return "", errors.New("empty path")
  13. }
  14. id := db.getShortPathID(p)
  15. if id == -1 {
  16. _, err := db.exec("insert or ignore into shortpath (path) values (@path)", sql.Named("path", p))
  17. if err != nil {
  18. return "", err
  19. }
  20. id = db.getShortPathID(p)
  21. }
  22. if id == -1 {
  23. return "", errors.New("failed to retrieve short path for " + p)
  24. }
  25. return fmt.Sprintf("/s/%x", id), nil
  26. }
  27. func (db *database) getShortPathID(p string) (id int) {
  28. if p == "" {
  29. return -1
  30. }
  31. row, err := db.queryRow("select id from shortpath where path = @path", sql.Named("path", p))
  32. if err != nil {
  33. return -1
  34. }
  35. err = row.Scan(&id)
  36. if err != nil {
  37. return -1
  38. }
  39. return id
  40. }
  41. func (a *goBlog) redirectToLongPath(rw http.ResponseWriter, r *http.Request) {
  42. id, err := strconv.ParseInt(chi.URLParam(r, "id"), 16, 64)
  43. if err != nil {
  44. a.serve404(rw, r)
  45. return
  46. }
  47. row, err := a.db.queryRow("select path from shortpath where id = @id", sql.Named("id", id))
  48. if err != nil {
  49. a.serve404(rw, r)
  50. return
  51. }
  52. var path string
  53. err = row.Scan(&path)
  54. if err != nil {
  55. a.serve404(rw, r)
  56. return
  57. }
  58. http.Redirect(rw, r, path, http.StatusMovedPermanently)
  59. }