strategy.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. The "strategy" package in Kurz provides the aliasing strategies.
  3. Files
  4. - strategy.go contains the interface and base implementation
  5. - strategies.go contains the strategy instances and utilities
  6. - manual.go contains the "manual" strategy
  7. - hexrcr32.go contains the "hexcrc32" strategy
  8. */
  9. package strategy
  10. import (
  11. "github.com/FGM/kurz/storage"
  12. "github.com/FGM/kurz/url"
  13. "log"
  14. "time"
  15. )
  16. /*
  17. AliasingStrategy defines the operations provided by the various aliasing implementations:
  18. The options parameter for Alias() MAY be used by some strategies, in which case they
  19. have to define their expectations about it.
  20. */
  21. type AliasingStrategy interface {
  22. Name() string // Return the name of the strategy object
  23. Alias(url url.LongUrl, s storage.Storage, options ...interface{}) (url.ShortUrl, error) // Return the short URL (alias) for a given long (source) URL
  24. UseCount(storage storage.Storage) int // Return the number of short URLs (aliases) using this strategy.
  25. }
  26. type baseStrategy struct{}
  27. func (y baseStrategy) Name() string {
  28. return "base"
  29. }
  30. func (y baseStrategy) Alias(long url.LongUrl, s storage.Storage, options ...interface{}) (url.ShortUrl, error) {
  31. var short url.ShortUrl
  32. var err error
  33. /** TODO
  34. * - validate alias is available
  35. */
  36. short = url.ShortUrl{
  37. Value: long.Value,
  38. ShortFor: long,
  39. Domain: long.Domain(),
  40. Strategy: y.Name(),
  41. SubmittedBy: storage.CurrentUser(),
  42. SubmittedOn: time.Now().UTC().Unix(),
  43. IsEnabled: true,
  44. }
  45. sql := `
  46. INSERT INTO shorturl(url, domain, strategy, submittedBy, submittedInfo, isEnabled)
  47. VALUES (?, ?, ?, ?, ?, ?)
  48. `
  49. result, err := s.DB.Exec(sql, short.Value, short.Domain, short.Strategy, short.SubmittedBy.Id, short.SubmittedOn, short.IsEnabled)
  50. if err != nil {
  51. log.Printf("Failed inserting %s: %#V", short.Value, err)
  52. } else {
  53. short.Id, _ = result.LastInsertId()
  54. }
  55. return short, err
  56. }
  57. /**
  58. Any nonzero result is likely an error.
  59. */
  60. func (y baseStrategy) UseCount(s storage.Storage) int {
  61. sql := `
  62. SELECT COUNT(*)
  63. FROM shorturl
  64. WHERE strategy = ?
  65. `
  66. var count int
  67. err := s.DB.QueryRow(sql, y.Name()).Scan(&count)
  68. if err != nil {
  69. count = 0
  70. log.Printf("Failed querying database for base strategy use count: %v\n", err)
  71. }
  72. return count
  73. }