完成聊天 websocket API 对接

This commit is contained in:
RockYang
2023-03-17 15:38:05 +08:00
parent c25cc97450
commit 9477b96629
7 changed files with 108 additions and 126 deletions

View File

@@ -1,11 +1,34 @@
package server
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"net/http"
)
func (s *Server) Chat(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"code": 0, "message": fmt.Sprintf("HELLO, ChatGPT !!!")})
ws, err := (&websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}).Upgrade(c.Writer, c.Request, nil)
if err != nil {
logger.Fatal(err)
return
}
logger.Infof("New websocket connected, IP: %s", c.Request.RemoteAddr)
client := NewWsClient(ws)
go func() {
for {
_, message, err := client.Receive()
if err != nil {
logger.Error(err)
client.Close()
return
}
// TODO: 接受消息,调用 ChatGPT 返回消息
logger.Info(string(message))
err = client.Send(message)
if err != nil {
logger.Error(err)
}
}
}()
}

View File

@@ -14,22 +14,18 @@ type Client interface {
// WsClient websocket client
type WsClient struct {
NodeId string
SessionId string
Conn *websocket.Conn
lock sync.Mutex
mt int
closed bool
Conn *websocket.Conn
lock sync.Mutex
mt int
closed bool
}
func NewWsClient(nodeId string, sessionId string, conn *websocket.Conn) *WsClient {
func NewWsClient(conn *websocket.Conn) *WsClient {
return &WsClient{
NodeId: nodeId,
SessionId: sessionId,
Conn: conn,
lock: sync.Mutex{},
mt: 2, // fixed bug for 'Invalid UTF-8 in text frame'
closed: false,
Conn: conn,
lock: sync.Mutex{},
mt: 2, // fixed bug for 'Invalid UTF-8 in text frame'
closed: false,
}
}