gin 和gorilla 写websocket 示例代码
时间: 2023-03-10 07:16:17 浏览: 167
gin框架简单使用示例
您好,Gin和Gorilla可以用以下示例代码实现Websocket:package mainimport (
"log"
"net/http" "github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}func main() {
router := gin.Default() router.GET("/", func(c *gin.Context) {
http.ServeFile(c.Writer, c.Request, "index.html")
}) router.GET("/ws", func(c *gin.Context) {
ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Println(err)
return
} for {
// Read
mt, message, err := ws.ReadMessage()
if err != nil {
log.Println(err)
break
}
log.Printf("Received: %s", message) // Write
err = ws.WriteMessage(mt, message)
if err != nil {
log.Println(err)
break
}
}
}) router.Run(":3000")
}
阅读全文