Created
July 4, 2014 23:55
-
-
Save kelseyhightower/b739edf36bbd068db55d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"fmt" | |
"path/filepath" | |
) | |
type Node struct { | |
Key string | |
Value string | |
} | |
type Nodes []*Node | |
func (ns Nodes) Len() int { | |
return len(ns) | |
} | |
func (ns Nodes) Less(i, j int) bool { | |
return ns[i].Key < ns[j].Key | |
} | |
func (ns Nodes) Swap(i, j int) { | |
ns[i], ns[j] = ns[j], ns[i] | |
} | |
type Store map[string]Node | |
func (s Store) Get(key string) (Node, bool) { | |
n, ok := s[key] | |
return n, ok | |
} | |
func (s Store) GetAll(pattern string) (Nodes, error) { | |
ns := make(Nodes, 0) | |
for _, n := range s { | |
m, err := filepath.Match(pattern, n.Key) | |
if err != nil { | |
return nil, err | |
} | |
if m { | |
ns = append(ns, &n) | |
} | |
} | |
return ns, nil | |
} | |
func (s Store) Set(key string, value string) { | |
s[key] = Node{key, value} | |
} | |
func main() { | |
s := Store{} | |
s.Set("/myapp/database/username", "admin") | |
s.Set("/myapp/database/password", "123456789") | |
n, ok := s.Get("/myapp/database/password") | |
if ok { | |
fmt.Println(n.Value) | |
} | |
nodes, err := s.GetAll("/myapp/*/*") | |
if err != nil { | |
log.Fatal(err.Error()) | |
} | |
for _, n := range nodes { | |
fmt.Println(n.Key) | |
fmt.Println(n.Value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment