David K. Bainbridge | f0da873 | 2016-06-01 16:15:37 -0700 | [diff] [blame] | 1 | package main |
| 2 | |
David K. Bainbridge | 546cdc3 | 2016-06-29 15:30:22 -0700 | [diff] [blame] | 3 | import ( |
| 4 | "fmt" |
| 5 | "net/url" |
| 6 | "strings" |
| 7 | ) |
| 8 | |
David K. Bainbridge | f0da873 | 2016-06-01 16:15:37 -0700 | [diff] [blame] | 9 | type Storage interface { |
| 10 | Put(id string, update StatusMsg) error |
| 11 | Get(id string) (*StatusMsg, error) |
David K. Bainbridge | 068e87d | 2016-06-30 13:53:19 -0700 | [diff] [blame] | 12 | Delete(id string) error |
David K. Bainbridge | f0da873 | 2016-06-01 16:15:37 -0700 | [diff] [blame] | 13 | List() ([]StatusMsg, error) |
| 14 | } |
| 15 | |
David K. Bainbridge | 546cdc3 | 2016-06-29 15:30:22 -0700 | [diff] [blame] | 16 | func NewStorage(spec string) (Storage, error) { |
| 17 | conn, err := url.Parse(spec) |
| 18 | if err != nil { |
| 19 | return nil, err |
| 20 | } |
| 21 | |
| 22 | switch strings.ToUpper(conn.Scheme) { |
| 23 | case "MEMORY": |
| 24 | return NewMemoryStorage(), nil |
| 25 | case "CONSUL": |
| 26 | return NewConsulStorage(spec) |
| 27 | default: |
| 28 | return nil, fmt.Errorf("Unknown storage scheme specified, '%s'", conn.Scheme) |
| 29 | } |
| 30 | } |
| 31 | |
David K. Bainbridge | f0da873 | 2016-06-01 16:15:37 -0700 | [diff] [blame] | 32 | type MemoryStorage struct { |
| 33 | Data map[string]StatusMsg |
| 34 | } |
| 35 | |
| 36 | func NewMemoryStorage() *MemoryStorage { |
| 37 | return &MemoryStorage{ |
| 38 | Data: make(map[string]StatusMsg), |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | func (s *MemoryStorage) Put(id string, update StatusMsg) error { |
| 43 | s.Data[id] = update |
David K. Bainbridge | f0da873 | 2016-06-01 16:15:37 -0700 | [diff] [blame] | 44 | return nil |
| 45 | } |
| 46 | |
| 47 | func (s *MemoryStorage) Get(id string) (*StatusMsg, error) { |
| 48 | m, ok := s.Data[id] |
| 49 | if !ok { |
| 50 | return nil, nil |
| 51 | } |
| 52 | return &m, nil |
| 53 | } |
| 54 | |
David K. Bainbridge | 068e87d | 2016-06-30 13:53:19 -0700 | [diff] [blame] | 55 | func (s *MemoryStorage) Delete(id string) error { |
| 56 | delete(s.Data, id) |
| 57 | return nil |
| 58 | } |
| 59 | |
David K. Bainbridge | f0da873 | 2016-06-01 16:15:37 -0700 | [diff] [blame] | 60 | func (s *MemoryStorage) List() ([]StatusMsg, error) { |
| 61 | r := make([]StatusMsg, len(s.Data)) |
| 62 | i := 0 |
| 63 | for _, v := range s.Data { |
| 64 | r[i] = v |
David K. Bainbridge | 97ee805 | 2016-06-14 00:52:07 -0700 | [diff] [blame] | 65 | i += 1 |
David K. Bainbridge | f0da873 | 2016-06-01 16:15:37 -0700 | [diff] [blame] | 66 | } |
| 67 | return r, nil |
| 68 | } |