-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest.go
80 lines (64 loc) · 1.59 KB
/
rest.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
package main
import (
"encoding/json"
"time"
"github.com/gin-gonic/gin"
)
func init() {
gin.SetMode("release")
}
func getBenchmarks(c *gin.Context) {
var benchmarks []benchmark
kvPairs := make(chan kvPair, 10)
go iter(kvPairs)
for p := range kvPairs {
var b benchmark
if err := json.Unmarshal(p.value, &b); err != nil {
c.IndentedJSON(500, gin.H{"message": err.Error()})
return
}
b.ID = p.key
benchmarks = append(benchmarks, b)
}
c.IndentedJSON(200, benchmarks)
}
func addBenchmark(c *gin.Context) {
var b benchmark
if err := c.BindJSON(&b); err != nil {
c.IndentedJSON(400, gin.H{"message": err.Error()})
return
}
if b.Timestamp == 0 {
b.Timestamp = time.Now().UnixNano()
}
value, _ := json.Marshal(b) // Ignoring errors because they are not really possible
if err := put(b.ID, value); err != nil {
c.IndentedJSON(500, gin.H{"message": err.Error()})
return
}
c.IndentedJSON(201, gin.H{"message": "ok"})
}
func deleteBenchmark(c *gin.Context) {
var payload struct {
ID uint64 `json:"id"`
}
if err := c.BindJSON(&payload); err != nil {
c.IndentedJSON(400, gin.H{"message": err.Error()})
return
}
if err := del(payload.ID); err != nil {
c.IndentedJSON(500, gin.H{"message": err.Error()})
return
}
c.IndentedJSON(200, gin.H{"message": "ok"})
}
func httpEngine() *gin.Engine {
router := gin.Default()
router.StaticFile("/", "./static/index.html")
router.Static("/static", "./static")
v1 := router.Group("/api/v1")
v1.GET("benchmarks", getBenchmarks)
v1.POST("benchmarks", addBenchmark)
v1.DELETE("benchmarks", deleteBenchmark)
return router
}