websocket/examples/echo/server.go

57 lines
1.0 KiB
Go
Raw Normal View History

2015-09-24 01:29:30 +03:00
// Copyright 2015 The Gorilla WebSocket Authors. All rights reserved.
2015-09-24 01:23:26 +03:00
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
2015-09-24 01:29:30 +03:00
// +build ignore
2015-09-24 01:23:26 +03:00
package main
import (
"flag"
"log"
"net/http"
"github.com/gorilla/websocket"
)
var addr = flag.String("addr", "localhost:8081", "http service address")
var upgrader = websocket.Upgrader{} // use default options
func echo(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "Not found", 404)
return
}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer c.Close()
for {
mt, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", message)
err = c.WriteMessage(mt, message)
if err != nil {
log.Println("write:", err)
break
}
}
}
func main() {
flag.Parse()
log.SetFlags(0)
http.HandleFunc("/", echo)
err := http.ListenAndServe(*addr, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}