dnssecsocket/gorilla-server/main.go

103 lines
2.4 KiB
Go
Raw Normal View History

package main
import "flag"
import "io"
import "log"
import "net/http"
import "github.com/gorilla/websocket"
import "github.com/golang/protobuf/proto"
import pb "git.wit.com/wit/witProtobuf"
var upgrader = websocket.Upgrader{
ReadBufferSize: 4096,
WriteBufferSize: 4096,
EnableCompression: true,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func sendSampleProtobuf(conn *websocket.Conn) {
msg := pb.CreateSampleEvent()
msg.Name = "test echo over gorilla websocket"
data, _ := proto.Marshal(msg)
err := conn.WriteMessage(websocket.BinaryMessage, data)
if err != nil {
log.Println("sendProtobuf() write:", err)
}
}
func sendProtobuf(conn *websocket.Conn, msg *pb.Event) {
data, _ := proto.Marshal(msg)
err := conn.WriteMessage(websocket.BinaryMessage, data)
if err != nil {
log.Println("sendProtobuf() write:", err)
}
}
func eventHandler(w http.ResponseWriter, r *http.Request) {
log.Println("echoHandler() START")
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("Upgrade:", err)
return
}
defer conn.Close()
for {
mytype, message, err := conn.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
if mytype == websocket.TextMessage {
log.Println("echoHandler() TextMessage mytype=", mytype)
}
if mytype == websocket.BinaryMessage {
log.Println("echoHandler() BinaryMessage mytype=", mytype)
pdata := new(pb.Event)
err = proto.Unmarshal(message, pdata)
if (err != nil) {
log.Printf("readConn() something fucked up happened in Unmarshal")
}
log.Printf("recv binary: %s", pdata)
if pdata.Type == pb.Event_MIGRATE {
log.Printf("GOT MIGRATE")
e := oldmain()
sendProtobuf(conn, e)
}
}
}
}
func serveHome(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "Not found.", http.StatusNotFound)
return
}
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
io.WriteString(w, "<html><body>Echo Server</body></html>")
}
var addr = flag.String("addr", ":9000", "http service address")
func main() {
flag.Parse()
http.HandleFunc("/", serveHome)
http.HandleFunc("/event", eventHandler)
log.Println("Starting http.ListenAndServe() on port 9000")
err := http.ListenAndServe(*addr, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}