44 lines
781 B
Go
44 lines
781 B
Go
package main
|
|
|
|
import (
|
|
"flag"
|
|
"github.com/gorilla/websocket"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
var addr = flag.String("addr", "localhost:8797", "http service address")
|
|
|
|
var upgrader = websocket.Upgrader{} // use default options
|
|
|
|
func echo(w http.ResponseWriter, r *http.Request) {
|
|
c, err := upgrader.Upgrade(w, r, nil)
|
|
if err != nil {
|
|
log.Print("upgrade:", err)
|
|
return
|
|
}
|
|
defer func(c *websocket.Conn) {
|
|
err := c.Close()
|
|
if err != nil {
|
|
log.Println("close: ", err)
|
|
return
|
|
}
|
|
}(c)
|
|
for {
|
|
mt, message, err := c.ReadMessage()
|
|
log.Printf("recv: %s", message)
|
|
err = c.WriteMessage(mt, message)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
flag.Parse()
|
|
log.SetFlags(0)
|
|
http.HandleFunc("/", echo)
|
|
log.Fatal(http.ListenAndServe(*addr, nil))
|
|
}
|