init commit
This commit is contained in:
115
server/web/app/handlers/node.go
Normal file
115
server/web/app/handlers/node.go
Normal file
@@ -0,0 +1,115 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
"os"
|
||||
"proxy-server/server/orm"
|
||||
"proxy-server/server/web/app/models"
|
||||
)
|
||||
|
||||
type NodeRegisterReq struct {
|
||||
Name string
|
||||
Secret string
|
||||
}
|
||||
|
||||
func NodeRegister(c *gin.Context) {
|
||||
|
||||
// 请求参数
|
||||
var req NodeRegisterReq
|
||||
err := c.ShouldBind(&req)
|
||||
if err != nil {
|
||||
_ = c.Error(errors.Wrap(err, "参数解析错误"))
|
||||
return
|
||||
}
|
||||
|
||||
// 验证 secret
|
||||
secret := os.Getenv("SECRET")
|
||||
if req.Secret != secret {
|
||||
_ = c.Error(errors.New("拒绝连接"))
|
||||
return
|
||||
}
|
||||
|
||||
// 注册节点
|
||||
// todo 查询运营商和地区
|
||||
err = orm.DB.Transaction(func(tx *gorm.DB) error {
|
||||
|
||||
// 查询节点是否已存在
|
||||
var count int64
|
||||
err := orm.DB.Where(&models.Node{
|
||||
Name: req.Name,
|
||||
}).Count(&count).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 不存在则注册
|
||||
if count == 0 {
|
||||
ipAddress := c.ClientIP()
|
||||
node := models.Node{
|
||||
Name: req.Name,
|
||||
Provider: "",
|
||||
Location: "",
|
||||
IPAddress: ipAddress,
|
||||
}
|
||||
err = orm.DB.Create(&node).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
_ = c.Error(errors.Wrap(err, "注册节点失败"))
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(200)
|
||||
}
|
||||
|
||||
type NodeReportReq struct {
|
||||
Name string
|
||||
}
|
||||
|
||||
func NodeReport(c *gin.Context) {
|
||||
|
||||
// 请求参数
|
||||
var req NodeReportReq
|
||||
err := c.ShouldBind(&req)
|
||||
if err != nil {
|
||||
_ = c.Error(errors.Wrap(err, "参数解析错误"))
|
||||
return
|
||||
}
|
||||
|
||||
// 上报节点信息
|
||||
err = orm.DB.Transaction(func(tx *gorm.DB) error {
|
||||
|
||||
// 查询节点
|
||||
var node models.Node
|
||||
err = orm.DB.Where(&models.Node{
|
||||
Name: req.Name,
|
||||
}).First(&node).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 更新节点信息
|
||||
ipAddress := c.ClientIP()
|
||||
if ipAddress != node.IPAddress {
|
||||
err = orm.DB.Model(&node).Update("ip_address", ipAddress).Error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
_ = c.Error(errors.Wrap(err, "上报节点信息失败"))
|
||||
return
|
||||
}
|
||||
|
||||
c.Status(200)
|
||||
}
|
||||
Reference in New Issue
Block a user