🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ package main import ( "fmt" "net/http" "github.com/gorilla/websocket" ) var upgrader = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { // 允许所有来源建立WebSocket连接 return true }, } func handleWebSocket(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { fmt.Println(err) return } defer conn.Close() for { messageType, p, err := conn.ReadMessage() if err != nil { fmt.Println(err) return } if err := conn.WriteMessage(messageType, p); err != nil { fmt.Println(err) return } } } func main() { http.HandleFunc("/websocket", handleWebSocket) http.ListenAndServe(":8080", nil) } ~~~