func handleWebSocket(conn *websocket.Conn) { respStatus := http.StatusOK defer func() { conn.Close() logRequest(HTTPS_WEBSOCKET, respStatus, conn.Request().Host, conn.Request()) }() request := make([]byte, 1024) for { n, err := conn.Read(request) if err != nil { if debugMode { log.Error("Error reading on WebSocket: %s", err) } break } response, status := getLiveItems(string(request[:n])) if status != http.StatusOK { respStatus = status break } if len(response) != 0 { if _, err = conn.Write(response); err != nil { break } } } }
func socketHandler(c *websocket.Conn) { in, out := make(chan *Message), make(chan *Message) errc := make(chan error, 1) // Decode messages from client and send to the in channel. go func() { dec := json.NewDecoder(c) for { var m Message if err := dec.Decode(&m); err != nil { errc <- err return } in <- &m } }() // Receive messages from the out channel and encode to the client. go func() { enc := json.NewEncoder(c) for m := range out { if err := enc.Encode(m); err != nil { errc <- err return } } }() // open a connection to minimega and handle the request megaconns := make(map[string]*megaconn) for { select { case m := <-in: log.Debugln("running snippet from:", c.Request().RemoteAddr) lOut := limiter(in, out) megaconns[m.Id] = runMega(m.Id, m.Body, lOut) case err := <-errc: if err != io.EOF { // A encode or decode has failed; bail. log.Errorln(err) } return } } }