package webServer
|
|
import (
|
"context"
|
"io/ioutil"
|
"net/http"
|
|
"serfNode/config"
|
"serfNode/ipc"
|
"serfNode/serf"
|
|
"github.com/gin-gonic/gin"
|
)
|
|
func Serve(port string) {
|
|
r := gin.Default()
|
r.GET("/serf/config", getSerfState)
|
|
r.GET("/serf/state", getSerfState)
|
r.GET("/serf/member", getSerfMembers)
|
r.POST("/serf/join", joinCluster)
|
r.GET("/serf/leave", leaveCluster)
|
r.POST("/serf/plc", transData)
|
|
r.Run(":" + port)
|
}
|
|
func resetConfig(c *gin.Context) {
|
nodeName := config.SerfConf.NodeName
|
|
err := ipc.GetConfigFromNodeRed()
|
if err == nil {
|
if nodeName != config.SerfConf.NodeName {
|
ctx := context.Background()
|
serf.InitAgent(ctx, *config.SerfConf)
|
}
|
}
|
|
}
|
|
func getSerfState(c *gin.Context) {
|
c.JSON(http.StatusOK, gin.H{
|
"success": true,
|
"data": serf.ClusterState(),
|
})
|
}
|
|
func getSerfMembers(c *gin.Context) {
|
c.JSON(http.StatusOK, gin.H{
|
"success": true,
|
"data": serf.Members(),
|
})
|
}
|
|
type joinParam struct {
|
NodeAddr string `json:"nodeAddr" binding:"required"`
|
}
|
|
func joinCluster(c *gin.Context) {
|
var query joinParam
|
err := c.BindJSON(&query)
|
if err != nil {
|
c.JSON(http.StatusBadRequest, gin.H{
|
"success": false,
|
"message": "参数错误",
|
})
|
|
return
|
}
|
|
err = serf.JoinCluster(query.NodeAddr)
|
if err != nil {
|
c.JSON(http.StatusOK, gin.H{
|
"success": false,
|
"message": err.Error(),
|
})
|
|
return
|
}
|
|
c.JSON(http.StatusOK, gin.H{
|
"success": true,
|
"message": "加入成功",
|
})
|
}
|
|
func leaveCluster(c *gin.Context) {
|
err := serf.LeaveCluster()
|
if err != nil {
|
c.JSON(http.StatusOK, gin.H{
|
"success": false,
|
"message": err.Error(),
|
})
|
|
return
|
}
|
|
c.JSON(http.StatusOK, gin.H{
|
"success": true,
|
"message": "加入成功",
|
})
|
}
|
|
func transData(c *gin.Context) {
|
bodyBytes, _ := ioutil.ReadAll(c.Request.Body)
|
|
err := serf.QueryMsg2Master(serf.PLCDATA, bodyBytes)
|
if err != nil {
|
c.JSON(http.StatusOK, gin.H{
|
"success": false,
|
"message": err.Error(),
|
})
|
|
return
|
}
|
|
c.JSON(http.StatusOK, gin.H{
|
"success": true,
|
"message": "发送成功",
|
})
|
}
|