-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdao.go
86 lines (73 loc) · 1.84 KB
/
dao.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright 2017 <CompanyName>, Inc. All Rights Reserved.
package hashgen
import (
"bytes"
"encoding/json"
"log"
"os"
"os/exec"
"sync"
)
// No database drivers are included in the Go standard library.
// Data access used in lieu of a database.
// Appends crypto hash data to file.
type UserAccountFile struct {
sync.RWMutex
filename string
}
func New(filename string) *UserAccountFile {
return &UserAccountFile{sync.RWMutex{}, filename}
}
func (f *UserAccountFile) Append(value interface{}) {
if f == nil {
return
}
// Background file operation
go func() {
b, err := json.Marshal(value)
if err != nil {
log.Fatal(err)
}
f.Lock()
defer f.Unlock()
ofile, err := os.OpenFile(f.filename, os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
if os.IsNotExist(err) {
_, err = os.Create(f.filename)
if err != nil {
log.Fatalf("Failed to create/open %s", f.filename)
}
}
ofile, err = os.OpenFile(f.filename, os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
}
if _, err := ofile.WriteString(string(b) + "\n"); err != nil {
log.Fatal(err)
}
// Don't defer writes due to possible os caching
if err := ofile.Close(); err != nil {
log.Fatal(err)
}
}()
}
func (f *UserAccountFile) Get(uuid string) (record []byte, ok bool) {
// Without an indexed database, finding any given uuid is a runtime concern.
// We could use an elaborate sorted data file plus binary search, but this
// is a toy application. Try the simplest thing that can work: grep!
if _, err := os.Stat(f.filename); os.IsNotExist(err) {
// No file, so not found
return []byte(""), false
}
cmd := exec.Command("grep", uuid, f.filename)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
return []byte(""), false
}
result := out.String()
log.Println(result)
return []byte(result), true
}