/
api.go
59 lines (46 loc) · 1.18 KB
/
api.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
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/semihalev/log"
"gopkg.in/gin-contrib/cors.v1"
)
func existsBlock(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"exists": blockCache.Exists(c.Param("key"))})
}
func getBlock(c *gin.Context) {
if ok, _ := blockCache.Get(c.Param("key")); !ok {
c.JSON(http.StatusNotFound, gin.H{"error": c.Param("key") + " not found"})
} else {
c.JSON(http.StatusOK, gin.H{"success": ok})
}
}
func removeBlock(c *gin.Context) {
blockCache.Remove(c.Param("key"))
c.JSON(http.StatusOK, gin.H{"success": true})
}
func setBlock(c *gin.Context) {
blockCache.Set(c.Param("key"), true)
c.JSON(http.StatusOK, gin.H{"success": true})
}
// StartAPIServer launches the API server
func StartAPIServer(addr string) error {
if addr == "" {
return nil
}
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
r.Use(cors.Default())
block := r.Group("/api/v1/block")
{
block.GET("/exists/:key", existsBlock)
block.GET("/get/:key", getBlock)
block.GET("/remove/:key", removeBlock)
block.GET("/set/:key", setBlock)
}
if err := r.Run(addr); err != nil {
return err
}
log.Info("API server listening on", "addr", addr)
return nil
}