package fusenrender import ( "context" "encoding/json" "fmt" "io" "log" "net/http" "time" "github.com/gorilla/websocket" "github.com/lni/dragonboat/v4" ) var UidCreater = NewUniqueId(1) var PopChannel chan []byte = make(chan []byte, 3) // chan *QueueItem = make(chan *QueueItem, 1) var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } func queueHandler(w http.ResponseWriter, r *http.Request) { conn, _ := upgrader.Upgrade(w, r, nil) var err error for { itemdata := <-PopChannel // 写回消息 err = conn.WriteMessage(websocket.BinaryMessage, itemdata) if err != nil { return } // 打印消息 fmt.Printf("%s len=%d sent: \n%s\n", conn.RemoteAddr(), len(itemdata), string(itemdata)) // 读取消息 // msgType, msg, err := conn.ReadMessage() // if err != nil { // return // } } } func callbackHandler(w http.ResponseWriter, r *http.Request) { conn, _ := upgrader.Upgrade(w, r, nil) for { // 读取消息 msgType, msg, err := conn.ReadMessage() if err != nil { return } // 打印消息 fmt.Printf("%s sent: %s\n", conn.RemoteAddr(), string(msg)) // 写回消息 err = conn.WriteMessage(msgType, msg) if err != nil { return } } } func queuePushHandler(w http.ResponseWriter, r *http.Request) { // 1. 读取Body内容 body, err := io.ReadAll(r.Body) if err != nil { panic(err) } // 2. 定义结构体 item := &QueueItem{ Group: "test", CreateAt: time.Now(), Data: "saddas", } // 3. 解析JSON到结构体 err = json.Unmarshal(body, item) if err != nil { panic(err) } } var wns *dragonboat.NodeHost func PushItem(nh *dragonboat.NodeHost, item *QueueItem) { cs := nh.GetNoOPSession(128) cmd := &CmdEnqueue{Command: Command{Group: "test"}} cmd.Item = item data, err := FsPasser.PackToBytes(cmd) if err != nil { log.Println(err) } ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) _, err = nh.SyncPropose(ctx, cs, data) if err != nil { log.Println(err) } // log.Println("enqueue", len(result.Data)) cancel() } func HttpStart(ns *dragonboat.NodeHost, port int) { wns = ns http.HandleFunc("/api/queue/push", queuePushHandler) http.HandleFunc("/ws/pop/queue", queueHandler) http.HandleFunc("/ws/callback", callbackHandler) log.Println(fmt.Sprintf(":%d", port)) http.ListenAndServe(fmt.Sprintf(":%d", port), nil) }