go_echo_wol/controller/wsmain.go

85 lines
1.7 KiB
Go

package controller
import (
"encoding/json"
"fmt"
"github.com/labstack/echo/v4"
"golang.org/x/net/websocket"
)
type MacData struct {
Mac string `json:"mac"`
}
type DelData struct {
ID int64 `json:"id"`
}
type AddData struct {
Nmae string `json:"name"`
Mac string `json:"mac"`
}
type TooLTT struct {
Method string `json:"method"`
Data interface{} `json:"data"`
Uuid string `json:"uuid"`
}
/*
ws 分发
*/
func Hello(c echo.Context) error {
websocket.Handler(func(ws *websocket.Conn) {
defer ws.Close()
for {
msg := ""
err := websocket.Message.Receive(ws, &msg)
if err != nil {
c.Logger().Error(err)
break
}
//暂时不解析的json
var json_data json.RawMessage
wsValue := TooLTT{
Data: &json_data,
}
json.Unmarshal([]byte(msg), &wsValue)
if err := json.Unmarshal([]byte(msg), &wsValue); err != nil {
fmt.Println(err)
}
switch wsValue.Method {
case "start":
var startdata MacData
if err := json.Unmarshal(json_data, &startdata); err != nil {
c.Logger().Error(err)
return
}
Send_start(startdata.Mac, &ws, wsValue.Uuid)
case "getall":
Getall(&ws, wsValue.Uuid)
case "del":
var DelData DelData
if err := json.Unmarshal(json_data, &DelData); err != nil {
c.Logger().Error(err)
return
}
Del(&ws, wsValue.Uuid, DelData.ID)
case "add":
var AddData AddData
if err := json.Unmarshal(json_data, &AddData); err != nil {
c.Logger().Error(err)
return
}
Add(&ws, wsValue.Uuid, AddData.Nmae, AddData.Mac)
default:
c.Logger().Error("没有找到方法")
}
fmt.Printf("请求方法:%s uuid:%s \n", wsValue.Method, wsValue.Uuid)
}
}).ServeHTTP(c.Response(), c.Request())
return nil
}