-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdemo.go
63 lines (51 loc) · 1.09 KB
/
demo.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
package main
import (
"encoding/json"
"io/ioutil"
"log"
"mkozhukh/chat/data"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/jinzhu/gorm"
)
var demoDataFolder = "demodata"
func importDemoData(db *gorm.DB) {
var c int
db.Model(&data.User{}).Count(&c)
if c > 0 {
return
}
stat, err := os.Stat(demoDataFolder)
if err != nil || !stat.IsDir() {
return
}
importDemoStruct(db, data.User{})
importDemoStruct(db, data.Message{})
importDemoStruct(db, data.Chat{})
importDemoStruct(db, data.UserChat{})
}
func importDemoStruct(db *gorm.DB, t interface{}) {
dt := reflect.TypeOf(t)
name := strings.ToLower(dt.Name())
cont, err := ioutil.ReadFile(filepath.Join(demoDataFolder, name+".json"))
if err != nil {
return
}
log.Println("[demo-data]", name)
slicePtr := reflect.New(reflect.SliceOf(dt))
slice := slicePtr.Interface()
err = json.Unmarshal(cont, &slice)
if err != nil {
log.Fatal(err)
}
sliceObj := slicePtr.Elem()
for i := 0; i < sliceObj.Len(); i++ {
el := sliceObj.Index(i)
err = db.Save(el.Interface()).Error
if err != nil {
log.Fatal(err)
}
}
}