-
Notifications
You must be signed in to change notification settings - Fork 4
/
web.go
119 lines (103 loc) · 2.31 KB
/
web.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
package main
import (
"encoding/json"
"github.com/gin-gonic/gin"
"github.com/syndtr/goleveldb/leveldb"
"log"
"net/http"
"strings"
"time"
)
func RunListening(db *leveldb.DB) {
router := gin.New()
router.Use(gin.Recovery())
router.LoadHTMLGlob("/web/*.html")
router.Static("/css", "/web/css")
router.Static("/js", "/web/js")
router.StaticFile("/", "/web/index.html") //前端接口
var h = Handler{
db: db,
}
router.GET("/interface", h.list)
router.GET("/refresh", h.refresh)
router.Run(":8080")
}
type Handler struct {
db *leveldb.DB
cache *[]model
}
type Search struct {
Name string `form:"name"`
Offset int `form:"offset" binding:"required,min=1"`
Limit int `form:"limit" binding:"required,min=10"`
}
func (h Handler) list(ctx *gin.Context) {
var search Search
if err := ctx.ShouldBindQuery(&search); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"msg": err.Error(),
})
return
}
if h.cache == nil {
h.load()
}
cache := *h.cache
// filter by name
if len(search.Name) > 0 {
var tmp []model
for i, _ := range cache {
if strings.Contains(cache[i].RequestURL, search.Name) {
tmp = append(tmp, cache[i])
}
}
cache = tmp
}
left := (search.Offset - 1) * search.Limit
right := search.Offset * search.Limit
if left >= len(cache) {
ctx.JSON(http.StatusOK, gin.H{
"msg": "no data",
})
return
}
if right > len(cache) {
ctx.JSON(http.StatusOK, gin.H{
"data": cache[left:],
"total": len(cache),
})
return
}
ctx.JSON(http.StatusOK, gin.H{
"data": cache[left:right],
"total": len(cache),
})
return
}
func (h Handler) refresh(ctx *gin.Context) {
stat := time.Now()
h.load()
log.Printf("[PRISM] load data success %fs", time.Since(stat).Seconds())
ctx.JSON(http.StatusOK, gin.H{
"msg": "success",
})
return
}
func (h *Handler) load() {
var ret []model
iter := h.db.NewIterator(nil, nil)
for iter.Next() {
// Remember that the contents of the returned slice should not be modified, and only valid until the next call to Next.
value := iter.Value()
md := model{}
if err := json.Unmarshal(value, &md); err != nil {
log.Printf("[PRISM] json unmarshal error (%s)", err.Error())
}
ret = append(ret, md)
}
iter.Release()
if err := iter.Error(); err != nil {
log.Printf("[PRISM] iter error (%s)", err.Error())
}
h.cache = &ret
}