-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
226 lines (180 loc) · 4.82 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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package main
import (
"context"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/lonnng/nex"
"github.com/gorilla/mux"
)
var ErrInvalidParameter = errors.New("invalid parameter")
var token = "123456"
// save clues
var db = struct{ clues []ClueInfo }{}
func logMiddleware(ctx context.Context, r *http.Request) (context.Context, error) {
fmt.Printf("Method=%s, RemoteAddr=%s, URL=%s\n", r.Method, r.RemoteAddr, r.URL.String())
return ctx, nil
}
func startTimeMiddleware(ctx context.Context, _ *http.Request) (context.Context, error) {
return context.WithValue(ctx, "startTime", time.Now().UnixNano()), nil
}
func endTimeMiddleware(ctx context.Context, _ http.ResponseWriter) (context.Context, error) {
start := ctx.Value("startTime").(int64)
end := time.Now().UnixNano()
duration := end - start
fmt.Printf("request duration: start=%d, end=%d, duration=%d\n", start, end, duration)
return ctx, nil
}
func main() {
nex.SetErrorEncoder(func(err error) interface{} {
return &ErrorMessage{
Code: -1000,
Error: err.Error(),
}
})
// global middleware
nex.Before(logMiddleware, startTimeMiddleware)
nex.After(endTimeMiddleware)
r := mux.NewRouter()
r.Handle("/clues", nex.Handler(createClue)).Methods("POST")
r.Handle("/clues", nex.Handler(clueList)).Methods("GET")
r.Handle("/clues2", nex.Handler(clueList2)).Methods("GET")
r.Handle("/clues/{id}", nex.Handler(clueInfo)).Methods("GET")
r.Handle("/clues/{id}", nex.Handler(updateClue)).Methods("PUT")
r.Handle("/clues/{id}", nex.Handler(deleteClue)).Methods("DELETE")
r.Handle("/blob", nex.Handler(uploadFile)).Methods("POST")
if err := http.ListenAndServe(":8080", r); err != nil {
panic(err)
}
}
func createClue(c *ClueInfo) (*StringMessage, error) {
title := strings.TrimSpace(c.Title)
number := strings.TrimSpace(c.Number)
if title == "" || number == "" {
return nil, errors.New("title and number can not empty")
}
db.clues = append(db.clues, *c)
return SuccessResponse, nil
}
func clueList(query nex.Form) (*ClueListResponse, error) {
s := query.Get("start")
c := query.Get("count")
var start, count int
var err error
if s == "" {
start = 0
} else {
start, err = strconv.Atoi(s)
if err != nil {
return nil, err
}
}
if c == "" {
count = len(db.clues)
} else {
count, err = strconv.Atoi(c)
if err != nil {
return nil, err
}
}
return &ClueListResponse{Data: db.clues[start : start+count]}, nil
}
// 与clueList函数功能相同, 使用query辅助函数
func clueList2(query nex.Form) (*ClueListResponse, error) {
start := query.IntOrDefault("start", 0)
count := query.IntOrDefault("count", len(db.clues))
return &ClueListResponse{Data: db.clues[start: start+count]}, nil
}
// util function
func parseID(r *http.Request) (int, error) {
vars := mux.Vars(r)
if strings.TrimSpace(vars["id"]) == "" {
return 0, ErrInvalidParameter
}
id, err := strconv.Atoi(strings.TrimSpace(vars["id"]))
if err != nil {
return 0, err
}
if len(db.clues) <= id-1 {
return 0, errors.New("can not found clue information")
}
return id, nil
}
func clueInfo(r *http.Request) (*ClueInfoResponse, error) {
id, err := parseID(r)
if err != nil {
return nil, err
}
return &ClueInfoResponse{Data: &db.clues[id-1]}, nil
}
func updateClue(r *http.Request, c *ClueInfo) (*StringMessage, error) {
id, err := parseID(r)
if err != nil {
return nil, err
}
title := strings.TrimSpace(c.Title)
number := strings.TrimSpace(c.Number)
if title == "" || number == "" {
return nil, errors.New("title and number can not empty")
}
db.clues[id] = *c
return SuccessResponse, nil
}
func deleteClue(h http.Header, r *http.Request) (*StringMessage, error) {
t := h.Get("Authorization")
if t != token {
return nil, errors.New("permission denied")
}
id, err := parseID(r)
if err != nil {
return nil, err
}
db.clues = append(db.clues[:id], db.clues[id:]...)
return SuccessResponse, nil
}
func uploadFile(form *multipart.Form) (*BlobResponse, error) {
uploaded, ok := form.File["uploadfile"]
if !ok {
return nil, errors.New("can not found `uploadfile` field")
}
localName := func(filename string) string {
ext := filepath.Ext(filename)
id := time.Now().Format("20060102150405.999999999")
return id + ext
}
var fds []io.Closer
defer func() {
for _, fd := range fds {
fd.Close()
}
}()
files := make(map[string]string)
for _, fh := range uploaded {
fileName := localName(fh.Filename)
files[fh.Filename] = fileName
// upload file
uf, err := fh.Open()
fds = append(fds, uf)
if err != nil {
return nil, err
}
// local file
lf, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, 0660)
fds = append(fds, lf)
if err != nil {
return nil, err
}
_, err = io.Copy(lf, uf)
if err != nil {
return nil, err
}
}
return &BlobResponse{Data: files}, nil
}