예제 #1
0
func main() {
	http.Handle("/echo", websocket.Handler(EchoServer))
	http.Handle("/lobby", websocket.Handler(LobbyServer))
	http.Handle("/", http.FileServer(http.Dir("/tmp")))
	fmt.Println("Listening on:", listenAddress)
	if err := http.ListenAndServe(listenAddress, nil); err != nil {
		panic("ListenAndServe: " + err.String())
	}
}
예제 #2
0
// This example demonstrates a trivial echo server.
func ExampleHandler() {
	http.Handle("/echo", websocket.Handler(EchoServer))
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		panic("ListenAndServe: " + err.Error())
	}
}
예제 #3
0
파일: twocloud.go 프로젝트: klinster/Bessie
func main() {
	flag.Parse()
	go hub()
	var err error
	session, err = mgo.Mongo("localhost")

	if err != nil {
		panic("main > Mongo: " + err.Error())
	}
	defer session.Close()
	pfx := "/static/"
	h := http.StripPrefix(pfx, http.FileServer(http.Dir("../static/")))
	http.Handle(pfx, h) // It is absurd I had to work that hard to serve static files. Let's shove them on AWS or something and forget about it
	http.HandleFunc("/tickle", doTickle)
	http.HandleFunc("/keys", viewKeys)
	http.HandleFunc("/keys/add", addKey)
	http.HandleFunc("/keys/check", checkKey)
	http.HandleFunc("/links/send", sendLink)
	http.HandleFunc("/register", registerHandler)
	http.HandleFunc("/openid/callback", openID)
	http.HandleFunc("/openid/callback/chrome", openID)
	http.HandleFunc("/users/validate", validateUser)
	http.HandleFunc("/logout", doLogout)
	http.HandleFunc("/login", doLogin)
	http.HandleFunc("/links/", linksList)
	http.HandleFunc("/", rootHandler)
	http.Handle("/ws", websocket.Handler(wsHandler))
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
// Accepts a http connection & request pair. It upgrades the connection and calls
// proceed if succesfull.
//
// TODO: Remove the ugly channels and timeouts. They should not be needed!
func (s *websocketSocket) accept(w http.ResponseWriter, req *http.Request, proceed func()) (err os.Error) {
	if s.connected {
		return ErrConnected
	}

	f := func(ws *websocket.Conn) {
		err = nil
		ws.SetReadTimeout(s.t.rtimeout)
		ws.SetWriteTimeout(s.t.wtimeout)
		s.connected = true
		s.ws = ws
		s.close = make(chan byte)
		defer close(s.close)

		proceed()

		// must block until closed
		<-s.close
	}

	err = errWebsocketHandshake
	if _, ok := req.Header["Sec-Websocket-Key1"]; ok {
		websocket.Handler(f).ServeHTTP(w, req)
	} else {
		websocket.Draft75Handler(f).ServeHTTP(w, req)
	}

	return
}
예제 #5
0
// We export a single function, which creates a page controlled by a
// single websocket.  It's quite primitive, and yet quite easy to use!
func HandleChans(url string, handler func(evts <-chan string, pages chan<- string, done <-chan os.Error)) {
	myh := func(ws *websocket.Conn) {
		evts := make(chan string)
		pages := make(chan string)
		done := make(chan os.Error)
		go handler(evts, pages, done)
		go func() {
			r := bufio.NewReader(ws)
			for {
				x, err := r.ReadString('\n')
				if err == nil {
					evts <- x[:len(x)-1]
				} else {
					done <- os.NewError("Error from r.ReadString: " + err.String())
					return
				}
			}
		}()
		for {
			x := <-pages
			_, err := fmt.Fprintln(ws, x)
			if err != nil {
				done <- os.NewError("Error in fmt.Fprintln: " + err.String())
				return
			}
		}
	}
	http.Handle(path.Join(url, "socket"), websocket.Handler(myh))

	skeleton := func(c http.ResponseWriter, req *http.Request) {
		c.SetHeader("Content-Type", "text/html")
		fmt.Fprintln(c, skeletonpage(req))
	}
	http.HandleFunc(url, skeleton)
}
예제 #6
0
파일: socket.go 프로젝트: taysom/tau
func main() {
	http.Handle("/echo", websocket.Handler(EchoServer))
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		panic("ListenAndServe: " + err.String())
	}
}
예제 #7
0
파일: listeners.go 프로젝트: ahf/ircd-novo
func (this *WebSocketListener) Listen() {
	http.Serve(this.listener, websocket.Handler(func(connection *websocket.Conn) {
		// The HTTP package creates the goroutine itself. No need for us to do it.
		// Set the RemoteAddr here because of Go Bug #1636
		this.ConnectionHandler(this.ircd, connection, connection.Request.RemoteAddr)
	}))
}
예제 #8
0
파일: web.go 프로젝트: Br3nda/doozerd
func evServer(w http.ResponseWriter, r *http.Request) {
	wevs := make(chan store.Event)
	path := r.URL.Path[len("/$events"):]

	glob, err := store.CompileGlob(path + "**")
	if err != nil {
		w.WriteHeader(400)
		return
	}

	rev, _ := Store.Snap()

	go func() {
		walk(path, Store, wevs)
		for {
			ch, err := Store.Wait(glob, rev+1)
			if err != nil {
				break
			}
			ev, ok := <-ch
			if !ok {
				break
			}
			wevs <- ev
			rev = ev.Rev
		}
		close(wevs)
	}()

	websocket.Handler(func(ws *websocket.Conn) {
		send(ws, path, wevs)
		ws.Close()
	}).ServeHTTP(w, r)
}
예제 #9
0
파일: websocket.go 프로젝트: mattn/gui
// We export a single function, which creates a page controlled by a
// single websocket.  It's quite primitive, and yet quite easy to use!
func HandleSeparate(url string, hh func() Handler) {
	myh := func(ws *websocket.Conn) {
		h := hh()
		h.AddSend(func(p string) { fmt.Fprintln(ws, p) })
		fmt.Fprintln(ws, "start")
		r := bufio.NewReader(ws)
		for {
			x, err := r.ReadString('\n')
			if err == nil {
				h.Handle(x[:len(x)-1])
			} else {
				h.Done(os.NewError("Error from r.ReadString: " + err.String()))
				return
			}
		}
	}
	http.Handle(path.Join(url, "socket"), websocket.Handler(myh))

	skeleton := func(c http.ResponseWriter, req *http.Request) {
		c.Header().Set("Content-Type", "text/html")
		fmt.Fprintln(c, skeletonpage(req))
	}
	http.HandleFunc(url, skeleton)

}
예제 #10
0
func Start(ch *chan int, st *State.State) {
	world = *ch
	state = st
	go http.ListenAndServe(":25560", http.HandlerFunc(httpServe))
	go http.ListenAndServe(":25561", websocket.Handler(wssServe))
	//	os.ForkExec("http://localhost:25560/index.oc", []string{}, []string{}, "", []*os.File{})
}
예제 #11
0
func makeWsConnHandler(core *WsHttpCore) http.Handler {
	return websocket.Handler(func(c *websocket.Conn) {
		id := core.RegisterConn(c)
		log.Println("send connid", id)
		c.Write([]byte(id))
		// chanWriter := core.MakeChanWriter(id)
		jsChan := core.MakeJsonChan(id)
		for {
			var data WsHttpMsg
			err := websocket.JSON.Receive(c, &data)
			if err != nil {
				log.Println("Error reading, socket closed")
				break
			}
			log.Println("recvd.", id, data)

			jsChan <- &data
		}
		// _,err := io.Copy(chanWriter,c)
		// if err != nil {
		// 	log.Println("wshttp.conn.error",id,err)
		// }
		// chanWriter.Close()
		core.RemoveConn(id)
	})
}
예제 #12
0
func main() {
	flag.Parse()
	go hub()
	http.Handle("/broadcast", websocket.Handler(clientHandler))
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Exit("ListenAndServe:", err)
	}
}
예제 #13
0
func main() {
	http.Handle("/", websocket.Handler(Echo))
	http.Handle("/send", http.HandlerFunc(myHandler))

	if err := http.ListenAndServe("localhost:1234", nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
예제 #14
0
파일: flicker.go 프로젝트: ngd/chrome-bench
func webSocketProtocolSwitch(c http.ResponseWriter, req *http.Request) {
	// Handle old and new versions of protocol.
	if _, found := req.Header["Sec-Websocket-Key1"]; found {
		websocket.Handler(clientHandler).ServeHTTP(c, req)
	} else {
		websocket.Draft75Handler(clientHandler).ServeHTTP(c, req)
	}
}
예제 #15
0
func main() {
	http.HandleFunc("/", NotFoundServer)
	http.HandleFunc("/test", HtmlResponseServer)
	http.Handle("/ws", websocket.Handler(WebSocketServer))
	err := http.ListenAndServe(":8888", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
예제 #16
0
func main() {
	log.Println("Starting Server...")

	http.Handle("/ws", websocket.Handler(handler))

	err := http.ListenAndServe(":8080", nil)

	if err != nil {
		panic("ListenAndServe: " + err.String())
	}
}
예제 #17
0
파일: server.go 프로젝트: taysom/tau
func main() {
	log.Println("Starting Server...")

	http.Handle("/echo", websocket.Handler(echoServer))
	//	http.Handle("/ws", websocket.Handler(handler));
	//	http.HandleFunc("/", handlerSimple);

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		panic("ListenAndServe: " + err.String())
	}
}
예제 #18
0
// newWebsocketHandler creates a new handler for websocket connections.
//
// vhost    - The related vhost.
// endpoint - The parent websocket endpoint.
//
// Returns new handler.
func newWebsocketHandler(vhost *Vhost, endpoint *WebsocketEndpoint) (h *websocketHandler) {
	h = &websocketHandler{
		vhost:    vhost,
		alive:    true,
		endpoint: endpoint,
		conns:    make(map[string]*WebsocketConnection),
	}
	h.handler = websocket.Handler(func(ws *websocket.Conn) {
		h.handle(ws)
	})
	return h
}
예제 #19
0
파일: main.go 프로젝트: heweitykc/ball
func main() {
	fmt.Println("begin")
	http.Handle("/", http.FileServer(http.Dir("."))) // <-- note this line

	http.Handle("/socket", websocket.Handler(Echo))

	if err := http.ListenAndServe(":1234", nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}

	fmt.Println("end")
}
예제 #20
0
func main() {
	data, err := ioutil.ReadFile("log")
	str := string(data)
	lines = strings.Split(str, "\n")

	http.Handle("/", websocket.Handler(Handle))
	fmt.Println("Handling.")
	err = http.ListenAndServe(":3654", nil)
	if err != nil {
		fmt.Println("ListenAndServe failed.")
		fmt.Println(err)
	}
}
예제 #21
0
파일: server.go 프로젝트: egonelbre/sivq
/*
 * Start server
 */
func main() {
	runtime.GOMAXPROCS(4)
	fmt.Println("Server started.")

	go hub()

	http.HandleFunc("/", errorHandler(indexHandler))
	http.HandleFunc("/upload/", uploadErrorHandler(uploadHandler))
	http.HandleFunc("/static/", errorHandler(staticHandler))
	http.HandleFunc("/img/", errorHandler(imgHandler))
	http.HandleFunc("/saveVector", uploadErrorHandler(saveVectorHandler))
	http.Handle("/process", websocket.Handler(clientHandler))
	http.ListenAndServe(":8080", nil)
}
예제 #22
0
파일: server.go 프로젝트: tonyfabeen/mirage
func (server *Server) Start() {
	var config = new(config.Config)
	ok := config.Parse()

	if ok {
		for key, channel := range config.Channels {
			fmt.Printf("K %s", key)
			http.Handle("/"+channel, websocket.Handler(ChannelHandler))
		}
		err := http.ListenAndServe(":"+config.Port, nil)
		if err != nil {
			panic("ListenAndServe: ", err.String())
		}
	}
}
예제 #23
0
파일: webchat.go 프로젝트: natelong/webchat
func main() {
	go pubHub()
	go subHub()

	http.HandleFunc("/favicon.ico", favicon)
	http.HandleFunc("/js/", serveStaticFile)
	http.HandleFunc("/css/", serveStaticFile)
	http.HandleFunc("/img/", serveStaticFile)
	http.HandleFunc("/", serveIndex)

	http.Handle("/chat", websocket.Handler(doEventStream))

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("ListenAndServe: %s", err)
	}
}
예제 #24
0
func main() {
	log.Println("Starting up")

	flag.Parse()
	streamHost = fmt.Sprintf("scribe-%s.local.yelpcorp.com:3535", *aggregator)
	log.Println("Connecting to ", streamHost)

	go listenTCPClients()

	http.Handle("/", http.HandlerFunc(ServePage))
	http.Handle("/lookup", http.HandlerFunc(ServeDataItemPage))
	http.Handle("/ws", websocket.Handler(ServeWS))

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		panic("ListenAndServe: " + err.String())
	}
}
예제 #25
0
func main() {
	go pubHub()
	go subHub()

	http.HandleFunc("/favicon.ico", favicon)
	http.HandleFunc("/api/search", doSearch)
	http.HandleFunc("/api/getPlaybackToken", doPlaybackToken)
	http.HandleFunc("/api/", serveApiIndex)
	http.HandleFunc("/js/", serveStaticFile)
	http.HandleFunc("/css/", serveStaticFile)
	http.HandleFunc("/", serveIndex)

	http.Handle("/event", websocket.Handler(doEventStream))

	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err.String())
	}
}
예제 #26
0
파일: web.go 프로젝트: andradeandrey/doozer
func evServer(w http.ResponseWriter, r *http.Request) {
	wevs := make(chan store.Event)
	logger := util.NewLogger(w.RemoteAddr())
	path := r.URL.Path[len(evPrefix):]
	logger.Println("new", path)

	evs := Store.Watch(path + "**")

	// TODO convert store.Snapshot to json and use that
	go func() {
		walk(path, Store, wevs)
		close(wevs)
	}()

	websocket.Handler(func(ws *websocket.Conn) {
		send(ws, path, wevs, logger)
		send(ws, path, evs, logger)
		ws.Close()
	}).ServeHTTP(w, r)
}
예제 #27
0
func StartUp(redis_host string, redis_db, port int, ready chan bool) {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	router := NewRouter(redis_host, redis_db)
	go router.Route()
	log.Println("router routing")
	websocketHandler := websocket.Handler(func(c *websocket.Conn) {
		router.HandleWebsocket(c)
		c.Close()
	})
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		websocketHandler.ServeHTTP(w, r)
	})
	log.Printf("listening on port %d", port)
	if ready != nil {
		ready <- true
	}
	err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
	if err != nil {
		log.Panicln(err)
	}
}
예제 #28
0
func main() {
	c := make(chan int)
	address := ":" + getenv("PORT", "8080")

	fmt.Printf("Address: %s\n", address)

	go func() {
		http.Handle("/echo", websocket.Handler(EchoServer))
		error := http.ListenAndServe(address, nil)
		if error != nil {
			panic("ListenAndServe: " + error.String())
		}
		c <- 0
	}()

	go func() {
		url := "ws://localhost" + address + "/echo"
		ws, error := websocket.Dial(url, "", "http://localhost/")
		if error != nil {
			panic("Dial:" + error.String())
		}

		if _, error := ws.Write([]byte("Hello world")); error != nil {
			panic("Write: " + error.String())
		}

		var msg = make([]byte, 16384)
		n, error := ws.Read(msg)
		if error != nil {
			panic("Read: " + error.String())
		}

		fmt.Printf("%s\n", msg[0:n])
	}()

	/* Rough equivalent to 'thread.join' waiting for the server to terminate, if
	ever */
	<-c
}
예제 #29
0
func main() {
	// Parse args
	flag.IntVar(&http_port, "port", 3100, "port to listen on for http")
	flag.Parse()

	// Prep channel list
	ws_channels = list.New()

	var auth = new(account)
	// read config file
	if confData, err := ioutil.ReadFile("../twitter/account.json"); err == nil {
		if err := json.Unmarshal(confData, auth); err != nil {
			fmt.Println("Error parsing config file:", err)
		}
	} else {
		fmt.Println("Error reading config file:", err)
		return
	}

	// print stream
	if t, err := twitter.NewStream(auth.Username, auth.Password); err == nil {
		// Start processing events
		go process(t)

		// Start server
		http.HandleFunc("/", RootServer)
		http.Handle("/events", websocket.Handler(SocketServer))
		err := http.ListenAndServe(fmt.Sprintf(":%v", http_port), nil)
		if err != nil {
			fmt.Println("ListenAndServe: ", err.String())
		}

	} else {
		fmt.Println(err)
	}
}
예제 #30
0
파일: web.go 프로젝트: kr/doozerd
func evServer(w http.ResponseWriter, r *http.Request) {
	wevs := make(chan store.Event)
	path := r.URL.Path[len("/$events"):]

	glob, err := store.CompileGlob(path + "**")
	if err != nil {
		w.WriteHeader(400)
		return
	}

	wt := store.NewWatch(Store, glob)

	go func() {
		walk(path, Store, wevs)
		close(wevs)
	}()

	websocket.Handler(func(ws *websocket.Conn) {
		send(ws, path, wevs)
		send(ws, path, wt.C)
		wt.Stop()
		ws.Close()
	}).ServeHTTP(w, r)
}