store.go 745 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package main
  2. import "sync"
  3. type URLStore struct {
  4. urls map[string]string
  5. mu sync.RWMutex
  6. }
  7. func NewURLStore() *URLStore {
  8. return &URLStore{urls: make(map[string]string)}
  9. }
  10. func (s *URLStore) Get(key string) string {
  11. s.mu.RLock()
  12. defer s.mu.RUnlock()
  13. return s.urls[key]
  14. }
  15. func (s *URLStore) Set(key, url string) bool {
  16. s.mu.Lock()
  17. defer s.mu.Unlock()
  18. if _, present := s.urls[key]; present {
  19. return false
  20. }
  21. s.urls[key] = url
  22. return true
  23. }
  24. func (s *URLStore) Count() int {
  25. s.mu.RLock()
  26. defer s.mu.RUnlock()
  27. return len(s.urls)
  28. }
  29. func (s *URLStore) Put(url string) string {
  30. for {
  31. key := genKey(s.Count()) // generate the short URL
  32. if ok := s.Set(key, url); ok {
  33. return key
  34. }
  35. }
  36. // shouldn't get here
  37. return ""
  38. }