memory.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package infrastructure
  2. import (
  3. "code.osinet.fr/fgm/kurz/domain"
  4. )
  5. type urlmap map[domain.URL]domain.URL
  6. var shortRepo = MemoryShortURLRepository{make(urlmap)}
  7. var targetRepo = MemoryTargetURLRepository{make(urlmap)}
  8. type MemoryShortURLRepository struct {
  9. targets urlmap
  10. }
  11. type MemoryTargetURLRepository struct {
  12. shorts urlmap
  13. }
  14. func (sr MemoryShortURLRepository) GetTarget(su domain.ShortURL) (domain.TargetURL, error) {
  15. var tu domain.TargetURL
  16. var err error
  17. if t, ok := sr.targets[su.URL]; ok {
  18. tu = domain.TargetURL{URL: t}
  19. } else {
  20. err = domain.MakeError(domain.ShortNotFound, "")
  21. }
  22. return tu, err
  23. }
  24. func (tr MemoryTargetURLRepository) GetShort(tu domain.TargetURL) (su domain.ShortURL, isNew bool, err error) {
  25. // If short exists, just return it.
  26. if s, ok := tr.shorts[tu.URL]; ok {
  27. su = domain.ShortURL{URL: s}
  28. return su, false, err
  29. }
  30. // If it doesn't exist, attempt to create it.
  31. su, err = domain.NewUnspecifiedShortURL(tu)
  32. if err != nil {
  33. // Creation failed.
  34. return su, false, err
  35. }
  36. tr.shorts[tu.URL] = su.URL
  37. shortRepo.targets[su.URL] = tu.URL
  38. return su, true, err
  39. }