Initial Store implementation

This commit is contained in:
Ian Gulliver
2022-03-15 04:43:03 +00:00
parent 53511b9da7
commit 4a22289ae2
6 changed files with 125 additions and 2 deletions

3
.gitignore vendored
View File

@@ -11,5 +11,4 @@
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
foo/

5
go.mod Normal file
View File

@@ -0,0 +1,5 @@
module github.com/firestuff/checky
go 1.16
require github.com/google/uuid v1.3.0

2
go.sum Normal file
View File

@@ -0,0 +1,2 @@
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=

24
main.go Normal file
View File

@@ -0,0 +1,24 @@
package main
import "fmt"
import "github.com/google/uuid"
func main() {
store := NewStore("foo")
out := &Template{
Id: uuid.NewString(),
Test: "round trip",
}
store.Write(out)
in := &Template{
Id: out.Id,
}
store.Read(in)
fmt.Printf("%+v\n", in)
}

79
store.go Normal file
View File

@@ -0,0 +1,79 @@
package main
import "encoding/hex"
import "encoding/json"
import "fmt"
import "os"
import "path/filepath"
type Storable interface {
GetType() string
GetId() string
}
type Store struct {
root string
}
func NewStore(root string) *Store {
return &Store{
root: root,
}
}
func (s *Store) Write(obj Storable) error {
dir := filepath.Join(s.root, obj.GetType())
filename := hex.EncodeToString([]byte(obj.GetId()))
err := os.MkdirAll(dir, 0700)
if err != nil {
return err
}
tmp, err := os.CreateTemp(dir, fmt.Sprintf("%s.*", filename))
if err != nil {
return err
}
defer tmp.Close()
enc := json.NewEncoder(tmp)
enc.SetEscapeHTML(false)
err = enc.Encode(obj)
if err != nil {
return err
}
err = tmp.Close()
if err != nil {
return err
}
err = os.Rename(tmp.Name(), filepath.Join(dir, filename))
if err != nil {
return err
}
return nil
}
func (s *Store) Read(obj Storable) error {
dir := filepath.Join(s.root, obj.GetType())
filename := hex.EncodeToString([]byte(obj.GetId()))
fh, err := os.Open(filepath.Join(dir, filename))
if err != nil {
return err
}
defer fh.Close()
dec := json.NewDecoder(fh)
dec.DisallowUnknownFields()
err = dec.Decode(obj)
if err != nil {
return err
}
return nil
}

14
template.go Normal file
View File

@@ -0,0 +1,14 @@
package main
type Template struct {
Id string
Test string
}
func (t *Template) GetType() string {
return "template"
}
func (t *Template) GetId() string {
return t.Id
}