diff --git a/app/websocket/conn.go b/app/websocket/conn.go new file mode 100644 index 0000000..d8c3086 --- /dev/null +++ b/app/websocket/conn.go @@ -0,0 +1,49 @@ +package websocket + +import ( + "log" + "net/http" + + "github.com/gin-gonic/gin" + "github.com/gorilla/websocket" +) + +// WebSocket upgrader +var upgrader = websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 1024, + CheckOrigin: func(r *http.Request) bool { + // Allow all connections for this example. In production, restrict origins. + return true + }, +} + +func Conn(c *gin.Context) { + conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) + if err != nil { + log.Println("Failed to upgrade to WebSocket:", err) + return + } + + defer conn.Close() + + log.Println("WebSocket connection established") + + for { + // Read a message + messageType, msg, err := conn.ReadMessage() + if err != nil { + log.Println("Error reading message:", err) + break + } + + log.Printf("Received message: %s\n", msg) + + // Echo the message back to the client + err = conn.WriteMessage(messageType, []byte("Echo: "+string(msg))) + if err != nil { + log.Println("Error writing message:", err) + break + } + } +} diff --git a/config/routes.go b/config/routes.go index 9541eb7..8a4c4fe 100644 --- a/config/routes.go +++ b/config/routes.go @@ -5,9 +5,12 @@ import ( "github.com/daqing/airway/app/api/up_api" "github.com/daqing/airway/app/api/user_api" + "github.com/daqing/airway/app/websocket" ) func Routes(r *gin.Engine) { + websocketRoutes(r) + apiRoutes(r) } @@ -18,3 +21,7 @@ func apiRoutes(r *gin.Engine) { user_api.Routes(v1) } + +func websocketRoutes(r *gin.Engine) { + r.GET("/ws", websocket.Conn) +} diff --git a/go.mod b/go.mod index 2157368..76d6661 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.21.3 require ( github.com/gin-contrib/cors v1.4.0 github.com/gin-gonic/gin v1.9.1 + github.com/gorilla/websocket v1.5.3 github.com/iancoleman/strcase v0.3.0 github.com/joho/godotenv v1.5.1 github.com/yuin/goldmark v1.6.0 diff --git a/go.sum b/go.sum index 3029e9b..ed22a58 100644 --- a/go.sum +++ b/go.sum @@ -37,6 +37,8 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=