Example #1
0
/**
 * Close connection
 */
func (server *server) Close(ws *websocket.Conn) {
	err := ws.Close()

	if err != nil {
		server.Error(err)
	}
}
Example #2
0
// handle implements a WebSocket handler.
func (r *Reader) handle(ws *websocket.Conn) {
	encode := len(ws.Config().Protocol) > 0 && ws.Config().Protocol[0] == base64BinaryWebSocketProtocol
	defer close(r.err)
	defer ws.Close()
	go IgnoreReceives(ws, r.timeout)
	r.err <- messageCopy(ws, r.r, encode, r.ping, r.timeout)
}
Example #3
0
func (this *socketManager) wsOnConnect(ws *websocket.Conn) {
	var err error
	var p payload

	defer func() {
		if err = ws.Close(); err != nil {
			logger.Info.Println("Websocket could not be closed", err.Error())
		}
	}()
	//Client connected to websocket
	connection := connection{ws}
	//Keep a reference to the connection
	this.connections[&connection] = true
	logger.Info.Println("WebSocket Connection event ...")
	logger.Info.Println("Number of clients connected ...", len(this.connections))

	//Get the last messages from the zmqDealer TCP pipe
	this.getLastMessages(connection)
	//Wait a bit for the last messages to send...
	time.Sleep(3 * time.Second)
	// Loop to keep websocket open
	for {
		if err = websocket.JSON.Receive(ws, &p); err != nil {
			//Socket is closed if
			logger.Info.Println("Websocket Disconnected...", err.Error())
			//Remove connection from active connections
			delete(this.connections, &connection)
			logger.Info.Println("Number of clients connected ...", len(this.connections))
			return
		}
	}
}
Example #4
0
func (c *Client) Stream(path string, headers map[string]string, in io.Reader, out io.WriteCloser) error {
	origin := fmt.Sprintf("https://%s", c.Host)
	endpoint := fmt.Sprintf("wss://%s%s", c.Host, path)

	config, err := websocket.NewConfig(endpoint, origin)

	if err != nil {
		return err
	}

	config.TlsConfig = &tls.Config{
		InsecureSkipVerify: true,
	}

	config.Header.Set("Version", c.Version)

	userpass := fmt.Sprintf("convox:%s", c.Password)
	userpass_encoded := base64.StdEncoding.EncodeToString([]byte(userpass))

	config.Header.Add("Authorization", fmt.Sprintf("Basic %s", userpass_encoded))

	for k, v := range headers {
		config.Header.Add(k, v)
	}

	config.TlsConfig = &tls.Config{
		InsecureSkipVerify: true,
	}

	var ws *websocket.Conn

	if proxy := os.Getenv("HTTPS_PROXY"); proxy != "" {
		ws, err = c.proxyWebsocket(config, proxy)
	} else {
		ws, err = websocket.DialConfig(config)
	}

	if err != nil {
		return err
	}

	defer ws.Close()

	var wg sync.WaitGroup

	if in != nil {
		go io.Copy(ws, in)
	}

	if out != nil {
		wg.Add(1)
		go copyAsync(out, ws, &wg)
	}

	wg.Wait()

	out.Close()

	return nil
}
Example #5
0
func (self *Server) webSocketHandler(conn *websocket.Conn) {

	dispatcher := NewDispatcher(self)

	for {
		data := map[string]interface{}{}
		err := websocket.JSON.Receive(conn, &data)

		if err != nil {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				fmt.Println(err)
				continue
			}
			if err == io.EOF {
				fmt.Println(fmt.Sprintf("Client Dissconected :%s", conn.RemoteAddr()))
				break
			} else {
				fmt.Println(fmt.Sprintf("Receive Data Failed %s", err))
				break
			}
		}

		fmt.Println("Dispatch", data)
		err = dispatcher.Dispatch(conn, data)

		if err != nil {
			fmt.Println(fmt.Sprintf("Dispatch Failed %s", err))
		}
	}

	defer func() {
		conn.Close()
	}()

}
Example #6
0
func scoreboardHandler(ws *websocket.Conn) {

	defer ws.Close()

	fmt.Fprint(ws, currentResult)
	sendedResult := currentResult
	lastUpdate := time.Now()

	for {
		if sendedResult != currentResult ||
			time.Now().After(lastUpdate.Add(time.Minute)) {

			sendedResult = currentResult
			lastUpdate = time.Now()

			_, err := fmt.Fprint(ws, currentResult)
			if err != nil {
				log.Println("Socket closed:", err)
				return
			}
		}

		time.Sleep(time.Second)
	}
}
Example #7
0
func (g *game) Start(ws *websocket.Conn) {
	defer ws.Close()

	var player user.User
	for {
		if err := websocket.JSON.Receive(ws, &player); err != nil {
			panic(err)
			return
		}
		player.Socket = ws
		g.Players[player.Name] = player
		for k, v := range g.Players {
			if k == player.Name {
				continue
			}

			if err := websocket.JSON.Send(v.Socket, player); err != nil {
				delete(g.Players, k)

				go g.SendMessageAll(&Message{
					Method:   "destroy",
					UserName: k,
				})
			}
		}
	}
}
Example #8
0
func split(data []byte, atEOF bool, conn *websocket.Conn, callback ReadCallBack) (adv int, token []byte, err error) {
	l := len(data)
	if l < 6 {
		return 0, nil, nil
	}
	if l > 100000 {
		conn.Close()
		log.Println("invalid query!")
		return 0, nil, errors.New("to large data!")
	}
	var len1, len2 int
	len1 = int(binary.LittleEndian.Uint16(data[:2]))
	len2 = int(binary.LittleEndian.Uint32(data[2:6]))
	offset := 0
	if len1+len2+6 > l {
		conn.Close()
		log.Println("invalid data", len1, len2, l)
		return 0, nil, errors.New("invalid data")
	}
	offset += len1 + len2 + 6
	head := string(data[6 : 6+len1])
	tail := data[6+len1 : 6+len1+len2]
	callback(conn, head, tail)
	return offset, []byte{}, nil
}
Example #9
0
// HandleConn handles on an individual socket connection
func (s *SocketHandler) HandleConn(ws *websocket.Conn) {
	defer ws.Close()
	doneChan := make(chan bool, 1)
	s.connLock.Lock()
	s.connections = append(s.connections, &WebSocketConn{
		Conn:     ws,
		DoneChan: doneChan,
	})
	s.connLock.Unlock()
	s.newConnectionChan <- struct{}{}

	// read commands
forloop:
	for {
		select {
		case <-doneChan:
			break forloop
		default:
			var msg Command
			if err := websocket.JSON.Receive(ws, &msg); err != nil {
				if err == io.EOF {
					break forloop
				}
				fmt.Printf("\n[ERROR] %v", err)
			} else {
				s.commandChan <- msg
			}
		}
	}
	fmt.Printf("Done listening on socket")
}
Example #10
0
func Chat(ws *websocket.Conn) {
	var message Message
	defer ws.Close()

	for {
		if err := websocket.JSON.Receive(ws, &message); err != nil {
			Log(err)
			return
		}

		active[message.Name] = ws

		if message.Text == "Register" {
			if err := websocket.JSON.Send(ws, online()); err != nil {
				Log(err)
				delete(active, message.Name)
				return
			}
			continue
		}

		go sendAll(&message)

	}
}
Example #11
0
File: chat.go Project: Chubik/chat
func SockServer(ws *websocket.Conn) {
	var err error
	var clientMessage string
	// use []byte if websocket binary type is blob or arraybuffer
	// var clientMessage []byte
	defer func() {
		if err = ws.Close(); err != nil {
			log.Println("Websocket could not be closed", err.Error())
		}
	}()

	client := ws.Request().RemoteAddr
	log.Println("Client connected:", client)
	sockCli := ClientConn{ws, client}
	ActiveClients[sockCli] = 0
	log.Println("Number of clients connected ...", len(ActiveClients))

	for {
		if err = Message.Receive(ws, &clientMessage); err != nil {
			log.Println("Websocket Disconnected waiting", err.Error())
			delete(ActiveClients, sockCli)
			log.Println("Number of clients still connected ...", len(ActiveClients))
			return
		}

		if len(clientMessage) > 0 {
			clientMessage = sockCli.clientIP + " Said: " + clientMessage
			for cs, _ := range ActiveClients {
				if err = Message.Send(cs.websocket, clientMessage); err != nil {
					log.Println("Could not send message to ", cs.clientIP, err.Error())
				}
			}
		}
	}
}
Example #12
0
// handle implements a WebSocket handler.
func (r *Reader) handle(ws *websocket.Conn) {
	// Close the connection when the client requests it, or when we finish streaming, whichever happens first
	closeConnOnce := &sync.Once{}
	closeConn := func() {
		closeConnOnce.Do(func() {
			ws.Close()
		})
	}

	negotiated := ws.Config().Protocol
	r.selectedProtocol = negotiated[0]
	defer close(r.err)
	defer closeConn()

	go func() {
		defer runtime.HandleCrash()
		// This blocks until the connection is closed.
		// Client should not send anything.
		IgnoreReceives(ws, r.timeout)
		// Once the client closes, we should also close
		closeConn()
	}()

	r.err <- messageCopy(ws, r.r, !r.protocols[r.selectedProtocol].Binary, r.ping, r.timeout)
}
Example #13
0
func (s *Server) Accept(ws *websocket.Conn) {
	ws.PayloadType = websocket.BinaryFrame
	if _, err := NewConnection(s, ws); err != nil {
		ws.SetDeadline(time.Now().Add(2 * time.Millisecond))
		ws.Close()
	}
}
Example #14
0
func wsserver(ws *websocket.Conn) {

	// read msg
	var (
		msg msgproto.Msg
		err error
		id  int32
		// topic string
	)
	for {
		err = msgCodec.Receive(ws, &msg)
		checkErr("Receive", err)
		if err != nil {
			break
		}
		// add client and topic client
		id = msg.GetId()
		if _, ok := clients[id]; !ok {
			clients[id] = ws
		}

		handleMsg(msg, ws)
	}

	defer func() {
		delete(clients, id)
		ws.Close()
	}()
}
Example #15
0
// HandleWS implements a websocket handler.
func (w *WatchServer) HandleWS(ws *websocket.Conn) {
	defer ws.Close()
	done := make(chan struct{})
	go func() {
		var unused interface{}
		// Expect this to block until the connection is closed. Client should not
		// send anything.
		websocket.JSON.Receive(ws, &unused)
		close(done)
	}()
	for {
		select {
		case <-done:
			w.watching.Stop()
			return
		case event, ok := <-w.watching.ResultChan():
			if !ok {
				// End of results.
				return
			}
			w.fixup(event.Object)
			obj, err := watchjson.Object(w.codec, &event)
			if err != nil {
				// Client disconnect.
				w.watching.Stop()
				return
			}
			if err := websocket.JSON.Send(ws, obj); err != nil {
				// Client disconnect.
				w.watching.Stop()
				return
			}
		}
	}
}
Example #16
0
func addLogs(ws *websocket.Conn) {
	var err error
	defer func() {
		data := map[string]interface{}{}
		if err != nil {
			data["error"] = err.Error()
			log.Error(err.Error())
		} else {
			data["error"] = nil
		}
		msg, _ := json.Marshal(data)
		ws.Write(msg)
		ws.Close()
	}()
	req := ws.Request()
	t := context.GetAuthToken(req)
	if t == nil {
		err = fmt.Errorf("wslogs: no token")
		return
	}
	if t.GetAppName() != app.InternalAppName {
		err = fmt.Errorf("wslogs: invalid token app name: %q", t.GetAppName())
		return
	}
	err = scanLogs(ws)
	if err != nil {
		return
	}
}
Example #17
0
File: log.go Project: tsuru/tsuru
func addLogs(ws *websocket.Conn) {
	var err error
	defer func() {
		msg := &errMsg{}
		if err != nil {
			msg.Error = err.Error()
			log.Errorf("failure in logs webservice: %s", err)
		}
		websocket.JSON.Send(ws, msg)
		ws.Close()
	}()
	req := ws.Request()
	t := context.GetAuthToken(req)
	if t == nil {
		err = errors.Errorf("wslogs: no token")
		return
	}
	if t.GetAppName() != app.InternalAppName {
		err = errors.Errorf("wslogs: invalid token app name: %q", t.GetAppName())
		return
	}
	err = scanLogs(ws)
	if err != nil {
		return
	}
}
Example #18
0
// wsHandler is a WebSocket server that handles requests from the WebSocket client in the form of:
// 1. { 'cmd': 'register', 'roomid': $ROOM, 'clientid': $CLIENT' },
// which binds the WebSocket client to a client ID and room ID.
// A client should send this message only once right after the connection is open.
// or
// 2. { 'cmd': 'send', 'msg': $MSG }, which sends the message to the other client of the room.
// It should be sent to the server only after 'regiser' has been sent.
// The message may be cached by the server if the other client has not joined.
//
// Unexpected messages will cause the WebSocket connection to be closed.
func (c *Collider) wsHandler(ws *websocket.Conn) {
	var rid, cid string

	registered := false

	var msg wsClientMsg
loop:
	for {
		err := ws.SetReadDeadline(time.Now().Add(time.Duration(wsReadTimeoutSec) * time.Second))
		if err != nil {
			c.wsError("ws.SetReadDeadline error: "+err.Error(), ws)
			break
		}

		err = websocket.JSON.Receive(ws, &msg)
		if err != nil {
			if err.Error() != "EOF" {
				c.wsError("websocket.JSON.Receive error: "+err.Error(), ws)
			}
			break
		}

		switch msg.Cmd {
		case "register":
			if registered {
				c.wsError("Duplicated register request", ws)
				break loop
			}
			if msg.RoomID == "" || msg.ClientID == "" {
				c.wsError("Invalid register request: missing 'clientid' or 'roomid'", ws)
				break loop
			}
			if err = c.roomTable.register(msg.RoomID, msg.ClientID, ws); err != nil {
				c.wsError(err.Error(), ws)
				break loop
			}
			registered, rid, cid = true, msg.RoomID, msg.ClientID
			c.dash.incrWs()

			defer c.roomTable.deregister(rid, cid)
			break
		case "send":
			if !registered {
				c.wsError("Client not registered", ws)
				break loop
			}
			if msg.Msg == "" {
				c.wsError("Invalid send request: missing 'msg'", ws)
				break loop
			}
			c.roomTable.send(rid, cid, msg.Msg)
			break
		default:
			c.wsError("Invalid message: unexpected 'cmd'", ws)
			break
		}
	}
	// This should be unnecessary but just be safe.
	ws.Close()
}
Example #19
0
func (ws *WebSocketServer) wslogsHandler(w *websocket.Conn) {
	source := w.Request().FormValue("source")
	host := fmt.Sprintf("%s/%d", w.RemoteAddr().String(), time.Now().UnixNano())

	defer func() {
		log.Printf("[%s - %s] closing websocket conn", ws.name, w.RemoteAddr().String())
		ws.b.DelSubscriber(host)
		w.Close()
	}()

	log.Printf("[%s - %s] accepting websocket conn", ws.name, w.RemoteAddr().String())

	r := make(chan *buffer.Event, recvBuffer)
	ws.b.AddSubscriber(host, r)

	for {
		select {
		case ev := <-r:
			if len(source) > 0 {
				if ev.Source != source {
					continue
				}
			}

			err := websocket.Message.Send(w, *ev.Text)
			if err != nil {
				log.Printf("[%s] error sending ws message: %v", w.RemoteAddr().String(), err.Error())
				return
			}
		}
	}
}
Example #20
0
func (l *listener) handler(ws *websocket.Conn) {
	l.lock.Lock()

	if !l.running {
		ws.Close()
		l.lock.Unlock()
		return
	}

	w := &wsPipe{ws: ws, addr: l.addr, proto: l.proto, open: true}
	w.iswss = l.iswss

	req := ws.Request()

	w.props = make(map[string]interface{})
	w.props[mangos.PropLocalAddr] = ws.LocalAddr()
	w.props[mangos.PropRemoteAddr], _ = net.ResolveTCPAddr("tcp", req.RemoteAddr)

	if l.iswss {
		w.props[mangos.PropTlsConnState] = *req.TLS
	}

	w.wg.Add(1)
	l.pending = append(l.pending, w)
	l.cv.Broadcast()
	l.lock.Unlock()

	// We must not return before the socket is closed, because
	// our caller will close the websocket on our return.
	w.wg.Wait()
}
Example #21
0
File: apps.go Project: jbuck/rack
func AppLogs(ws *websocket.Conn) error {
	defer ws.Close()

	app := mux.Vars(ws.Request())["app"]

	a, err := models.GetApp(app)

	if awsError(err) == "ValidationError" {
		return fmt.Errorf("no such app: %s", app)
	}

	if err != nil {
		return err
	}

	logs := make(chan []byte)
	done := make(chan bool)

	a.SubscribeLogs(logs, done)

	for data := range logs {
		ws.Write(data)
	}

	return nil
}
Example #22
0
func handleWss(wsconn *websocket.Conn) {
	p := Responder{nil, wsconn.Request(), time.Now()}
	serverIP := wsconn.Request().Header.Get("X-Server-IP")

	conn, err := net.Dial("tcp", serverIP)
	if err != nil {
		p.errorLog(http.StatusInternalServerError, "Error connecting to '%s': %s", serverIP, err.Error())
		wsconn.Close()
		return
	}
	defer conn.Close()
	defer wsconn.Close()

	wsconn.PayloadType = websocket.BinaryFrame

	t := &copySyncer{alive: true}

	go p.CopyR2W(t, conn, wsconn, serverIP+" ws2vnc")
	go p.CopyR2W(t, wsconn, conn, serverIP+" vnc2ws")

	p.errorLog(http.StatusOK, "websocket started: '%s'", serverIP)

	for t.IsAlive() {
		time.Sleep(100 * time.Millisecond)
	}

	p.errorLog(http.StatusOK, "websocket closed: '%s'", serverIP)
}
Example #23
0
func (c WebSockApp) AxisMovementWidgetWebSocket(user string, ws *websocket.Conn) revel.Result {
	revel.INFO.Printf("%s", "WS_AXIS_MOV request recieved")
	defer ws.Close()

	newmessages := make(chan string)
	//quit := make(chan struct{})
	go func() {
		var msg string
		err := websocket.Message.Receive(ws, &msg)
		if err != nil {
			close(newmessages)
			return
		}
		newmessages <- msg
	}()
	for {
		select {
		case msg := <-newmessages:
			//TODO:Change printf on cmds to virtual keyboard
			if strings.HasPrefix(msg, "X") {
				revel.INFO.Printf("%s", "X_AXIS cmd recieved")
			}
			if strings.HasPrefix(msg, "Y") {
				revel.INFO.Printf("%s", "Y_AXIS cmd recieved")
			}
			if strings.HasPrefix(msg, "Z") {
				revel.INFO.Printf("%s", "Z_AXIS cmd recieved")
			}
		}
	}
}
Example #24
0
func wsServer(ws *websocket.Conn) {
	var buf string
	defer func() {
		if err := ws.Close(); err != nil {
			log.Println("Websocket could not be closed", err.Error())
		} else {
			log.Println("Websocket closed")
		}
	}()
	//q := ws.Request().URL.Query()
	//name := q.Get("name")
	stopped := false
	ticker := time.Tick(time.Duration(1) * time.Second)
	for !stopped {
		select {
		case <-ticker:
			val := expvar.Get(metricsVar)
			if val == nil {
				buf = ""
			} else {
				buf = val.String()
			}
			_, err := ws.Write([]byte(buf))
			if err != nil {
				log.Printf("Websocket error: %s\n", err.Error())
				stopped = true
			}

		}
	}
}
Example #25
0
// HandleWS implements a websocket handler.
func (s *WatchServer) HandleWS(ws *websocket.Conn) {
	defer ws.Close()
	done := make(chan struct{})
	go wsstream.IgnoreReceives(ws, 0)

	var unknown runtime.Unknown
	internalEvent := &versioned.InternalEvent{}
	buf := &bytes.Buffer{}
	streamBuf := &bytes.Buffer{}
	ch := s.watching.ResultChan()
	for {
		select {
		case <-done:
			s.watching.Stop()
			return
		case event, ok := <-ch:
			if !ok {
				// End of results.
				return
			}
			obj := event.Object
			s.fixup(obj)
			if err := s.embeddedEncoder.Encode(obj, buf); err != nil {
				// unexpected error
				utilruntime.HandleError(fmt.Errorf("unable to encode watch object: %v", err))
				return
			}

			// ContentType is not required here because we are defaulting to the serializer
			// type
			unknown.Raw = buf.Bytes()
			event.Object = &unknown

			// the internal event will be versioned by the encoder
			*internalEvent = versioned.InternalEvent(event)
			if err := s.encoder.Encode(internalEvent, streamBuf); err != nil {
				// encoding error
				utilruntime.HandleError(fmt.Errorf("unable to encode event: %v", err))
				s.watching.Stop()
				return
			}
			if s.useTextFraming {
				if err := websocket.Message.Send(ws, streamBuf.String()); err != nil {
					// Client disconnect.
					s.watching.Stop()
					return
				}
			} else {
				if err := websocket.Message.Send(ws, streamBuf.Bytes()); err != nil {
					// Client disconnect.
					s.watching.Stop()
					return
				}
			}
			buf.Reset()
			streamBuf.Reset()
		}
	}
}
Example #26
0
func (this *DevWS) freeWS(ws *websocket.Conn) {
	this.lock.Lock()
	defer this.lock.Unlock()
	ws.Close()
	if this.ws == ws {
		this.isNeeded = false
	}
}
Example #27
0
func (a *Api) execContainer(ws *websocket.Conn) {
	qry := ws.Request().URL.Query()
	containerId := qry.Get("id")
	command := qry.Get("cmd")
	ttyWidth := qry.Get("w")
	ttyHeight := qry.Get("h")
	token := qry.Get("token")
	cmd := strings.Split(command, ",")

	if !a.manager.ValidateConsoleSessionToken(containerId, token) {
		ws.Write([]byte("unauthorized"))
		ws.Close()
		return
	}

	log.Debugf("starting exec session: container=%s cmd=%s", containerId, command)
	clientUrl := a.manager.DockerClient().URL

	execConfig := &dockerclient.ExecConfig{
		AttachStdin:  true,
		AttachStdout: true,
		AttachStderr: true,
		Tty:          true,
		Cmd:          cmd,
		Container:    containerId,
		Detach:       true,
	}

	execId, err := a.manager.DockerClient().ExecCreate(execConfig)
	if err != nil {
		log.Errorf("error calling exec: %s", err)
		return
	}

	if err := a.hijack(clientUrl.Host, "POST", "/exec/"+execId+"/start", true, ws, ws, ws, nil, nil); err != nil {
		log.Errorf("error during hijack: %s", err)
		return
	}

	// resize
	w, err := strconv.Atoi(ttyWidth)
	if err != nil {
		log.Error(err)
		return
	}

	h, err := strconv.Atoi(ttyHeight)
	if err != nil {
		log.Error(err)
		return
	}

	if err := a.manager.DockerClient().ExecResize(execId, w, h); err != nil {
		log.Errorf("error resizing exec tty: %s", err)
		return
	}

}
Example #28
0
File: log.go Project: gwmoura/yati
func addLogs(ws *websocket.Conn) {
	var err error
	defer func() {
		data := map[string]interface{}{}
		if err != nil {
			data["error"] = err.Error()
			log.Error(err.Error())
		} else {
			data["error"] = nil
		}
		msg, _ := json.Marshal(data)
		ws.Write(msg)
		ws.Close()
	}()
	req := ws.Request()
	t := context.GetAuthToken(req)
	if t == nil {
		err = fmt.Errorf("wslogs: no token")
		return
	}
	if t.GetAppName() != app.InternalAppName {
		err = fmt.Errorf("wslogs: invalid token app name: %q", t.GetAppName())
		return
	}
	dispatcher := app.NewlogDispatcher()
	scanner := bufio.NewScanner(ws)
	for scanner.Scan() {
		var entry app.Applog
		data := bytes.TrimSpace(scanner.Bytes())
		if len(data) == 0 {
			continue
		}
		err = json.Unmarshal(data, &entry)
		if err != nil {
			dispatcher.Stop()
			err = fmt.Errorf("wslogs: parsing log line %q: %s", string(data), err)
			return
		}
		err = dispatcher.Send(&entry)
		if err != nil {
			// Do not disconnect by returning here, dispatcher will already
			// retry db connection and we gain nothing by ending the WS
			// connection.
			log.Errorf("wslogs: error storing log: %s", err)
		}
	}
	err = dispatcher.Stop()
	if err != nil {
		err = fmt.Errorf("wslogs: error storing log: %s", err)
		return
	}
	err = scanner.Err()
	if err != nil {
		err = fmt.Errorf("wslogs: waiting for log data: %s", err)
		return
	}
}
Example #29
0
func addLogs(ws *websocket.Conn) {
	var err error
	defer func() {
		data := map[string]interface{}{}
		if err != nil {
			data["error"] = err.Error()
			log.Error(err.Error())
		} else {
			data["error"] = nil
		}
		msg, _ := json.Marshal(data)
		ws.Write(msg)
		ws.Close()
	}()
	req := ws.Request()
	t := context.GetAuthToken(req)
	if t == nil {
		err = fmt.Errorf("wslogs: no token")
		return
	}
	if t.GetAppName() != app.InternalAppName {
		err = fmt.Errorf("wslogs: invalid token app name: %q", t.GetAppName())
		return
	}
	logCh, errCh := app.LogReceiver()
	scanner := bufio.NewScanner(ws)
	for scanner.Scan() {
		var entry app.Applog
		data := bytes.TrimSpace(scanner.Bytes())
		if len(data) == 0 {
			continue
		}
		err = json.Unmarshal(data, &entry)
		if err != nil {
			close(logCh)
			err = fmt.Errorf("wslogs: parsing log line %q: %s", string(data), err)
			return
		}
		select {
		case logCh <- &entry:
		case err := <-errCh:
			close(logCh)
			err = fmt.Errorf("wslogs: storing log: %s", err)
			return
		}
	}
	close(logCh)
	err = scanner.Err()
	if err != nil {
		err = fmt.Errorf("wslogs: waiting for log data: %s", err)
		return
	}
	err = <-errCh
	if err != nil {
		err = fmt.Errorf("wslogs: storing log: %s", err)
	}
}
Example #30
0
// EchoServer contains the main server loop
func WsHandler(ws *websocket.Conn) {
	log.Printf("%v connected to server", ws.Request().RemoteAddr)
	addr := ws.Request().RemoteAddr

	// Cleanup
	defer func() {
		// TODO: remove conn from channel
		if err := ws.Close(); err != nil {
			log.Panicf("%v cleanup could not close connecteion: %v", addr, err.Error())
		}
	}()

	var data Request
	for {
		err := websocket.JSON.Receive(ws, &data)
		switch {
		case err == io.EOF:
			log.Printf("%v disconnected", addr)
			return
		default:
			panic(err.Error())
		case err == nil:
		}

		switch data.Command {
		case "":
			fmt.Printf("empty message\n")
		case "requestChannelId":
			log.Printf("%v requestChannelId", addr)
			channelId, err := generateChannelId()
			if err {
				log.Panicf("%v could not generate channel id", addr)
				return
			}
			connections[channelId] = []*websocket.Conn{}
			response := RequestChannelIdResponse{
				ChannelId: channelId,
			}
			websocket.JSON.Send(ws, response)
		case "connectChannel":
			log.Printf("%v connectChannel", addr)
			// TODO: disconnect from previous channel
			connections[data.Channel] = append(connections[data.Channel], ws)
		case "send":
			log.Printf("%v send", addr)
			/* Iterate all connections */
			for _, conn := range connections[data.Channel] {
				if conn != ws {
					websocket.JSON.Send(conn, data)
				}
			}
		default:
			log.Panicf("%v Unhandled message\n%v", addr, data)
		}
	}
}