-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
177 lines (154 loc) · 4.66 KB
/
main.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/*
Build with: go build -tags=bindatafs
*/
package main
import (
"fmt"
"html/template"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/flowdev/dogs/config/bindatafs"
"github.com/flowdev/dogs/mygorm"
"github.com/flowdev/dogs/myqor"
"github.com/jinzhu/gorm"
"github.com/mattn/go-sqlite3"
)
const generationsForTree = 6
func main() {
workDir := filepath.Dir(os.Args[0])
// Log to log file:
// If the file doesn't exist, create it, or append to the file
f, err := os.OpenFile(filepath.Join(workDir, "DogBreeding.log"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
log.SetOutput(f)
log.Printf("INFO: Dogs app is starting, work dir=%s", workDir)
assetFS := bindatafs.AssetFS
tmplContentAncestors, err := assetFS.Asset("ancestors/index.html.tmpl")
if err != nil {
log.Fatal(err)
}
tmplContentBreedingbook, err := assetFS.Asset("breedingbook/index.html.tmpl")
if err != nil {
log.Fatal(err)
}
tmplContentParentssiblings, err := assetFS.Asset("parentssiblings/index.html.tmpl")
if err != nil {
log.Fatal(err)
}
tmplAncestors := template.Must(template.New("ancestors").Parse(string(tmplContentAncestors)))
tmplBreedingbook := template.Must(template.New("breedingbook").Parse(string(tmplContentBreedingbook)))
tmplParentssiblings := template.Must(template.New("parentssiblings").Parse(string(tmplContentParentssiblings)))
libVersion, _, sourceID := sqlite3.Version()
log.Printf("INFO: sqlite3 libVersion=%s, sourceID:%s", libVersion, sourceID)
db, err := mygorm.Init(filepath.Join(workDir, "DogBreeding.db"))
if err != nil {
log.Fatal(err)
}
db.SetLogger(log.New(f, "\n", 0))
// Initalize QOR Admin
adm, err := myqor.Init(db, assetFS, workDir)
if err != nil {
log.Fatal(err)
}
ln, err := net.Listen("tcp", "127.0.0.1:8001")
if err != nil {
log.Fatal(err)
}
defer ln.Close()
msg := fmt.Sprintf("Listening on http://%s/admin", ln.Addr().String())
log.Print(msg)
fmt.Println(msg)
mux := http.NewServeMux()
mux.HandleFunc("/ancestors/", handleAncestors(tmplAncestors, db))
mux.HandleFunc("/breedingbook/", handleAncestors(tmplBreedingbook, db))
mux.HandleFunc("/parentssiblings/", handleAncestors(tmplParentssiblings, db))
adm.MountTo("/admin", mux)
fmt.Println("Press 'control' + 'c' to stop the server")
log.Fatal(http.Serve(ln, mux))
}
type tmplAncestorsDate struct {
Ancestors []*mygorm.Dog
Quantities []int //Number of times the ancestors appear in the tree
Error error
}
func handleAncestors(tmplAncestors *template.Template, db *gorm.DB,
) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
var id2 int
// The "/ancestors/" pattern matches everything after this, too.
// So we need to check that the ID (and only that) exists.
urlParts := strings.Split(r.URL.Path, "/")
n := len(urlParts)
if n < 3 || n > 4 {
log.Printf("ERROR: Ancestor handler called for illegal path: %s", r.URL.Path)
http.NotFound(w, r)
return
}
id, err := strconv.Atoi(urlParts[2])
if err != nil {
log.Printf("ERROR: Dog ID '%s' isn't a valid integer: %v", urlParts[2], err)
http.NotFound(w, r)
return
}
if n > 3 {
id2, err = strconv.Atoi(urlParts[3])
if err != nil {
log.Printf("ERROR: Dog ID (2) '%s' isn't a valid integer: %v", urlParts[3], err)
http.NotFound(w, r)
return
}
} else {
id2 = -1
}
err = tmplAncestors.Execute(w, generateAncestorTable(id, id2, db)) // no own transaction (read only)
if err != nil {
log.Printf("ERROR: Unable to execute ancestor template for ID '%d': %v", id, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func generateAncestorTable(id, id2 int, tx *gorm.DB) tmplAncestorsDate {
var ancestors []*mygorm.Dog
var err error
if id2 < 0 {
ancestors, err = mygorm.FindAncestorsForID(tx, id, generationsForTree)
} else {
d := &mygorm.Dog{
FatherID: uint(id2),
MotherID: uint(id),
Name: "Puppy",
}
alc, err2 := mygorm.ComputeALC(tx, d)
if err2 != nil {
log.Printf("ERROR: Unable to calculate the ALC for Puppy of %d and %d: %v", id, id2, err2)
} else {
d.ALC = mygorm.Percentage(alc)
}
ancestors, err = mygorm.FindAncestorsForDog(tx, d, generationsForTree)
}
quantities := calculateQuantities(ancestors)
return tmplAncestorsDate{
Ancestors: ancestors,
Quantities: quantities,
Error: err,
}
}
func calculateQuantities(ancestors []*mygorm.Dog) []int {
tmpDogCount := make(map[uint]int, len(ancestors))
for _, dog := range ancestors {
tmpDogCount[dog.ID]++
}
quantities := make([]int, len(ancestors))
for i, dog := range ancestors {
quantities[i] = tmpDogCount[dog.ID]
}
return quantities
}