Пример #1
1
func main() {
	flag.Parse()

	if arguments.pprof {
		log.Println("pprof enabled")
		go func() {
			log.Println(http.ListenAndServe("localhost:6060", nil))
		}()

		fp, err := os.Create("backend.pprof")
		if err != nil {
			panic(err)
		}
		defer fp.Close()

		pprof.StartCPUProfile(fp)
		defer pprof.StopCPUProfile()
	}

	if err := loadTree(arguments.tree); err != nil {
		log.Println(err)
		os.Exit(-1)
	}

	http.Handle("/", http.FileServer(http.Dir(arguments.web)))
	http.Handle("/render", websocket.Handler(renderServer))

	log.Println("waiting for connections...")
	if err := http.ListenAndServe(fmt.Sprintf(":%v", arguments.port), nil); err != nil {
		log.Println(err)
		os.Exit(-1)
	}
}
Пример #2
0
func main() {
	flag.Parse()
	s, err := susigo.NewSusi(*susiaddr, *cert, *key)
	if err != nil {
		log.Printf("Error while creating susi connection: %v", err)
		return
	}
	susi = s
	log.Println("successfully create susi connection")
	sessionTimeouts = make(map[string]time.Time)

	if *user == "" && *pass == "" {
		http.HandleFunc("/publish", publishHandler)
		http.HandleFunc("/upload", uploadHandler)
		http.Handle("/ws", websocket.Handler(websocketHandler))
		http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir(*assetDir))))
		http.HandleFunc("/", redirectToIndex)
	} else {
		http.HandleFunc("/publish", BasicAuth(publishHandler))
		http.HandleFunc("/upload", BasicAuth(uploadHandler))
		http.HandleFunc("/ws", BasicAuth(websocket.Handler(websocketHandler).ServeHTTP))
		http.HandleFunc("/assets/", BasicAuth(http.StripPrefix("/assets/", http.FileServer(http.Dir(*assetDir))).ServeHTTP))
		http.HandleFunc("/", BasicAuth(redirectToIndex))
	}

	log.Printf("starting http server on %v...", *webaddr)
	if *useHTTPS {
		log.Fatal(http.ListenAndServeTLS(*webaddr, *cert, *key, context.ClearHandler(http.DefaultServeMux)))
	} else {
		log.Fatal(http.ListenAndServe(*webaddr, context.ClearHandler(http.DefaultServeMux)))
	}
}
Пример #3
0
func (w *WebServer) start(host string) {
	http.HandleFunc("/ws-server",
		func(w http.ResponseWriter, req *http.Request) {
			s := websocket.Server{
				Handler: websocket.Handler(func(ws *websocket.Conn) {
					jsonrpc.ServeConn(ws)
				}),
			}
			s.ServeHTTP(w, req)
			log.Println("connected ws-server")
		})
	http.HandleFunc("/ws-client",
		func(rw http.ResponseWriter, req *http.Request) {
			s := websocket.Server{
				Handler: websocket.Handler(func(ws *websocket.Conn) {
					w.client = jsonrpc.NewClient(ws)
					w.ch <- struct{}{}
					<-w.ch
				}),
			}
			s.ServeHTTP(rw, req)
			log.Println("connected ws-client")
		})
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, r.URL.Path[1:])
	})
	if err := http.ListenAndServe(host, nil); err != nil {
		log.Fatal(err)
	}
}
Пример #4
0
func (s *TestHttpService) startPod() error {
	unsecurePodServer := http.NewServeMux()
	unsecurePodServer.HandleFunc("/", s.handleHelloPod)
	unsecurePodServer.HandleFunc("/"+s.PodTestPath, s.handleHelloPodTest)
	unsecurePodServer.Handle("/"+s.PodWebSocketPath, websocket.Handler(s.handleWebSocket))

	if err := s.startServing(s.PodHttpAddr, unsecurePodServer); err != nil {
		return err
	}

	alternatePodServer := http.NewServeMux()
	alternatePodServer.HandleFunc("/", s.handleHelloPod2)
	alternatePodServer.HandleFunc("/"+s.PodTestPath, s.handleHelloPod2)

	if err := s.startServing(s.AlternatePodHttpAddr, alternatePodServer); err != nil {
		return err
	}

	securePodServer := http.NewServeMux()
	securePodServer.HandleFunc("/", s.handleHelloPodSecure)
	securePodServer.HandleFunc("/"+s.PodTestPath, s.handleHelloPodTestSecure)
	securePodServer.Handle("/"+s.PodWebSocketPath, websocket.Handler(s.handleWebSocket))
	if err := s.startServingTLS(s.PodHttpsAddr, s.PodHttpsCert, s.PodHttpsKey, s.PodHttpsCaCert, securePodServer); err != nil {
		return err
	}

	return nil
}
Пример #5
0
func main() {
	globalMux := http.NewServeMux()
	dockerUrl := "tcp://127.0.0.1:5554"
	tlsCaCert := ""
	tlsCert := ""
	tlsKey := ""
	allowInsecure := true
	log.SetLevel(log.DebugLevel)
	client, err := utils.GetClient(dockerUrl, tlsCaCert, tlsCert, tlsKey, allowInsecure)
	if err != nil {
		log.Fatal(err)
	}
	a := &Api{client, true, true, &sync.Mutex{}}

	globalMux.Handle("/", http.FileServer(http.Dir("static")))
	globalMux.Handle("/exec", websocket.Handler(a.execContainer))
	globalMux.Handle("/ws", websocket.Handler(a.execContainer))
	s := &http.Server{
		Addr:    "0.0.0.0:8081",
		Handler: context.ClearHandler(globalMux),
	}
	var runErr error
	runErr = s.ListenAndServe()
	if runErr != nil {
		log.Fatal(runErr)
	}

}
Пример #6
0
func main() {
	// Serve test folder.
	http.Handle("/", http.FileServer(http.Dir("./test/")))

	http.Handle("/ws/immediate-close", websocket.Handler(func(ws *websocket.Conn) {
		// Cleanly close the connection.
		err := ws.Close()
		if err != nil {
			panic(err)
		}
	}))

	http.Handle("/ws/binary-static", websocket.Handler(func(ws *websocket.Conn) {
		err := websocket.Message.Send(ws, []byte{0x00, 0x01, 0x02, 0x03, 0x04})
		if err != nil {
			panic(err)
		}
	}))

	http.Handle("/ws/wait-30s", websocket.Handler(func(ws *websocket.Conn) {
		<-time.After(30 * time.Second)
	}))

	err := http.ListenAndServe(":3000", nil)
	if err != nil {
		panic(err)
	}
}
Пример #7
0
func pubsocketdHandler(w http.ResponseWriter, req *http.Request) {

	// See above (20140729/straup)

	if websocketAllowInsecure {

		s := websocket.Server{
			Handler: websocket.Handler(pubSubHandler),
		}

		s.ServeHTTP(w, req)

	} else {

		originURL := websocketAllowableURLs[0]

		pubsocketdConfig := websocket.Config{Origin: &originURL}

		s := websocket.Server{
			Config:    pubsocketdConfig,
			Handshake: pubsocketdHandshake,
			Handler:   websocket.Handler(pubSubHandler),
		}

		s.ServeHTTP(w, req)
	}

}
Пример #8
0
func init() {

	http.Handle("/", websocket.Handler(socketListener))
	http.Handle("/matsock", websocket.Handler(handleMatlabCommands))
	// http.HandleFunc("/series", FetchSeries)

	// 	ch <- true
	// }()

}
Пример #9
0
// This example demonstrates a trivial echo server.
func main() {
	http.HandleFunc("/test", TestServer)
	http.Handle("/", http.FileServer(http.Dir(".")))
	http.Handle("/echo", websocket.Handler(Echo))
	http.Handle("/echo2", websocket.Handler(EchoServer))
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		panic("ListenAndServe: " + err.Error())
	}
}
Пример #10
0
func main() {

	// Force logrus to use console colouring
	var forceColours = flag.Bool("logrusforcecolours", false, "force logrus to use console colouring")
	flag.Parse()
	if *forceColours {
		log.SetFormatter(&log.TextFormatter{ForceColors: true})
	}

	// What are we running on?
	log.WithFields(
		log.Fields{"gover": runtime.Version(), "goos": runtime.GOOS, "goarch": runtime.GOARCH}).Info("Brightlight")

	// Start drivers
	controller.StartTeensyDriver()
	controller.StartRelayDriver()
	renderer := make(chan *framebuffer.FrameBuffer)
	framebuffer.StartDriver(renderer)
	animations.StartDriver(renderer)
	stats.StartDriver()

	// Figure out where the content directory is GOPATH may contain : separated paths
	contentPath := path.Join(os.Getenv("GOPATH"), "src/github.com/andew42/brightlight/ui")
	log.WithField("contentPath", contentPath).Info("Serving content")

	// Set up web routes (first static content)
	mime.AddExtensionType(".manifest", "text/cache-manifest")
	fs := http.FileServer(http.Dir(contentPath))
	http.Handle("/", fs)

	// Config requires PUT (write) support
	http.HandleFunc("/config/", servers.GetConfigHandler(contentPath))

	// Requests to run zero or more animation (json payload)
	http.HandleFunc("/RunAnimations/", servers.RunAnimationsHandler)

	// Requests to show a strip length on the room lights
	http.HandleFunc("/StripLength/", servers.StripLenHandler)

	// Push frame buffer changes over a web socket
	http.Handle("/FrameBuffer", websocket.Handler(servers.FrameBufferHandler))

	// Push stats info over a web socket
	http.Handle("/Stats", websocket.Handler(servers.StatsHandler))

	// Start the option server
	http.HandleFunc("/option/", servers.OptionHandler)

	// Start web server
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Error(err.Error())
	}

	log.Info("brightlight exited")
}
Пример #11
0
func managementInterface() {
	weatherUpdate = NewUIBroadcaster()
	trafficUpdate = NewUIBroadcaster()

	http.HandleFunc("/", defaultServer)
	http.Handle("/logs/", http.StripPrefix("/logs/", http.FileServer(http.Dir("/var/log"))))
	http.HandleFunc("/view_logs/", viewLogs)

	http.HandleFunc("/status",
		func(w http.ResponseWriter, req *http.Request) {
			s := websocket.Server{
				Handler: websocket.Handler(handleStatusWS)}
			s.ServeHTTP(w, req)
		})
	http.HandleFunc("/situation",
		func(w http.ResponseWriter, req *http.Request) {
			s := websocket.Server{
				Handler: websocket.Handler(handleSituationWS)}
			s.ServeHTTP(w, req)
		})
	http.HandleFunc("/weather",
		func(w http.ResponseWriter, req *http.Request) {
			s := websocket.Server{
				Handler: websocket.Handler(handleWeatherWS)}
			s.ServeHTTP(w, req)
		})
	http.HandleFunc("/traffic",
		func(w http.ResponseWriter, req *http.Request) {
			s := websocket.Server{
				Handler: websocket.Handler(handleTrafficWS)}
			s.ServeHTTP(w, req)
		})

	http.HandleFunc("/getStatus", handleStatusRequest)
	http.HandleFunc("/getSituation", handleSituationRequest)
	http.HandleFunc("/getTowers", handleTowersRequest)
	http.HandleFunc("/getSatellites", handleSatellitesRequest)
	http.HandleFunc("/getSettings", handleSettingsGetRequest)
	http.HandleFunc("/setSettings", handleSettingsSetRequest)
	http.HandleFunc("/shutdown", handleShutdownRequest)
	http.HandleFunc("/reboot", handleRebootRequest)
	http.HandleFunc("/getClients", handleClientsGetRequest)
	http.HandleFunc("/updateUpload", handleUpdatePostRequest)
	http.HandleFunc("/roPartitionRebuild", handleroPartitionRebuild)

	err := http.ListenAndServe(managementAddr, nil)

	if err != nil {
		log.Printf("managementInterface ListenAndServe: %s\n", err.Error())
	}
}
Пример #12
0
func main() {
	flag.Parse()
	wsocket.Init()
	wsCntrl.Init()
	go playRadio(wsocket, wsCntrl)
	http.Handle("/radio", websocket.Handler(handler))
	http.Handle("/ctrl", websocket.Handler(ctrlHandler))
	http.HandleFunc("/", rootHandler)
	err := http.ListenAndServe(":"+PORT, nil)
	if err != nil {
		panic("ListenAndServe: " + err.Error())
	}

}
Пример #13
0
func main() {

	if BASIC_HANDLER {
		http.Handle("/echo", websocket.Handler(echoHandler))
		err := http.ListenAndServeTLS(":8080", "client_cert.pem", "client_key.pem", nil)
		if err != nil {
			panic("ListenAndServe: " + err.Error())
		}
	} else {

		http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			defer r.Body.Close()
			switch r.URL.Path {
			case "/":
				u := func() string {
					if r.TLS == nil {
						return "ws://localhost:4080/echo"
					} else {
						return "wss://localhost:8080/echo"
					}
				}()
				http.ServeContent(w, r, "index.html", time.Now(), bytes.NewReader([]byte(Content(u))))
			case "/echo":
				websocket.Handler(EchoHandler).ServeHTTP(w, r)
			default:
				http.NotFound(w, r)
			}
		})

		done := make(chan bool)

		go func() {

			var tlsConfig tls.Config = tls.Config{
			//InsecureSkipVerify: true,
			}

			var server http.Server = http.Server{
				Addr:      ":8080",
				TLSConfig: &tlsConfig,
			}

			fmt.Println(server.ListenAndServeTLS(CERT_NAME, KEY_NAME))
			done <- true
		}()

		<-done
	}

}
Пример #14
0
func main() {
	flag.Parse()
	http.Handle("/reflect", websocket.Handler(reflector))
	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal(err)
	}
}
Пример #15
0
func InitWebsocket() (err error) {
	var (
		listener     *net.TCPListener
		addr         *net.TCPAddr
		httpServeMux = http.NewServeMux()
	)
	httpServeMux.Handle("/sub", websocket.Handler(serveWebsocket))
	for _, bind := range Conf.WebsocketBind {
		if addr, err = net.ResolveTCPAddr("tcp4", bind); err != nil {
			log.Error("net.ResolveTCPAddr(\"tcp4\", \"%s\") error(%v)", bind, err)
			return
		}
		if listener, err = net.ListenTCP("tcp4", addr); err != nil {
			log.Error("net.ListenTCP(\"tcp4\", \"%s\") error(%v)", bind, err)
			return
		}
		server := &http.Server{Handler: httpServeMux}
		log.Debug("start websocket listen: \"%s\"", bind)
		go func() {
			if err = server.Serve(listener); err != nil {
				log.Error("server.Serve(\"%s\") error(%v)", bind, err)
				panic(err)
			}
		}()
	}
	return
}
Пример #16
0
func main() {
	// set GPIO25 to output mode
	pin, err := gpio.OpenPin(rpi.GPIO25, gpio.ModeOutput)
	if err != nil {
		fmt.Printf("Error opening pin! %s\n", err)
		return
	}

	// turn the led off on exit
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		for _ = range c {
			fmt.Printf("\nClearing and unexporting the pin.\n")
			pin.Clear()
			pin.Close()
			os.Exit(0)
		}
	}()

	go buttonHandler(pin)

	// http listen
	//http.Handle("/button", websocket.Handler(EchoServer))
	http.HandleFunc("/button", func(w http.ResponseWriter, req *http.Request) {
		s := websocket.Server{Handler: websocket.Handler(EchoServer)}
		s.ServeHTTP(w, req)
	})
	http.ListenAndServe(":8080", nil)
}
func TestProxyUpgrade(t *testing.T) {
	backendServer := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
		defer ws.Close()
		body := make([]byte, 5)
		ws.Read(body)
		ws.Write([]byte("hello " + string(body)))
	}))
	defer backendServer.Close()

	serverURL, _ := url.Parse(backendServer.URL)
	proxyHandler := &UpgradeAwareProxyHandler{
		Location: serverURL,
	}
	proxy := httptest.NewServer(proxyHandler)
	defer proxy.Close()

	ws, err := websocket.Dial("ws://"+proxy.Listener.Addr().String()+"/some/path", "", "http://127.0.0.1/")
	if err != nil {
		t.Fatalf("websocket dial err: %s", err)
	}
	defer ws.Close()

	if _, err := ws.Write([]byte("world")); err != nil {
		t.Fatalf("write err: %s", err)
	}

	response := make([]byte, 20)
	n, err := ws.Read(response)
	if err != nil {
		t.Fatalf("read err: %s", err)
	}
	if e, a := "hello world", string(response[0:n]); e != a {
		t.Fatalf("expected '%#v', got '%#v'", e, a)
	}
}
Пример #18
0
func stubEvent(t *testing.T, e interface{}, filter MessageFilter) (*client, chan struct{}, func()) {
	f := func(ws *websocket.Conn) {
		b, err := json.Marshal(e)
		if err != nil {
			t.Fatalf("Error marshaling to JSON: %v", err)
		}
		ws.Write(b)
	}
	s := httptest.NewServer(websocket.Handler(f))
	rtm := rtmStartResponse{
		OK:  true,
		URL: strings.Replace(s.URL, "http://", "ws://", 1),
	}
	b, err := json.Marshal(rtm)
	if err != nil {
		t.Fatalf("Error marshaling rtmStartResponse: %v", err)
	}

	cancel := make(chan struct{}, 1)
	client := NewClient("", http.Client{
		Transport: &roundTripper{
			t:        t,
			response: string(b),
			filter: func(*http.Request) bool {
				return true
			},
		},
	}, filter)

	return client, cancel, func() {
		s.Close()
		cancel <- struct{}{}
	}
}
Пример #19
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())
	}
}
Пример #20
0
func main() {
	authentication = getAuth()

	log.Printf("Starting Goship...")
	if err := os.Mkdir(*dataPath, 0777); err != nil && !os.IsExist(err) {
		log.Fatal("could not create data dir: ", err)
	}
	flag.Parse()
	go h.run()
	http.HandleFunc("/", checkAuth(HomeHandler, authentication))
	http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, r.URL.Path[1:])
	})
	http.Handle("/web_push", websocket.Handler(websocketHandler))
	http.HandleFunc("/deploy", checkAuth(DeployPage, authentication))
	http.HandleFunc("/deployLog/", checkAuth(extractDeployLogHandler(DeployLogHandler), authentication))
	http.HandleFunc("/output/", checkAuth(extractOutputHandler(DeployOutputHandler), authentication))
	http.HandleFunc("/commits/", checkAuth(extractCommitHandler(ProjCommitsHandler), authentication))
	http.HandleFunc("/deploy_handler", checkAuth(DeployHandler, authentication))
	http.HandleFunc("/lock", checkAuth(LockHandler, authentication))
	http.HandleFunc("/unlock", checkAuth(UnLockHandler, authentication))
	http.HandleFunc("/comment", checkAuth(CommentHandler, authentication))
	http.HandleFunc("/auth/github/login", loginHandler("github", authentication.authorization))
	http.HandleFunc("/auth/github/callback", callbackHandler("github", authentication.authorization))
	fmt.Printf("Running on %s\n", *bindAddress)
	log.Fatal(http.ListenAndServe(*bindAddress, nil))
}
Пример #21
0
func (s *Server) Start() {
	if s.Context == nil {
		s.Context = context.Background()
	}
	if s.Port == 0 {
		s.Port = DefaultPort
	}
	if s.v == 0 {
		s.v = 1
	}

	mux := http.NewServeMux()
	mux.HandleFunc("/livereload.js", s.serveLiveReloadJS)
	mux.HandleFunc("/xlivereload.js", s.serveLiveReloadJS)
	mux.Handle("/livereload", websocket.Handler(s.handleConnection))

	s.conns = make(map[int]*Conn)
	s.cond = sync.NewCond(&s.mut)

	hd := &httpdown.HTTP{
		StopTimeout: 5 * time.Second,
		KillTimeout: 5 * time.Second,
	}

	server := &http.Server{Addr: ":" + strconv.Itoa(s.Port), Handler: mux}

	hs, err := hd.ListenAndServe(server)
	if err != nil {
		panic("ListenAndServe: " + err.Error())
	}
	s.hs = hs
	log.Printf("Listening on port %v", s.Port)

	go s.shutdownOn(s.Context.Done())
}
Пример #22
0
func main() {
	http.Handle("/", websocket.Handler(Echo))

	if err := http.ListenAndServe(":1234", nil); err != nil {
		log.Fatal("ListenAndServer:", err)
	}
}
Пример #23
0
func TestEcho(t *testing.T) {
	http.Handle("/echo", websocket.Handler(echoServer))
	once.Do(startCherryServer)

	client, err := net.Dial("tcp", serverAddr)
	if err != nil {
		t.Fatal("dialing", err)
	}

	conn, err := websocket.NewClient(newConfig(t, "/echo"), client)
	if err != nil {
		t.Errorf("WebSocket handshake error: %v", err)
		return
	}

	msg := []byte("hello, world\n")
	if _, err := conn.Write(msg); err != nil {
		t.Errorf("Write: %v", err)
	}
	var actual_msg = make([]byte, 512)
	n, err := conn.Read(actual_msg)
	if err != nil {
		t.Errorf("Read: %v", err)
	}
	actual_msg = actual_msg[0:n]
	if !bytes.Equal(msg, actual_msg) {
		t.Errorf("Echo: expected %q got %q", msg, actual_msg)
	}
	conn.Close()
}
Пример #24
0
// Run starts the collider server and blocks the thread until the program exits.
func (c *Collider) Run(p int, useTls bool) {
	http.Handle("/ws", websocket.Handler(c.wsHandler))
	http.HandleFunc("/status", c.httpStatusHandler)
	http.HandleFunc("/", c.httpHandler)

	var e error

	pstr := ":" + strconv.Itoa(p)
	if useTls {
		config := &tls.Config{
			// Only allow ciphers that support forward secrecy for iOS9 compatibility:
			// https://developer.apple.com/library/prerelease/ios/technotes/App-Transport-Security-Technote/
			CipherSuites: []uint16{
				tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
				tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
				tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
				tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
				tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
				tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
				tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
			},
			PreferServerCipherSuites: true,
		}
		server := &http.Server{Addr: pstr, Handler: nil, TLSConfig: config}

		e = server.ListenAndServeTLS("/cert/cert.pem", "/cert/key.pem")
	} else {
		e = http.ListenAndServe(pstr, nil)
	}

	if e != nil {
		log.Fatal("Run: " + e.Error())
	}
}
Пример #25
0
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
}
Пример #26
0
func main() {
	SetCues()
	conns = list.New()
	http.Handle("/chat", websocket.Handler(Chat))
	http.Handle("/", http.FileServer(http.Dir("./html")))
	http.ListenAndServe(":8080", nil)
}
Пример #27
0
func (s *router) wsContainersAttach(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}
	containerName := vars["name"]

	if !s.daemon.Exists(containerName) {
		return derr.ErrorCodeNoSuchContainer.WithArgs(containerName)
	}

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

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

		if err := s.daemon.ContainerWsAttachWithLogs(containerName, wsAttachWithLogsConfig); err != nil {
			logrus.Errorf("Error attaching websocket: %s", err)
		}
	})
	ws := websocket.Server{Handler: h, Handshake: nil}
	ws.ServeHTTP(w, r)

	return nil
}
Пример #28
0
// NewHandler returns a websocket server which checks the origin of requests.
func NewHandler(origin *url.URL) websocket.Server {
	return websocket.Server{
		Config:    websocket.Config{Origin: origin},
		Handshake: handshake,
		Handler:   websocket.Handler(socketHandler),
	}
}
Пример #29
0
func (ln wslistener) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	websocket.Handler(func(wcon *websocket.Conn) {

		// It appears we mustn't pass wcon to external users as is.
		// We'll pass a pipe instead, because the only way to know if a wcon
		// was closed remotely is to read from it until EOF.

		ch := make(chan struct{})
		p1, p2 := net.Pipe()

		go func() {
			io.Copy(wcon, p1)
			wcon.Close()
		}()
		go func() {
			io.Copy(p1, wcon)
			p1.Close()

			close(ch)
		}()

		select {
		case ln.acceptCh <- p2:
		case <-ln.closeCh:
		}

		// As soon as we return from this function, websocket library will
		// close wcon. So we'll wait until p2 or wcon is closed.
		<-ch

	}).ServeHTTP(w, r)
}
Пример #30
0
// If http.ListenandServe return an error,
// it will throws a panic.
func wsListener() {
	if err := func() error {
		httpServeMux := http.NewServeMux()
		httpServeMux.Handle("/pub", websocket.Handler(WsHandle))
		var (
			l   net.Listener
			err error
		)
		if Conf.Tls {
			tlsConf := new(tls.Config)
			tlsConf.Certificates = make([]tls.Certificate, 1)
			tlsConf.Certificates[0], err = tls.X509KeyPair(Conf.Cert, Conf.Key)
			if err != nil {
				return err
			}
			l, err = tls.Listen("tcp", Conf.WebSocket_addr, tlsConf)
			if err != nil {
				return err
			}
			return http.Serve(l, httpServeMux)
		} else {
			return http.ListenAndServe(Conf.WebSocket_addr, httpServeMux)
		}
	}(); err != nil {
		panic(err)
	}
}