コード例 #1
1
func http() {
	server := martini.Classic()

	server.Use(martini.Static("public", martini.StaticOptions{
		Prefix: "public",
	}))

	server.Use(martini.Static("bower_components", martini.StaticOptions{
		Prefix: "bower_components",
	}))

	server.Use(render.Renderer(render.Options{
		Extensions: []string{".tmpl", ".html"},
		Delims:     render.Delims{"{[{", "}]}"},
	}))

	server.Get("/", func(r render.Render) {
		r.HTML(200, "index", nil)
	})

	//
	server.Get("/clients/:pid", func(params martini.Params, r render.Render) {
		r.HTML(200, "index", params["pid"])
	})

	type jd map[string]interface{}
	type ja []interface{}

	// json api
	server.Get("/api/clients", func(r render.Render) {
		client_info := ja{}

		for _, c := range compositors {
			var surfaces []Surface

			for _, s := range c.Surfaces {
				surfaces = append(surfaces, *s)
			}

			client_info = append(client_info, jd{
				"pid": c.Pid,
				"ss":  surfaces,
			})
		}

		r.JSON(200, client_info)
	})

	// websocket api

	server.Get("/api/clients", websocket.Handler(func(ws *websocket.Conn) {

	}).ServeHTTP)

	server.Get("/api/clients/:pid", websocket.Handler(func(ws *websocket.Conn) {

	}).ServeHTTP)

	server.Run()
}
コード例 #2
0
ファイル: handler.go プロジェクト: jbrukh/goavatar
func (s *OctopusSocket) ListenAndServe() {
	var (
		port      = fmt.Sprintf(":%d", *listenPort)
		wsControl = websocket.Handler(s.handleControlConn)
		wsData    = websocket.Handler(s.handleDataConn)
	)

	absRepo, err := filepath.Abs(s.device.Repo().Basedir())
	if err != nil {
		absRepo = s.device.Repo().Basedir()
	}

	fmt.Printf(`Octopus Connector
Copyright (c) 2013 Jake Brukhman/Octopus. All rights reserved.

`)

	fmt.Printf("Version:  %s\n", Version())
	fmt.Printf("Device:   %v\n", s.device.Name())
	fmt.Printf("Control:  http://localhost:%d%s\n", *listenPort, *controlEndpoint)
	fmt.Printf("Data:     http://localhost:%d%s\n", *listenPort, *dataEndpoint)
	fmt.Printf("Repo:     %v\n\n", absRepo)

	// ensure the repository exists
	if err := os.MkdirAll(absRepo, 0755); err != nil {
		log.Fatalf("could not create the device repo: %s", absRepo)
	}

	http.Handle(*controlEndpoint, wsControl)
	http.Handle(*dataEndpoint, wsData)

	if err := http.ListenAndServe(port, nil); err != nil {
		log.Fatalf("could not start OctopusSocket: %v", err)
	}
}
コード例 #3
0
ファイル: socket_test.go プロジェクト: jimjh/octopi
// TestRedirects ensures that the socket follows redirects, if they are given.
func TestRedirects(tester *testing.T) {

	t := test.New(tester)
	count1 := 0
	count2 := 0

	listener1, err := net.Listen("tcp", ":11111")
	t.AssertNil(err, "net.Listen")

	listener2, err := net.Listen("tcp", ":11112")
	t.AssertNil(err, "net.Listen")

	server1 := &http.Server{Handler: websocket.Handler(redirect(&count1))}
	server2 := &http.Server{Handler: websocket.Handler(accept(&count2))}

	go server1.Serve(listener1)
	go server2.Serve(listener2)

	socket := &Socket{
		HostPort: "localhost:11111",
		Path:     "",
		Origin:   "localhost:12345",
	}
	_, err = socket.Send(nil, 3, fakeOrigin)
	t.AssertNil(err, "socket.Send")

	listener1.Close()
	listener2.Close()

	matcher := new(test.IntMatcher)
	t.AssertEqual(matcher, 1, count1)
	t.AssertEqual(matcher, 1, count2)

}
コード例 #4
0
ファイル: main.go プロジェクト: Kadajett/wearscript
func main() {
	err := SignatureCreateKey()
	if err != nil {
		log.Fatal("SignatureCreateKey: Is the Redis database running?: ", err)
		return
	}
	m := pat.New()
	m.Get("/static/{path}", http.HandlerFunc(StaticServer))
	m.Post("/setup", http.HandlerFunc(SetupHandler))
	m.Post("/user/key/{type}", http.HandlerFunc(SecretKeySetupHandler))

	// Control flow is: /authgh -> github -> /oauth2callbackgh
	m.Get("/authgh", http.HandlerFunc(AuthHandlerGH))
	m.Get("/oauth2callbackgh", http.HandlerFunc(Oauth2callbackHandlerGH))

	// Control flow is: /auth -> google -> /oauth2callback
	m.Get("/auth", http.HandlerFunc(authHandler))
	m.Get("/oauth2callback", http.HandlerFunc(oauth2callbackHandler))

	m.Get("/signout", http.HandlerFunc(signoutHandler))
	m.Post("/signout", http.HandlerFunc(signoutHandler))
	m.Post("/signature", http.HandlerFunc(SignatureVerifyHandler))
	http.Handle("/ws/glass/", websocket.Handler(WSGlassHandler))
	http.Handle("/ws/client", websocket.Handler(WSWebHandler))
	http.Handle("/ws/client/", websocket.Handler(WSWebHandler))
	http.Handle("/ws/web", websocket.Handler(WSWebHandler))
	http.Handle("/ws/web/", websocket.Handler(WSWebHandler))
	m.Get("/", http.HandlerFunc(PlaygroundServer))
	http.Handle("/", m)
	err = http.ListenAndServe(":"+servePort, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
コード例 #5
0
ファイル: stabbey.go プロジェクト: Garoth/StAbbey
/* Start the server and connect url paths to functions */
func main() {
	flag.Parse()
	log.SetFlags(log.Lshortfile)

	go signalhandlers.Interrupt()
	go signalhandlers.Quit()

	http.HandleFunc("/resources/js/", JavascriptHandler)
	http.HandleFunc("/resources/css/", CssHandler)
	http.HandleFunc("/resources/img/", ImgHandler)
	http.HandleFunc(HTTP_ROOT, InitSetup)
	http.HandleFunc(HTTP_CONNECT, ConnectSetup)
	http.HandleFunc(HTTP_CONNECT_HAND, ConnectHandSetup)
	http.HandleFunc(HTTP_CONNECT_MAP, ConnectMapSetup)
	http.Handle(HTTP_WEBSOCKET, websocket.Handler(PlayerConnect))
	http.Handle(HTTP_WEBSOCKET_SPECTATOR, websocket.Handler(SpectatorConnect))

	log.Println("Starting Server")
	GAME = game.NewGame()
	RUNTIME = runtime.New(GAME)

	if err := http.ListenAndServe(*ADDR, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
コード例 #6
0
ファイル: main.go プロジェクト: jujum4n/wearscript
func main() {
	SignatureCreateKey()
	m := pat.New()
	m.Get("/static/{path}", http.HandlerFunc(StaticServer))
	m.Post("/notify/{key}", http.HandlerFunc(NotifyServer))
	m.Post("/notify/", http.HandlerFunc(NotifyServer))
	m.Post("/setup", http.HandlerFunc(SetupHandler))
	m.Post("/user/key/{type}", http.HandlerFunc(SecretKeySetupHandler))

	// Control flow is: /auth -> google -> /oauth2callback
	m.Get("/auth", http.HandlerFunc(authHandler))
	m.Get("/oauth2callback", http.HandlerFunc(oauth2callbackHandler))

	m.Post("/signout", http.HandlerFunc(signoutHandler))
	m.Post("/flags", http.HandlerFunc(FlagsHandler))
	m.Get("/flags", http.HandlerFunc(FlagsHandler))
	m.Delete("/flags", http.HandlerFunc(FlagsHandler))
	m.Post("/signature", http.HandlerFunc(SignatureVerifyHandler))
	http.Handle("/ws/glass/", websocket.Handler(WSGlassHandler))
	http.Handle("/ws/web", websocket.Handler(WSWebHandler))
	http.Handle("/ws/web/", websocket.Handler(WSWebHandler))
	m.Get("/", http.HandlerFunc(PlaygroundServer))
	http.Handle("/", m)
	err := http.ListenAndServe(":"+servePort, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
コード例 #7
0
ファイル: broker.go プロジェクト: jimjh/octopi
// listenHttp starts a http server at the given port and listens for incoming
// websocket messages.
func listenHttp(port int) {
	http.Handle("/"+protocol.PUBLISH, websocket.Handler(producer))
	http.Handle("/"+protocol.FOLLOW, websocket.Handler(follower))
	http.Handle("/"+protocol.SUBSCRIBE, websocket.Handler(consumer))
	http.Handle("/"+protocol.SWAP, websocket.Handler(register))
	log.Info("HTTP server started on %d.", port)
	http.ListenAndServe(":"+strconv.Itoa(port), nil)
}
コード例 #8
0
func startServer() {
	http.Handle("/", websocket.Handler(websocketHandler))
	http.Handle("/json", websocket.Handler(websocketHandlerJSON))

	server := httptest.NewServer(nil)
	serverAddr = server.Listener.Addr().String()

	log.Print("Test WebSocket server listening on ", serverAddr)
}
コード例 #9
0
ファイル: webSocket.go プロジェクト: Drithin/Fall_Arm
func main() {

	http.Handle("/notice", websocket.Handler(noticeToNurseHandler))
	http.Handle("/receive", websocket.Handler(patientInputHandler))
	err := http.ListenAndServe(":8081", nil)
	if err != nil {
		panic("ListenAndServe: " + err.Error())
	}
}
コード例 #10
0
ファイル: app.go プロジェクト: varghesepaul/GoChattr
func main() {
	http.Handle("/", http.FileServer(http.Dir("public")))
	http.Handle("/ws", websocket.Handler(websocketHandler))
	http.Handle("/ws-stats", websocket.Handler(websocketStatsHandler))

	log.Println("Server listening at :4000")

	http.ListenAndServe(":4000", nil)
}
コード例 #11
0
ファイル: server.go プロジェクト: rdallman/flaming-wookie
func main() {
	r := mux.NewRouter()
	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
	r.PathPrefix("/templates/").Handler(http.StripPrefix("/templates/", http.FileServer(http.Dir("templates/"))))
	r.HandleFunc("/", handlePage("index"))

	//Authentication (auth.go) //TODO javascript me
	r.HandleFunc("/login", handlePage("login")).Methods("GET")
	r.HandleFunc("/logmein", login).Methods("POST") //TODO /login
	r.HandleFunc("/logmeout", logout)
	r.HandleFunc("/register", handlePage("register")).Methods("GET")
	r.HandleFunc("/register", register).Methods("POST")

	//API class methods (api.go)
	r.HandleFunc("/classes", handleClassList).Methods("GET")
	r.HandleFunc("/classes", handleCreateClass).Methods("POST")
	r.HandleFunc("/classes/{cid:[0-9]+}", handleClassGet).Methods("GET")
	r.HandleFunc("/classes/{cid:[0-9]+}", handleClassUpdate).Methods("POST")
	r.HandleFunc("/classes/{cid:[0-9]+}", handleClassDelete).Methods("DELETE")
	r.HandleFunc("/classes/{cid:[0-9]+}/quiz", handleQuizList).Methods("GET")
	r.HandleFunc("/classes/{cid:[0-9]+}/polls", handlePollsList).Methods("GET")
	r.HandleFunc("/classes/{cid:[0-9]+}/quiz", handleQuizCreate).Methods("POST")
	r.HandleFunc("/classes/{cid:[0-9]+}/poll", handlePollCreate).Methods("POST")
	r.HandleFunc("/classes/{cid:[0-9]+}/student", handleAddStudent).Methods("POST")
	r.HandleFunc("/classes/{cid:[0-9]+}/student", handleDeleteStudent).Methods("DELETE")
	r.HandleFunc("/classes/{cid:[0-9]+}/student", handleUpdateStudent).Methods("PUT")
	r.HandleFunc("/classes/{cid:[0-9]+}/attendance", handleAttendanceList).Methods("GET")

	//API quiz methods (api.go)
	r.HandleFunc("/quiz", handleQuizList).Methods("GET")
	r.HandleFunc("/quiz/{id:[0-9]+}", handleQuizGet).Methods("GET")
	r.HandleFunc("/quiz/{id:[0-9]+}", handleQuizDelete).Methods("DELETE")
	r.HandleFunc("/quiz/{id:[0-9]+}/grades", handleGetQuizGrades).Methods("GET")
	//TODO r.HandleFunc("/quiz/{id:[0-9]+}", handleQuizUpdate).Methods("POST")

	// API for polls
	r.HandleFunc("/polls", handlePollsList).Methods("GET")
	r.HandleFunc("/poll/{id:[0-9]+}", handlePollGet).Methods("GET")
	r.HandleFunc("/poll/{id:[0-9]+}", handlePollDelete).Methods("DELETE")
	r.HandleFunc("/poll/{id:[0-9]+}/results", handlePollResults).Methods("GET")

	//Javascript pages
	r.HandleFunc("/dashboard/", handlePage("dashboard")).Methods("GET")
	//TODO browser "student" client

	// websockets
	r.Handle("/takeme/{id:[0-9]+}", websocket.Handler(studServer))
	r.Handle("/giveme/{id:[0-9]+}", websocket.Handler(teachServer))
	r.Handle("/takeAttendance/{cid:[0-9]+}", websocket.Handler(attendanceServer))

	http.Handle("/", r)
	serveFile("/favicon.ico", "./favicon.ico")
	http.ListenAndServe(":8080", nil)
}
コード例 #12
0
ファイル: web.go プロジェクト: edsu/ginger
func (ch *gingerHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	var rest string
	var urlregex = regexp.MustCompile(`^/(?P<rest>[^/]+)?$`)
	matches := urlregex.FindStringSubmatch(req.URL.Path)
	if len(matches) > 0 {
		rest = matches[1]
	}
	var t *template.Template
	d := templateData{"Ginger": ch.g}

	d["Ginger"] = ch.g
	if rest == "" {
		if req.Method == "GET" {
			t = getTemplate("templates/" + "home" + ".html")
			d["Found"] = true
		} else if req.Method == "POST" {
			dec := json.NewDecoder(req.Body)
			var v map[string]interface{}
			if err := dec.Decode(&v); err == nil {
				url, ok := v["url"].(string)
				if ok {
					if err := ch.g.Add(url, req.RemoteAddr); err != nil {
						log.Println("Error adding URL:", err)
					} else {
						ch.g.StateChanged()
						http.Redirect(w, req, req.URL.Path+"/", http.StatusCreated)
					}
				} else {
					log.Printf("not string as expected: %#v, %T\n", v["url"], v["url"])
				}
			} else {
				log.Println("couldn't add URL:", err)
			}
			req.Body.Close()
			// TODO: write a response
		} else {
			w.WriteHeader(http.StatusMethodNotAllowed)
		}
	} else if rest == "state" {
		cs := &gingerServer{ch.g}
		websocket.Handler(cs.GingerServer).ServeHTTP(w, req)
	} else if rest == "add" {
		cs := &gingerServer{ch.g}
		websocket.Handler(cs.Add).ServeHTTP(w, req)
	} else {
		w.WriteHeader(http.StatusNotFound)
		t = getTemplate("templates/" + "home" + ".html")
	}

	if t != nil {
		writeTemplate(t, d, w)
	}

}
コード例 #13
0
ファイル: http_server.go プロジェクト: uabassguy/loggregator
func (httpServer *httpServer) Start(incomingProtobufChan <-chan []byte, apiEndpoint string) {
	go httpServer.ParseEnvelopes(incomingProtobufChan)

	httpServer.logger.Infof("HttpServer: Listening for sinks at %s", apiEndpoint)
	http.Handle(TAIL_PATH, websocket.Handler(httpServer.websocketSinkHandler))
	http.Handle(DUMP_PATH, websocket.Handler(httpServer.dumpSinkHandler))
	err := http.ListenAndServe(apiEndpoint, nil)
	if err != nil {
		panic(err)
	}
}
コード例 #14
0
ファイル: server.go プロジェクト: Mounaam/zedrem
func RunServer(ip string, port int, sslCrt string, sslKey string, withSignaling bool) {
	http.Handle("/fs/", http.StripPrefix("/fs/", &WebFSHandler{}))
	http.Handle("/clientsocket", websocket.Handler(socketServer))
	http.Handle("/editorsocket", websocket.Handler(editorSocketServer))
	if sslCrt != "" {
		fmt.Printf("Zedrem server now running on wss://%s:%d\n", ip, port)
		log.Fatal(http.ListenAndServeTLS(fmt.Sprintf("%s:%d", ip, port), sslCrt, sslKey, nil))
	} else {
		fmt.Printf("Zedrem server now running on ws://%s:%d\n", ip, port)
		log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", ip, port), nil))
	}
}
コード例 #15
0
func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "%s", c.ParseToLatticeString(bodyReadHelper(w, r)))
	})
	http.HandleFunc("/xml", func(w http.ResponseWriter, r *http.Request) {
		w.Write(c.ParseToSentence(bodyReadHelper(w, r)).ToXML())
	})
	http.HandleFunc("/json", func(w http.ResponseWriter, r *http.Request) {
		w.Write(c.ParseToSentence(bodyReadHelper(w, r)).ToJSON())
	})
	http.Handle("/ws", websocket.Handler(websocketHandler))
	http.Handle("/ws/json", websocket.Handler(websocketHandlerJSON))
	log.Fatal(http.ListenAndServe(":8080", nil))
}
コード例 #16
0
ファイル: dashboard.go プロジェクト: smarinskaya/skynet
func main() {
	var err error

	flag.Parse()

	log = skynet.NewConsoleSemanticLogger("dashboard", os.Stderr)
	if *mgoserver == "" {
		log.Trace(fmt.Sprintf("%+v", skynet.MongoError{
			"",
			"No mongodb server url (both -mgoserver and SKYNET_MGOSERVER missing)",
		}))
	}

	mlogger, err := skynet.NewMongoSemanticLogger(*mgoserver, "skynet",
		"log", skynet.UUID())
	if err != nil {
		log.Error(fmt.Sprintf("%+v", skynet.MongoError{
			Addr: "Could not connect to mongo db for logging",
			Err:  err.Error(),
		}))
	}
	log = skynet.NewMultiSemanticLogger(mlogger, log)

	DC = Doozer()

	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/logs/search", searchHandler)
	http.Handle("/media/", http.StripPrefix("/media/", http.FileServer(http.Dir(*webroot+"/tmpl"))))
	http.Handle("/favicon.ico", http.FileServer(http.Dir(*webroot+"/tmpl/images")))
	http.Handle("/logs/ws", websocket.Handler(wsHandler))

	im := client.NewInstanceMonitor(DC, true)
	http.Handle("/instances/ws", websocket.Handler(func(ws *websocket.Conn) {
		NewInstanceSocket(ws, im)
	}))

	// Cache templates
	layoutTmpl = template.Must(template.ParseFiles(*webroot +
		"/tmpl/layout.html.template"))
	indexTmpl = template.Must(template.ParseFiles(*webroot +
		"/tmpl/index.html.template"))
	searchTmpl = template.Must(template.ParseFiles(*webroot +
		"/tmpl/search.html.template"))

	err = http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Fatal("ListenAndServe: " + err.Error())
	}
}
コード例 #17
0
ファイル: server.go プロジェクト: akrennmair/whiteboard
func main() {
	new_coords = make(chan []int, 1)
	add_conn = make(chan NewConn, 10)
	del_conn = make(chan *websocket.Conn, 10)
	go dispatch_coords()

	servemux := http.NewServeMux()

	servemux.Handle("/view", websocket.Handler(ViewerHandler))
	servemux.Handle("/present", websocket.Handler(PresenterHandler))
	servemux.Handle("/", http.FileServer(http.Dir(".")))

	httpsrv := &http.Server{Handler: servemux, Addr: "0.0.0.0:8000"}
	httpsrv.ListenAndServe()
}
コード例 #18
0
ファイル: bb.go プロジェクト: akrennmair/blackboard
func main() {
	new_coords = make(chan []float64, 1)
	add_conn = make(chan NewConn, 10)
	del_conn = make(chan *websocket.Conn, 10)
	go dispatch_coords()

	servemux := http.NewServeMux()

	servemux.Handle("/recvdata", websocket.Handler(recvdataServer))
	servemux.Handle("/senddata", websocket.Handler(senddataServer))
	servemux.Handle("/", http.FileServer(http.Dir(".")))

	httpsrv := &http.Server{Handler: servemux, Addr: "0.0.0.0:8000"}
	httpsrv.ListenAndServe()
}
コード例 #19
0
ファイル: tokenizerd.go プロジェクト: jmcvetta/tokenizerd
func main() {
	log.SetFlags(log.Ltime | log.Lshortfile)
	//
	// Parse command line
	//
	listenUrl := flag.String("url", "localhost:3000", "Host/port on which to run websocket listener")
	mongoUrl := flag.String("mongo", "localhost", "URL of MongoDB server")
	flag.Parse()
	// Extract DB name from DB URL, if present
	dbName := "tokenizer" // If no DB name specified, use "tokenizer"
	switch _, auth, _, err := mgourl.ParseURL(*mongoUrl); true {
	case err != nil:
		log.Fatal("Could not parse MongoDB URL:", err)
	case auth.Db != "":
		dbName = auth.Db
	}
	//
	// Setup MongoDB connection
	//
	log.Println("Connecting to MongoDB on", *mongoUrl)
	session, err := mgo.Dial(*mongoUrl)
	if err != nil {
		log.Fatalln(err)
	}
	db := session.DB(dbName)
	//
	// Initialize Tokenizer
	//
	t := tokenizer.NewMongoTokenizer(db)
	//
	// Register URLs
	//
	mux := pat.New()
	mux.Get("/v1/rest/tokenize/:string", rest.TokenizeHandler(t))
	mux.Get("/v1/rest/detokenize/:token", rest.DetokenizeHandler(t))
	mux.Get("/v1/ws/tokenize", websocket.Handler(ws.Tokenize(t)))
	mux.Get("/v1/ws/detokenize", websocket.Handler(ws.Detokenize(t)))
	mux.Get("/", http.HandlerFunc(HomePageHandler))
	http.Handle("/", mux)
	//
	// Start HTTP server
	//
	log.Println("Starting HTTP server on", *listenUrl)
	err = http.ListenAndServe(*listenUrl, nil)
	if err != nil {
		log.Fatalln("ListenAndServe: " + err.Error())
	}
}
コード例 #20
0
ファイル: main.go プロジェクト: ikuwow/goSample
func main() {
	http.Handle("/echo", websocket.Handler(echoHandler))
	http.Handle("/", http.FileServer(http.Dir("./")))
	if err := http.ListenAndServe(":8000", nil); err != nil {
		panic("ListenAndServe: " + err.Error())
	}
}
コード例 #21
0
ファイル: main.go プロジェクト: Joey92/xTracker
func main() {

	sigchan := make(chan os.Signal, 1)
	signal.Notify(sigchan, os.Interrupt)
	signal.Notify(sigchan, syscall.SIGTERM)
	go func() {
		<-sigchan
		shutdownFlag = true
	}()

	rides = map[int64]*Ride{}
	rideUpdates = make(chan *Ride, 0)

	http.Handle("/live", websocket.Handler(livemap))
	http.HandleFunc("/location", locationHandler)

	// run main application in goroutine
	go http.ListenAndServe(":8080", nil)

	go updateClients()

	go rideCleanup()

	for !shutdownFlag {
		time.Sleep(1 * time.Second)
	}

	shutdown()

	os.Exit(1)
}
コード例 #22
0
ファイル: examplehandler_test.go プロジェクト: 98pm/docker
// 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())
	}
}
コード例 #23
0
ファイル: server.go プロジェクト: houbl/docker
func wsContainersAttach(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := parseForm(r); err != nil {
		return err
	}
	if vars == nil {
		return fmt.Errorf("Missing parameter")
	}

	if err := eng.Job("container_inspect", vars["name"]).Run(); err != nil {
		return err
	}

	h := websocket.Handler(func(ws *websocket.Conn) {
		defer ws.Close()
		job := eng.Job("attach", vars["name"])
		job.Setenv("logs", r.Form.Get("logs"))
		job.Setenv("stream", r.Form.Get("stream"))
		job.Setenv("stdin", r.Form.Get("stdin"))
		job.Setenv("stdout", r.Form.Get("stdout"))
		job.Setenv("stderr", r.Form.Get("stderr"))
		job.Stdin.Add(ws)
		job.Stdout.Add(ws)
		job.Stderr.Set(ws)
		if err := job.Run(); err != nil {
			utils.Errorf("Error attaching websocket: %s", err)
		}
	})
	h.ServeHTTP(w, r)

	return nil
}
コード例 #24
0
func main() {
	fmt.Println("Server address is", myAddress)
	var serverURI = fmt.Sprintf("%s:%d", configuration.ServerAddress, configuration.ServerPort)
	var isMobile = regexp.MustCompile(`(M|m)obile|(I|i)P(hone|od|ad)|(A|a)ndroid|(B|b)lackBerry|(I|i)EMobile|(K|k)indle|(N|n)etFront|(S|s)ilk-Accelerated|(hpw|web)OS|(F|f)ennec|(M|m)inimo|(O|o)pera (M|m)(obi|ini)|(B|b)lazer|(D|d)olfin|(D|d)olphin|(S|s)kyfire|(Z|z)une`)

	//communcation settings
	var newLobbyChan = make(chan *lobby)         //all the new lobbies are sent over this to our hub to be registered
	var socketConnChan = make(chan socketEntity) //the sockets send a channel to the hub with ID for their connection.
	var killHubChan = make(chan entity)          //used to kill lobbies etc off. This is sockets to lobby ONLY.

	go hub(newLobbyChan, socketConnChan, killHubChan) //spawn hub to keep track of the lobbies and answer queries about lobbies

	http.Handle(configuration.HTTPRoutes.Root, http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			if isMobile.MatchString(r.UserAgent()) { //if its a mobile user
				handleMobile(w, r)
			} else {
				handleDesktop(newLobbyChan, w, r)
			}

		}))

	http.Handle(configuration.HTTPRoutes.Javascript.Route, http.StripPrefix(configuration.HTTPRoutes.Javascript.Route, http.FileServer(http.Dir(configuration.HTTPRoutes.Javascript.RootLocation))))
	http.Handle(configuration.HTTPRoutes.Images.Route, http.StripPrefix(configuration.HTTPRoutes.Images.Route, http.FileServer(http.Dir(configuration.HTTPRoutes.Images.RootLocation))))

	http.Handle(configuration.HTTPRoutes.Websocket, websocket.Handler(
		func(ws *websocket.Conn) {
			handleSocket(socketConnChan, killHubChan, ws)
		}))

	fmt.Println("Binding and listening on", serverURI)
	if err := http.ListenAndServe(serverURI, nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
コード例 #25
0
ファイル: web.go プロジェクト: rjmcguire/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)
}
コード例 #26
0
ファイル: main.go プロジェクト: Tumas/threaded
func main() {
	sources := []*threaded.FeedConfigItem{
		&threaded.FeedConfigItem{
			Guid: "geras_dviratis",
			Url:  "http://www.gerasdviratis.lt/forum/syndication.php",
			Identifier: &threaded.FeedIdentifier{
				ParamName: "t",
				ParamType: "parameter",
			},
		},
	}

	hub := threaded.Hub{
		Connections: make(map[*websocket.Conn]bool),
		Register:    make(chan *websocket.Conn),
		Unregister:  make(chan *websocket.Conn),
	}

	wsHandler := func(ws *websocket.Conn) {
		hub.Register <- ws
		// defer func() { hub.unregister <- ws }()
		select {}
	}

	go hub.Run(&sources)

	http.HandleFunc("/", homeHandler)
	http.Handle("/ws", websocket.Handler(wsHandler))
	if err := http.ListenAndServe(":8080", nil); err != nil {
		fmt.Printf("ListenAndServe: %s", err)
	}
}
コード例 #27
0
ファイル: mobilelogserver.go プロジェクト: yc7369/gostudy
func main() {
	flag.Parse()
	config.SetConfig("config", *flag.String("config", "config.xml", "config xml file for start"))
	config.SetConfig("logfilename", *flag.String("logfilename", "/log/logfilename.log", "log file name"))
	config.SetConfig("deamon", *flag.String("deamon", "false", "need run as demo"))
	config.SetConfig("port", *flag.String("port", "8000", "http port "))
	config.SetConfig("log", *flag.String("log", "debug", "logger level "))
	config.LoadFromFile(config.GetConfigStr("config"), "global")
	if err := config.LoadFromFile(config.GetConfigStr("config"), "MobileLogServer"); err != nil {
		fmt.Println(err)
		return
	}
	monitorMap = make(map[*websocket.Conn]*websocket.Conn)
	logger, err := logging.NewTimeRotationHandler(config.GetConfigStr("logfilename"), "060102-15")
	if err != nil {
		fmt.Println(err)
		return
	}
	logger.SetLevel(logging.DEBUG)
	logging.AddHandler("MLOG", logger)
	logging.Info("server startin...")
	http.Handle("/ws", websocket.Handler(MonitorServer))
	http.Handle("/", http.FileServer(http.Dir(".")))
	http.HandleFunc("/log/fxsj", LogServer)
	http.HandleFunc("/log/hxsg", LogServer)
	http.HandleFunc("/testlua", testLua)
	http.HandleFunc("/log/sbjs", LogServer)
	err = http.ListenAndServe(config.GetConfigStr("ip")+":"+config.GetConfigStr("port"), nil)
	if err != nil {
		fmt.Println(err)
		logging.Error("ListenAndServe:%s", err.Error())
	}
	logging.Info("server stop...")
}
コード例 #28
0
ファイル: server.go プロジェクト: ngpestelos/docker
func (s *Server) wsContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := parseForm(r); err != nil {
		return err
	}
	if vars == nil {
		return fmt.Errorf("Missing parameter")
	}

	h := websocket.Handler(func(ws *websocket.Conn) {
		defer ws.Close()

		wsAttachWithLogsConfig := &daemon.ContainerWsAttachWithLogsConfig{
			InStream:  ws,
			OutStream: ws,
			ErrStream: ws,
			Logs:      boolValue(r, "logs"),
			Stream:    boolValue(r, "stream"),
		}

		if err := s.daemon.ContainerWsAttachWithLogs(vars["name"], wsAttachWithLogsConfig); err != nil {
			logrus.Errorf("Error attaching websocket: %s", err)
		}
	})
	h.ServeHTTP(w, r)

	return nil
}
コード例 #29
0
func main() {
	http.Handle("/", websocket.Handler(handler))
	err := http.ListenAndServe(listenAddr, nil)
	if err != nil {
		log.Fatal(err)
	}
}
コード例 #30
0
ファイル: PIDuino-ui.go プロジェクト: gregose/PIDuino
func main() {
	flag.Parse()

	tempLog = temperatureLog{LogSize: 0, MaxLogSize: maxLogSize, Data: make([]temperatureLogEntry, 2)}
	tempLog.Data[0] = temperatureLogEntry{Label: "Boiler", Values: make([]temperatureLogValue, 0)}
	tempLog.Data[1] = temperatureLogEntry{Label: "Grouphead", Values: make([]temperatureLogValue, 0)}

	go h.broadcastLoop()

	if devMode {
		go devLoop()
	} else {
		go serialLoop()
	}

	http.HandleFunc("/buffer.json", bufferHandler)
	http.HandleFunc("/flush", flushHandler)
	http.Handle("/events", websocket.Handler(eventServer))
	http.Handle("/",
		http.FileServer(
			&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "views"}))

	portString := fmt.Sprintf(":%d", port)
	err := http.ListenAndServe(portString, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}