129 lines
2.5 KiB
Go
129 lines
2.5 KiB
Go
package unisc
|
|
|
|
import (
|
|
"bytes"
|
|
"dashboard/dao/sqldb"
|
|
"dashboard/models"
|
|
"dashboard/routes"
|
|
"dashboard/services/uniss"
|
|
"dashboard/utils"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type HttpRoute struct {
|
|
httpHandle *httpHandle
|
|
middleWare *middleWare
|
|
}
|
|
|
|
func NewHttpRoute(httpc chan *models.UnisHttpRequest) *HttpRoute {
|
|
res := new(HttpRoute)
|
|
|
|
res.httpHandle = newhttpHandle(httpc)
|
|
res.middleWare = newmiddleWare()
|
|
|
|
return res
|
|
}
|
|
|
|
func (u *HttpRoute) AddRoute(r *gin.Engine) {
|
|
unisr := r.Group("/api/unis")
|
|
unisr.Use(routes.ErrWapper(u.middleWare.GinCheckServerId), routes.ErrWapper(u.middleWare.GinStoreRequest))
|
|
{
|
|
unisr.POST("/config/v1/add", routes.ErrWapper(u.httpHandle.stationConfig))
|
|
}
|
|
}
|
|
|
|
type middleWare struct {
|
|
}
|
|
|
|
func newmiddleWare() *middleWare {
|
|
return new(middleWare)
|
|
}
|
|
|
|
func (m *middleWare) GinCheckServerId(c *gin.Context) error {
|
|
serverId := c.GetHeader("serverId")
|
|
|
|
if serverId != serverId {
|
|
c.Abort()
|
|
return &models.BaseError{
|
|
Code: http.StatusServiceUnavailable,
|
|
Msg: "Server Id error",
|
|
}
|
|
}
|
|
|
|
channel, err := strconv.Atoi(c.GetHeader("channel"))
|
|
if err != nil {
|
|
c.Abort()
|
|
return &models.BaseError{
|
|
Code: http.StatusServiceUnavailable,
|
|
Msg: "Channel Id error",
|
|
}
|
|
}
|
|
|
|
c.Set(models.GinContextServerId, serverId)
|
|
c.Set(models.GinContextChannel, channel)
|
|
|
|
c.Next()
|
|
|
|
return nil
|
|
}
|
|
|
|
func (m *middleWare) GinStoreRequest(c *gin.Context) (err error) {
|
|
defer func() {
|
|
if err != nil {
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}()
|
|
|
|
log, _ := utils.GetLogFromContext(c)
|
|
channel := c.GetInt(models.GinContextChannel)
|
|
|
|
oldConf, _err := sqldb.ResFulDataGet(c.Request.Method, c.Request.URL.String(), channel)
|
|
if _err != nil {
|
|
err = _err
|
|
}
|
|
|
|
bodyBytes, _err := io.ReadAll(c.Request.Body)
|
|
if _err != nil {
|
|
err = _err
|
|
}
|
|
|
|
c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
|
|
|
|
if oldConf != string(bodyBytes) {
|
|
log.Sugar().Info("The resful request is not equel local store")
|
|
if _err := sqldb.ResFulDataStore(c.Request.Method, c.Request.URL.String(), string(bodyBytes), channel); err != nil {
|
|
err = _err
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (m *middleWare) GinWithUnisObject(unis *uniss.UnisStation) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
c.Set(models.GinContextUnis, unis)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func (m *middleWare) GetUnisObjectFromContext(c *gin.Context) (*uniss.UnisStation, error) {
|
|
res, ok := c.Get(models.GinContextUnis)
|
|
if !ok {
|
|
return nil, models.ErrorInvalidData
|
|
}
|
|
|
|
unis, ok := res.(*uniss.UnisStation)
|
|
if !ok {
|
|
return nil, models.ErrorInvalidData
|
|
}
|
|
|
|
return unis, nil
|
|
}
|