-
Notifications
You must be signed in to change notification settings - Fork 35
/
api.go
102 lines (89 loc) · 2.66 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
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
package api
import (
"net/http"
"os"
"github.com/gin-gonic/gin"
"github.com/mitchellh/mapstructure"
"github.com/rs/zerolog/log"
"github.com/fakeyanss/jt808-server-go/internal/config"
"github.com/fakeyanss/jt808-server-go/internal/protocol/model"
"github.com/fakeyanss/jt808-server-go/internal/server"
"github.com/fakeyanss/jt808-server-go/internal/storage"
)
func Run(serv *server.TCPServer, cfg *config.Config) {
// web server structure
gin.SetMode(gin.ReleaseMode)
router := gin.Default()
cache := storage.GetDeviceCache()
geoCache := storage.GetGeoCache()
router.GET("/device", func(c *gin.Context) {
c.JSON(http.StatusOK, cache.ListDevice())
})
router.GET("/device/:phone/geo", func(c *gin.Context) {
phone := c.Param("phone")
device, err := cache.GetDeviceByPhone(phone)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"err": err.Error()})
return
}
res := make(map[string]any)
err = mapstructure.Decode(device, &res)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"err": err.Error()})
return
}
gis, err := geoCache.GetGeoLatestByPhone(phone)
if err != nil {
return
}
res["gis"] = gis
c.JSON(http.StatusOK, res)
})
router.GET("/device/:phone/params", func(c *gin.Context) {
phone := c.Param("phone")
device, err := cache.GetDeviceByPhone(phone)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"err": err.Error()})
return
}
session, err := storage.GetSession(device.SessionID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"err": err.Error()})
}
header := model.GenMsgHeader(device, 0x8104, session.GetNextSerialNum())
msg := model.Msg8104{
Header: header,
}
serv.Send(session.ID, &msg)
// todo: read channel from process 0104 msg
})
router.PUT("/device/:phone/params", func(c *gin.Context) {
phone := c.Param("phone")
params := model.DeviceParams{}
if err := c.ShouldBind(¶ms); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"err": err.Error()})
}
device, err := cache.GetDeviceByPhone(phone)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"err": err.Error()})
return
}
session, err := storage.GetSession(device.SessionID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"err": err.Error()})
}
header := model.GenMsgHeader(device, 0x8103, session.GetNextSerialNum())
msg := model.Msg8103{
Header: header,
Parameters: ¶ms,
}
serv.Send(session.ID, &msg)
})
httpAddr := ":" + cfg.Server.Port.HTTPPort
log.Debug().Msgf("Listening and serving HTTP on :%s", cfg.Server.Port.HTTPPort)
err := router.Run(httpAddr)
if err != nil {
log.Error().Err(err).Str("addr", httpAddr).Msg("Fail to run gin router")
os.Exit(1)
}
}