strategy.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. "errors"
  12. "github.com/FGM/kurz/storage"
  13. "github.com/FGM/kurz/url"
  14. "log"
  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, 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, options ...interface{}) (url.ShortUrl, error) {
  31. var ret url.ShortUrl
  32. var err error = errors.New("Base strategy is abstract")
  33. return ret, err
  34. }
  35. /**
  36. Any nonzero result is likely an error.
  37. */
  38. func (y baseStrategy) UseCount(s storage.Storage) int {
  39. sql := `
  40. SELECT COUNT(*)
  41. FROM shorturl
  42. WHERE strategy = ?
  43. `
  44. var count int
  45. err := s.DB.QueryRow(sql, y.Name()).Scan(&count)
  46. if err != nil {
  47. count = 0
  48. log.Printf("Failed querying database for base strategy use count: %v\n", err)
  49. }
  50. return count
  51. }