-
Notifications
You must be signed in to change notification settings - Fork 1
/
iterfiles.go
70 lines (65 loc) · 1.57 KB
/
iterfiles.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
package main
import (
"encoding/json"
"net/http"
"strconv"
"time"
"github.com/go-sql-driver/mysql"
)
func (t *Tracker) iterFiles(w http.ResponseWriter, r *http.Request) {
var err error
from := uint64(0)
count := uint64(1000)
fromStr := r.FormValue("from")
if fromStr != "" {
from, err = strconv.ParseUint(fromStr, 10, 64)
if err != nil {
http.Error(w, "invalid param: from", http.StatusBadRequest)
return
}
}
countStr := r.FormValue("count")
if countStr != "" {
count, err = strconv.ParseUint(countStr, 10, 64)
if err != nil {
http.Error(w, "invalid param: count", http.StatusBadRequest)
return
}
}
type file struct {
ID int64 `json:"id"`
Key string `json:"key"`
CreatedAt string `json:"created_at"`
}
files := make([]file, 0)
rows, err := t.db.Query("select fid, dkey, created_at from file where fid > ? order by fid limit ?", from, count)
if err != nil {
t.internalServerError("cannot get keys from database", err, r, w)
return
}
defer rows.Close()
for rows.Next() {
var f file
var createdAt mysql.NullTime
err = rows.Scan(&f.ID, &f.Key, &createdAt)
if err != nil {
t.internalServerError("cannot scan row", err, r, w)
return
}
f.CreatedAt = createdAt.Time.Format(time.RFC3339)
files = append(files, f)
}
err = rows.Err()
if err != nil {
t.internalServerError("cannot close rows", err, r, w)
return
}
response := struct {
Files []file `json:"files"`
}{
Files: files,
}
w.Header().Set("content-type", "application/json")
encoder := json.NewEncoder(w)
encoder.Encode(response) // nolint: errcheck
}