-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathimport.go
94 lines (85 loc) · 1.83 KB
/
import.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
package main
import (
"encoding/csv"
"fmt"
"io"
"net/http"
"strings"
"github.com/jinzhu/gorm"
)
func (h Handler) importPage(w http.ResponseWriter, r *http.Request) {
page := make(map[string]interface{})
page["authorities"] = Authorities
page["message"] = r.Context().Value(KeyMessage)
h.HTML(w, r, "import.htm", page)
}
// Handle the upload file request
func (h Handler) importHandler(w http.ResponseWriter, r *http.Request) {
file, header, err := r.FormFile("file")
if err != nil {
r = addMessage(r, err.Error())
h.importPage(w, r)
return
}
if !strings.HasSuffix(header.Filename, ".csv") {
r = addMessage(r, "請上傳 CSV 檔案")
h.importPage(w, r)
return
}
n, err := importAccounts(
h.db,
file,
r.FormValue("authority"),
)
if err != nil {
r = addMessage(r, err.Error())
h.importPage(w, r)
return
}
r = addMessage(r, fmt.Sprintf("成功匯入%d筆資料", n))
h.importPage(w, r)
}
func importAccounts(db *gorm.DB, r io.Reader, authroity string) (n int, err error) {
reader := csv.NewReader(r)
index, _ := reader.Read() // ignore column name
for {
row, err := reader.Read()
if err == io.EOF {
break
}
columns := parseColumns(index, row)
columns["authority"] = authroity
added, err := createAccount(db, columns)
if err != nil {
return n, err
}
if added {
n++
}
}
return n, nil
}
func parseColumns(index, row []string) (columns map[string]string) {
columns = make(map[string]string)
for i, v := range index {
if len(row) > i {
columns[v] = row[i]
}
}
return
}
func createAccount(db *gorm.DB, columns map[string]string) (_ bool, err error) {
_, err = NewAccount(
db,
columns["id"],
columns["name"],
columns["password"],
columns["class"],
columns["number"],
columns["authority"],
)
if err == AccountAlreadyExist {
return false, nil
}
return true, err
}