initial: ZeroTier-like P2P mesh VPN server with multi-tenant Web UI
This commit is contained in:
81
internal/handler/node.go
Normal file
81
internal/handler/node.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"zeromesh/internal/service"
|
||||
)
|
||||
|
||||
type NodeHandler struct {
|
||||
nodeService *service.NodeService
|
||||
}
|
||||
|
||||
func NewNodeHandler(nodeService *service.NodeService) *NodeHandler {
|
||||
return &NodeHandler{nodeService: nodeService}
|
||||
}
|
||||
|
||||
type registerNodeReq struct {
|
||||
NodeID string `json:"node_id" binding:"required"`
|
||||
PublicKey string `json:"public_key" binding:"required"`
|
||||
Name string `json:"name"`
|
||||
IPAddress string `json:"ip_address"`
|
||||
Port int `json:"port"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
func (h *NodeHandler) Register(c *gin.Context) {
|
||||
var req registerNodeReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
uid := userID(c)
|
||||
node, err := h.nodeService.Register(req.NodeID, req.PublicKey, req.Name, req.IPAddress, req.Port, req.Version, uid)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"node": node})
|
||||
}
|
||||
|
||||
func (h *NodeHandler) List(c *gin.Context) {
|
||||
uid := userID(c)
|
||||
if !isAdmin(c) {
|
||||
nodes, err := h.nodeService.ListNode(uid)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"nodes": nodes})
|
||||
return
|
||||
}
|
||||
nodes, err := h.nodeService.ListNode(0)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"nodes": nodes})
|
||||
}
|
||||
|
||||
func (h *NodeHandler) ListOnline(c *gin.Context) {
|
||||
uid := userID(c)
|
||||
nodes, err := h.nodeService.ListOnline(uid)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"nodes": nodes})
|
||||
}
|
||||
|
||||
func (h *NodeHandler) Heartbeat(c *gin.Context) {
|
||||
nodeID := c.Param("node_id")
|
||||
if err := h.nodeService.SetOnline(nodeID, true); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
time.Sleep(5 * time.Second)
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
}
|
||||
Reference in New Issue
Block a user