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