Exemplo n.º 1
1
func webSocket(res http.ResponseWriter, req *http.Request) {
	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		CheckOrigin:     func(r *http.Request) bool { return true },
	}

	res.Header().Set("Access-Control-Allow-Origin", "*")

	conn, err := upgrader.Upgrade(res, req, nil)
	if err != nil {
		log.Printf("Not a web socket connection: %s \n", err)
		return
	}

	for {
		messageType, p, err := conn.ReadMessage()
		if err != nil {
			return
		}
		if err = conn.WriteMessage(messageType, p); err != nil {
			return
		}
	}
}
Exemplo n.º 2
0
func slashws(w http.ResponseWriter, req *http.Request) {
	// Upgrader.Upgrade() has Origin check if .CheckOrigin is nil
	upgrader := gorillawebsocket.Upgrader{}
	wsconn, err := upgrader.Upgrade(w, req, nil)
	if err != nil { // Upgrade() does http.Error() to the client
		return
	}

	// req.Method == "GET" asserted by the mux
	req.Form = nil // reset reused later .Form
	c := &conn{
		Conn:          wsconn,
		requestOrigin: req,
		receive:       make(chan *received, 2),
		push:          make(chan *pageUpdate, 2),
		full:          defaultClient(),
	}
	register <- c
	defer func() {
		unregister <- c
		c.Conn.Close()
	}()
	stop := make(chan struct{}, 1)
	go c.receiveLoop(stop) // read from the client
	c.updateLoop(stop)     // write to the client
}
Exemplo n.º 3
0
Arquivo: ws.go Projeto: vadv/ostent
func IndexWS(access *Access, errlog *log.Logger, minperiod flags.Period, w http.ResponseWriter, req *http.Request) {
	// Upgrader.Upgrade() has Origin check if .CheckOrigin is nil
	upgrader := gorillawebsocket.Upgrader{
		HandshakeTimeout: 5 * time.Second,
	}
	wsconn, err := upgrader.Upgrade(w, req, nil)
	if err != nil { // Upgrade() does http.Error() to the client
		return
	}

	// req.Method == "GET" asserted by the mux
	req.Form = nil // reset reused later .Form
	c := &conn{
		Conn: wsconn,

		requestOrigin: req,

		receive: make(chan *received, 2),
		pushch:  make(chan *IndexUpdate, 2),
		para:    params.NewParams(minperiod),
		access:  access,
	}
	Register <- c
	defer func() {
		unregister <- c
		c.Conn.Close()
	}()
	stop := make(chan struct{}, 1)
	go c.receiveLoop(stop)     // read from the client
	c.updateLoop(errlog, stop) // write to the client
}
Exemplo n.º 4
0
func Upgrade(res http.ResponseWriter, req *http.Request) {
	if req.Header["Origin"][0] != "http://localhost" {
		return
	}
	up := websocket.Upgrader{
		CheckOrigin: func(req *http.Request) bool {
			if req.Header["Origin"][0] != "http://localhost" {
				//	return false
				// gorilla stops the app if wrong origin...
			}
			return true
		},
	}
	conn, err := up.Upgrade(res, req, nil)
	if err != nil {
		log.Fatal(err)
	}
	go hub.Handle(conn)
	hub.H.Register <- &hub.Register{conn, time.Now().UnixNano()}
	r, err := json.Marshal(&hub.BroadcastMessage{
		0,
		"User connected",
	})
	if err != nil {
		log.Fatal(err)
	}
	hub.H.Broadcast <- &hub.Broadcast{
		conn,
		r,
		"default",
	}
}
Exemplo n.º 5
0
// Start the websocket server, each peer connecting to this websocket will be added as a connection to the dispatcher
func Start(d *Dispatcher, port int) {
	var upgrader = websocket.Upgrader{
		ReadBufferSize:  2048,
		WriteBufferSize: 2048,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		log.Debug("Connection received")
		conn, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Fatal(err)
		}

		defer conn.Close()

		startConnection(conn, d)
	})

	go http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
	log.Println(fmt.Sprintf("Websocket server started on port %d", port))
	select {}
}
Exemplo n.º 6
0
func (w *webserver) live(resp http.ResponseWriter, req *http.Request) {
	//get our feeder registered
	wsf := &liveWSFeeder{
		ch: make(chan namedBwSample, chanBufferSize),
	}
	id, err := w.lf.RegisterLiveFeeder(wsf)
	if err != nil {
		resp.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer w.lf.DeregisterLiveFeeder(id)

	//upgrade to a websocket
	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}
	conn, err := upgrader.Upgrade(resp, req, nil)
	if err != nil {
		return
	}
	defer conn.Close()

	//start feeding and relaying
	for s := range wsf.ch {
		if err := websocket.WriteJSON(conn, s); err != nil {
			break
		}
	}
}
Exemplo n.º 7
0
func main() {
	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	http.Handle("/", handlers.LoggingHandler(os.Stderr, http.FileServer(http.Dir("."))))
	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		conn, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Println(err)
			return
		}
		defer conn.Close()
		for {
			t, msg, err := conn.ReadMessage()
			if err != nil {
				log.Println(err)
				return
			}
			log.Println("Received:", string(msg))
			err = conn.WriteMessage(t, msg)
			if err != nil {
				log.Println(err)
				return
			}
		}
	})
	host := "localhost:3030"
	log.Printf("http://%v", host)
	log.Fatal(http.ListenAndServe(host, nil))
}
Exemplo n.º 8
0
func consoleHandler(w http.ResponseWriter, r *http.Request) {
	upgrader := websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println(err)
		return
	}
	go wsReadLoop(conn)
	defer conn.Close()

	lines, done, err := tailFile(fOptions.LogPath)
	if err != nil {
		log.Println(err)
		return
	}
	defer close(done)

	for line := range lines {
		err = conn.WriteMessage(websocket.TextMessage, append(line, '\n'))
		if err != nil {
			return
		}
	}
}
Exemplo n.º 9
0
// ListenAndServe will run a simple WS (HTTP) server.
// return listening error
func (s *Server) ListenAndServe(address string, path string) error {
	l, err := net.Listen("tcp", address)
	if err != nil {
		return err
	}
	s.listener = l

	mux := http.NewServeMux()
	mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
		var upgrader = websocket.Upgrader{
			ReadBufferSize:  s.readBufferSize,
			WriteBufferSize: s.writeBufferSize,
			CheckOrigin: func(r *http.Request) bool {
				return true
			},
		}

		conn, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Print("upgrade:", err)
			return
		}

		s.wsHandler.ServeWS(
			conn.UnderlyingConn(),
			newAbstractStream(conn),
			r.URL.Query(),
		)
	})
	s.httpHandler = mux

	go s.serve()

	return nil
}
Exemplo n.º 10
0
func (ws *webSocketRenderer) handler(w http.ResponseWriter, r *http.Request) {
	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	h := http.Header{}

	h["Sec-WebSocket-Protocol"] = []string{"nesrender"}
	conn, err := upgrader.Upgrade(w, r, h)

	if err != nil {
		panic("Unable to upgrade connection")
	}

	ws.conns = append(ws.conns, conn)

	for {
		t, _, err := conn.ReadMessage()
		if err != nil {
			break
		}

		if t == websocket.CloseMessage {
			break
		}
	}
}
Exemplo n.º 11
0
func startMockAcsServer(t *testing.T, closeWS <-chan bool) (*httptest.Server, chan<- string, <-chan string, <-chan error, error) {
	serverChan := make(chan string)
	requestsChan := make(chan string)
	errChan := make(chan error)

	upgrader := websocket.Upgrader{ReadBufferSize: 1024, WriteBufferSize: 1024}
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ws, err := upgrader.Upgrade(w, r, nil)
		go func() {
			<-closeWS
			ws.Close()
		}()
		if err != nil {
			errChan <- err
		}
		go func() {
			_, msg, err := ws.ReadMessage()
			if err != nil {
				errChan <- err
			} else {
				requestsChan <- string(msg)
			}
		}()
		for str := range serverChan {
			err := ws.WriteMessage(websocket.TextMessage, []byte(str))
			if err != nil {
				errChan <- err
			}
		}
	})

	server := httptest.NewTLSServer(handler)
	return server, serverChan, requestsChan, errChan, nil
}
Exemplo n.º 12
0
func Handle(w http.ResponseWriter, r *http.Request) {
	upgrader := websocket.Upgrader{
		CheckOrigin: func(req *http.Request) bool {
			if req.Host == "127.0.0.1:9090" {
				return true
			} else {
				return false
			}
		},
	}
	var err error
	WebSocketConn, err = upgrader.Upgrade(w, r, nil)
	if err != nil {
		utils.Errorf("Error upgrade http: %s", err.Error())
		return
	}
	for {
		mt, bytes, err := WebSocketConn.ReadMessage()
		if err != nil {
			utils.Errorf("Error read message: %v", err)
			WebSocketConn.Close()
			WebSocketConn = nil
			return
		}
		utils.Debugf("Client msg received: %d, %s", mt, string(bytes))
	}
}
func (f *FakeFirehose) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	f.lock.Lock()
	defer f.lock.Unlock()

	f.lastAuthorization = r.Header.Get("Authorization")
	f.requested = true

	if f.lastAuthorization != f.validToken {
		log.Printf("Bad token passed to firehose: %s", f.lastAuthorization)
		rw.WriteHeader(403)
		r.Body.Close()
		return
	}

	upgrader := websocket.Upgrader{
		CheckOrigin: func(*http.Request) bool { return true },
	}

	ws, _ := upgrader.Upgrade(rw, r, nil)

	defer ws.Close()
	defer ws.WriteControl(websocket.CloseMessage, f.closeMessage, time.Time{})

	for _, envelope := range f.events {
		buffer, _ := proto.Marshal(&envelope)
		err := ws.WriteMessage(websocket.BinaryMessage, buffer)
		if err != nil {
			panic(err)
		}
	}
	f.wg.Wait()
}
Exemplo n.º 14
0
func echo(w http.ResponseWriter, r *http.Request) {

	// Upgrade from http to websocket protocol
	upgrader := websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}

	c, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		panic(err)
	}
	defer c.Close()
	for {
		mt, message, err := c.ReadMessage()

		if err != nil {
			panic(err)
		}
		fmt.Printf("Received message: %s\n", message)
		err = c.WriteMessage(mt, message)
		if err != nil {
			panic(err)
		}
	}
}
Exemplo n.º 15
0
func main() {
	upgrader := websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		id, err := authentication.AuthenticateRequest(r.FormValue("AccessToken"))
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}

		if id == -1 {
			http.Error(w, "", 401)
			return
		}

		conn, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Fatal(err)
		}

		c := client.New(id, conn)
		router.AddClientChan <- c
		go c.Run()
	})

	fmt.Println("listening on 8080")
	http.ListenAndServe(":8080", nil)
}
Exemplo n.º 16
0
func WSServer(w http.ResponseWriter, req *http.Request) {
	var upgrader = websocket.Upgrader{
		ReadBufferSize:  64,
		WriteBufferSize: 64,
	}
	conn, err := upgrader.Upgrade(w, req, nil)
	if err != nil {
		fmt.Println("ERROR:" + err.Error())
		return
	}
	for {
		messageType, r, err := conn.NextReader()
		reader := bufio.NewReader(r)
		b, err := reader.ReadBytes('\n')

		response := []byte("ECHO FROM " + servername + ":" + string(b))
		if err != nil {
			fmt.Println("ERROR:" + err.Error())
			return
		}
		// w, err := conn.NextWriter(messageType)
		// if err != nil {
		// 	fmt.Println("ERROR:"+err.Error())
		//    return
		// }
		if err := conn.WriteMessage(messageType, response); err != nil {
			fmt.Println("ERROR:" + err.Error())
			return
		}
	}
}
Exemplo n.º 17
0
func GetConnection(rw http.ResponseWriter, req *http.Request) (*connection, error) {
	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	upgrader.CheckOrigin = func(r *http.Request) bool {
		// allow all connections by default
		return true
	}

	conn := &connection{}

	for _, v := range req.Header["Connection"] {
		for _, i := range strings.Split(v, ",") {
			if strings.EqualFold(strings.TrimSpace(i), "upgrade") {
				webConn, err := upgrader.Upgrade(rw, req, nil)
				if err != nil {
					return nil, err
				}

				conn.webConn = webConn
				return conn, nil
			}
		}
	}

	conn.rw = rw
	return conn, nil
}
Exemplo n.º 18
0
func wsHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("wshandler")
	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	conn, err := upgrader.Upgrade(w, r, nil)

	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	defer conn.Close()
	if err != nil {
		log.Println(err)
		return
	}

	for {
		messageType, message, err := conn.ReadMessage()
		if err != nil {
			return
		}
		log.Print(message)

		err = conn.WriteMessage(messageType, []byte(strings.Join(getdrives(), ",")))
		if err != nil {
			return
		}
	}
}
func fakeFirehoseHandler(rw http.ResponseWriter, r *http.Request) {
	defer GinkgoRecover()
	authorization := r.Header.Get("Authorization")

	if authorization != "bearer good-token" {
		log.Printf("Bad token passed to firehose: %s", authorization)
		rw.WriteHeader(403)
		r.Body.Close()
		return
	}

	upgrader := websocket.Upgrader{
		CheckOrigin: func(*http.Request) bool { return true },
	}

	ws, _ := upgrader.Upgrade(rw, r, nil)

	defer ws.Close()
	defer ws.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Time{})

	for envelope := range fakeFirehoseInputChan {
		buffer, err := proto.Marshal(envelope)
		Expect(err).NotTo(HaveOccurred())
		err = ws.WriteMessage(websocket.BinaryMessage, buffer)
		Expect(err).NotTo(HaveOccurred())
	}
}
Exemplo n.º 20
0
// NewSockets returns a new websocket port
func NewSockets(upgrader *websocket.Upgrader, headers http.Header, hs SocketHandler) FlatChains {
	return NewFlatChain(func(c *Context, nx NextHandler) {

		if headers != nil {
			origin, ok := c.Req.Header["Origin"]

			if ok {
				headers.Set("Access-Control-Allow-Credentials", "true")
				headers.Set("Access-Control-Allow-Origin", strings.Join(origin, ";"))
			} else {
				headers.Set("Access-Control-Allow-Origin", "*")
			}
		}

		conn, err := upgrader.Upgrade(c.Res, c.Req, headers)

		if err != nil {
			return
		}

		flux.GoDefer(fmt.Sprintf("WebSocketPort.Handler"), func() {
			hs(NewSocketWorker(&Websocket{
				Conn: conn,
				Ctx:  c,
			}))
			nx(c)
		})
	})
}
Exemplo n.º 21
0
func (t _websocket_example_handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	//ServeHTTP(ResponseWriter, *Request)
	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	wsConn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		fmt.Println(err)
		return
	}

	go func() {
		time.Sleep(100)

		if err := wsConn.Close(); err != nil {
			fmt.Printf("close error %s", err.Error())
			return
		}
	}()

	for i := 0; i < 11; i++ {
		fmt.Printf("begin read count %d\n", i)
		_, _, err := wsConn.ReadMessage()
		if err != nil {
			fmt.Println(err)
			return
		} else {
			fmt.Printf("read count %d\n", i)
		}
	}
}
Exemplo n.º 22
0
func main() {
	prog := path.Base(os.Args[0])
	log.SetFlags(0)
	log.SetPrefix(prog + ": ")

	flag.Usage = Usage
	flag.Parse()

	if flag.NArg() > 0 {
		Usage()
		os.Exit(1)
	}

	log.Printf("Serving at http://%s:%d/", *host, *port)

	chat := Chat{}
	chat.broadcast = topic.New()
	chat.registry = birpc.NewRegistry()
	chat.registry.RegisterService(&chat)
	defer close(chat.broadcast.Broadcast)
	upgrader := websocket.Upgrader{}

	serve := func(w http.ResponseWriter, req *http.Request) {
		ws, err := upgrader.Upgrade(w, req, nil)
		if err != nil {
			log.Println(err)
			return
		}
		endpoint := wetsock.NewEndpoint(chat.registry, ws)
		messages := make(chan interface{}, 10)
		chat.broadcast.Register(messages)
		go func() {
			defer chat.broadcast.Unregister(messages)
			for i := range messages {
				msg := i.(Outgoing)
				// Fire-and-forget.
				// TODO use .Notify when it exists
				_ = endpoint.Go("Chat.Message", msg, nil, nil)
			}
			// broadcast topic kicked us out for being too slow;
			// probably a hung TCP connection. let client
			// re-establish.
			log.Printf("Kicking slow client: %v", ws.RemoteAddr())
			ws.Close()
		}()

		if err := endpoint.Serve(); err != nil {
			log.Printf("websocket error from %v: %v", ws.RemoteAddr(), err)
		}
	}

	http.HandleFunc("/sock", serve)
	http.Handle("/", http.HandlerFunc(index))
	addr := fmt.Sprintf("%s:%d", *host, *port)
	err := http.ListenAndServe(addr, nil)
	if err != nil {
		log.Fatal(err)
	}
}
Exemplo n.º 23
0
func (s *WSServer) serveMessages(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
	// if X-Host-ID specified avoid having twice the same ID
	hostID := r.Header.Get("X-Host-ID")
	if hostID != "" {
		s.RLock()
		for c := range s.clients {
			if c.host == hostID {
				logging.GetLogger().Errorf("host_id error, connection from %s(%s) conflicts with another one", r.RemoteAddr, hostID)
				w.WriteHeader(http.StatusConflict)
				s.RUnlock()
				return
			}
		}
		s.RUnlock()
	}

	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	conn, err := upgrader.Upgrade(w, &r.Request, nil)
	if err != nil {
		return
	}

	c := &WSClient{
		read:   make(chan []byte, maxMessages),
		send:   make(chan []byte, maxMessages),
		conn:   conn,
		server: s,
		host:   hostID,
		kind:   r.Header.Get("X-Client-Type"),
	}
	logging.GetLogger().Infof("New WebSocket Connection from %s : URI path %s", conn.RemoteAddr().String(), r.URL.Path)

	s.register <- c

	var wg sync.WaitGroup
	wg.Add(2)

	quit := make(chan struct{})

	go c.writePump(&wg, quit)
	go c.processMessages(&wg, quit)

	c.readPump()

	quit <- struct{}{}
	quit <- struct{}{}

	close(c.read)
	close(c.send)

	wg.Wait()
}
Exemplo n.º 24
0
// State opens up a push notification based state differential protocol. After
// a client connects to this endpoint, it will constantly receive state updates
// whenever a change occurs. The endpoint does not accept any inbound data apart
// from ping/pong messages to ensure the dashboard is still active.
func (server *stateServer) State(w http.ResponseWriter, r *http.Request) {
	// Define the WebSocket protocol details and open the persistent connection
	var upgrader = websocket.Upgrader{
		ReadBufferSize:  65536,
		WriteBufferSize: 65536,
	}
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log15.Error("Failed to upgrade connection to web sockets", "error", err)
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	defer conn.Close()

	// Create a contextual logger for this connection
	session := atomic.AddUint32(&server.sessions, 1)
	logger := log15.New("session", session)

	logger.Debug("New dashboard connection")
	defer logger.Debug("Dashboard connection closed")

	// Lock the state for updates and stream out the current one
	server.lock.Lock()

	message, err := jsonMarshalLowercase(server.state)
	if err != nil {
		logger.Crit("Failed to serialize initial state", "error", err)
		server.lock.Unlock()
		return
	}
	if err := conn.WriteMessage(websocket.TextMessage, message); err != nil {
		// Tear down the connection if initial send fails
		logger.Warn("Failed to send initial state", "error", err)
		server.lock.Unlock()
		return
	}
	// Otherwise register the connection for update and ensure it's cleaned up
	logger.Debug("Initial state sent, subscribing to diffs")
	server.conns[session] = conn
	defer func() {
		server.lock.Lock()
		defer server.lock.Unlock()

		delete(server.conns, session)
	}()
	// Updates can proceed to all sessions
	server.lock.Unlock()

	// Keep reading messages until the client closes the connection
	for {
		// This is a push only endpoint, dump whatever the client sends
		if _, _, err := conn.NextReader(); err != nil {
			return
		}
	}
}
Exemplo n.º 25
0
func main() {
	flag.Parse()

	go func() {
		for {
			err := SerialWaitSignal()
			if err != nil {
				log.Error(err)
				continue
			}
			data, err := SerialReadFrame()
			if err != nil {
				log.Error(err)
				continue
			}
			pm10 := bigEndian(data[0], data[1])
			pm25 := bigEndian(data[2], data[3])
			pm100 := bigEndian(data[4], data[5])
			log.Infof("PM1.0: %d, PM2.5: %d, PM10: %d", pm10, pm25, pm100)

			atomic.StoreInt32(&currentPM25, int32(pm25))
			atomic.StoreInt32(&currentPM100, int32(pm100))
		}
	}()

	router := httprouter.New()
	k := kami.New(nil, router).With(CORS)

	k.Get("/realtime", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		upg := websocket.Upgrader{
			CheckOrigin: func(r *http.Request) bool {
				// accept any origin
				return true
			},
		}
		ws, err := upg.Upgrade(w, r, nil)
		if err != nil {
			log.Warnf("Error to upgrade: %s", err.Error())
			http.Error(w, "internal error", http.StatusInternalServerError)
			return
		}
		go WSHandler(ws)
	})

	k.Get("/", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "/static/viewer.html", http.StatusMovedPermanently)
	})

	http.Handle("/", k.Handler())

	fs := http.FileServer(http.Dir("static"))
	http.Handle("/static/", http.StripPrefix("/static/", fs))

	log.Infof("Listen at %s", *flagAPI)
	panic(http.ListenAndServe(*flagAPI, http.DefaultServeMux))
}
Exemplo n.º 26
0
//initServeSocket takes in a Broadcaster and initializes a serveSocket net/http
//handler function that upgrades the request to create a new WebSocket Conn,
//which then is used added to the Broadcaster.
func initServeSocket(b Broadcaster) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		up := ws.Upgrader{}
		conn, err := up.Upgrade(w, r, nil)
		if err != nil {
			return
		}

		b.AddConn(conn)
	}
}
Exemplo n.º 27
0
func (w *WebsocketController) createWebsocketConnection(writer http.ResponseWriter, req *http.Request) *websocket.Conn {
	upgrader := websocket.Upgrader{}
	connection, err := upgrader.Upgrade(writer, req, nil)
	if err != nil {
		panic(err)
	}

	w.logger.Println("connection opened")

	return connection
}
Exemplo n.º 28
0
func (e eventResponse) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	upgrader := websocket.Upgrader{}

	c, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		w.Write([]byte(fmt.Sprintf("websocket upgrade failed: %v", err)))
		return
	}

	s := notifications.NewSubscriber(c, r)
	e.h.Subscribe(s)
}
Exemplo n.º 29
0
func Start(orientChan chan orient.Event, shootChan chan shoot.Event) {
	port := 4242

	var upgrader = websocket.Upgrader{
		ReadBufferSize:  2048,
		WriteBufferSize: 2048,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}

	http.HandleFunc("/control", func(w http.ResponseWriter, r *http.Request) {
		log.Debug("Connection received")
		conn, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Fatal(err)
		}

		defer conn.Close()

		for {
			messageType, reader, err := conn.NextReader()
			if err != nil {
				log.Println(err)
				return
			}
			if messageType == websocket.TextMessage {
				packet := Packet{}
				decoder := json.NewDecoder(reader)
				if err := decoder.Decode(&packet); err != nil {
					log.Warning(err)
					continue
				}

				switch packet.Type {
				case "orient":
					event := orient.Event{}
					mapstructure.Decode(packet.Payload, &event)
					orientChan <- event
				case "shoot":
					event := shoot.Event{}
					mapstructure.Decode(packet.Payload, &event)
					shootChan <- event
				default:
					log.Info("Oops unknown packet: ", packet)
				}
			}
		}
	})

	go http.ListenAndServe(fmt.Sprintf("0.0.0.0:%d", port), nil)
	log.Infof("Websocket server started on port %d", port)
}
Exemplo n.º 30
0
Arquivo: serve.go Projeto: gnawux/ink
func Websocket(ctx *ink.Context) {
	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}
	if c, err := upgrader.Upgrade(ctx.Res, ctx.Req, nil); err != nil {
		Fatal(err)
	} else {
		conn = c
	}
	ctx.Stop()
}