forked from appleboy/gorush
/
server.go
95 lines (78 loc) · 2.15 KB
/
server.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
package gorush
import (
"fmt"
"github.com/fvbock/endless"
"github.com/gin-gonic/gin"
api "gopkg.in/appleboy/gin-status-api.v1"
"net/http"
)
func abortWithError(c *gin.Context, code int, message string) {
c.JSON(code, gin.H{
"code": code,
"message": message,
})
c.Abort()
}
func rootHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"text": "Welcome to notification server.",
})
}
func pushHandler(c *gin.Context) {
var form RequestPush
var msg string
if err := c.BindJSON(&form); err != nil {
msg = "Missing notifications field."
LogAccess.Debug(msg)
abortWithError(c, http.StatusBadRequest, msg)
return
}
if len(form.Notifications) == 0 {
msg = "Notifications field is empty."
LogAccess.Debug(msg)
abortWithError(c, http.StatusBadRequest, msg)
return
}
if int64(len(form.Notifications)) > PushConf.Core.MaxNotification {
msg = fmt.Sprintf("Number of notifications(%d) over limit(%d)", len(form.Notifications), PushConf.Core.MaxNotification)
LogAccess.Debug(msg)
abortWithError(c, http.StatusBadRequest, msg)
return
}
// queue notification.
go queueNotification(form)
c.JSON(http.StatusOK, gin.H{
"success": "ok",
})
}
func configHandler(c *gin.Context) {
c.YAML(http.StatusCreated, PushConf)
}
func routerEngine() *gin.Engine {
// set server mode
gin.SetMode(PushConf.Core.Mode)
r := gin.New()
// Global middleware
r.Use(gin.Logger())
r.Use(gin.Recovery())
r.Use(VersionMiddleware())
r.Use(LogMiddleware())
r.Use(StatMiddleware())
r.GET(PushConf.API.StatGoURI, api.StatusHandler)
r.GET(PushConf.API.StatAppURI, appStatusHandler)
r.GET(PushConf.API.ConfigURI, configHandler)
r.GET(PushConf.API.SysStatURI, sysStatsHandler)
r.POST(PushConf.API.PushURI, pushHandler)
r.GET("/", rootHandler)
return r
}
// RunHTTPServer provide run http or https protocol.
func RunHTTPServer() error {
var err error
if PushConf.Core.SSL && PushConf.Core.CertPath != "" && PushConf.Core.KeyPath != "" {
err = endless.ListenAndServeTLS(":"+PushConf.Core.Port, PushConf.Core.CertPath, PushConf.Core.KeyPath, routerEngine())
} else {
err = endless.ListenAndServe(":"+PushConf.Core.Port, routerEngine())
}
return err
}