func InitWebsocket(addrs []string) (err error) { var ( bind string listener *net.TCPListener addr *net.TCPAddr httpServeMux = http.NewServeMux() server *http.Server ) httpServeMux.Handle("/sub", websocket.Handler(serveWebsocket)) for _, bind = range addrs { 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} if Debug { 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 }
// ServeFD creates an http.Server and sets it up to serve given a socket activated // argument. func ServeFd(addr string, handle http.Handler) error { ls, e := systemd.ListenFD(addr) if e != nil { return e } chErrors := make(chan error, len(ls)) // We don't want to start serving on these sockets until the // "initserver" job has completed. Otherwise required handlers // won't be ready. <-activationLock // Since ListenFD will return one or more sockets we have // to create a go func to spawn off multiple serves for i := range ls { listener := ls[i] go func() { httpSrv := http.Server{Handler: handle} chErrors <- httpSrv.Serve(listener) }() } for i := 0; i < len(ls); i += 1 { err := <-chErrors if err != nil { return err } } return nil }
func NewHttpService(context interface { Acquire() Release() }, server *http.Server) (s *HttpService, err error) { s = &HttpService{} addr := server.Addr if addr == "" { addr = ":http" } s.listener, err = net.Listen("tcp", addr) if err != nil { return } var w sync.WaitGroup w.Add(1) context.Acquire() go func() { defer context.Release() l := s.listener w.Done() server.Serve(l) }() return }
// NewHTTP returns a ListenProxy with a http as the listening service. This is // a convenience wrapper kept in place for compatibility with older checkouts. // Might be removed in the future. func NewHTTP(handler http.Handler) *ListenProxy { lp := NewListenProxy(checker, 10) httpServer := http.Server{Addr: ":http", Handler: handler} go httpServer.Serve(lp.Listener()) return lp }
func HandleRoot(w http.ResponseWriter, r *http.Request) { originalListener, err := net.Listen("tcp", ":8090") if err != nil { panic(err) } sl, err := customListener.New(originalListener) if err != nil { panic(err) } http.HandleFunc("/", helloHttp) server := http.Server{} stop := make(chan os.Signal) signal.Notify(stop, syscall.SIGINT) var wg sync.WaitGroup go func() { wg.Add(1) defer wg.Done() server.Serve(sl) }() fmt.Printf("Serving HTTP\n") select { case signal := <-stop: fmt.Printf("Got signal:%v\n", signal) } fmt.Printf("Stopping listener\n") sl.Stop() fmt.Printf("Waiting on server\n") wg.Wait() }
// ListenAndServeTLS starts a server that listens on the provided TCP mode (as supported // by net.Listen). func ListenAndServeTLS(srv *http.Server, network string, certFile, keyFile string) error { addr := srv.Addr if addr == "" { addr = ":https" } config := &tls.Config{} if srv.TLSConfig != nil { *config = *srv.TLSConfig } if config.NextProtos == nil { config.NextProtos = []string{"http/1.1"} } var err error config.Certificates = make([]tls.Certificate, 1) config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile) if err != nil { return err } ln, err := net.Listen(network, addr) if err != nil { return err } tlsListener := tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, config) return srv.Serve(tlsListener) }
func (s *StreamHandlerSuite) Get(c *C) *http.Response { f, err := os.Open(s.FileName) c.Assert(err, IsNil) _, err = f.Seek(0, os.SEEK_END) c.Assert(err, IsNil) s.Handler = &StreamHandler{ File: f, FlushInterval: 1 * time.Millisecond, IdleTimeout: 20 * time.Millisecond, } l, err := net.Listen("tcp", "localhost:") c.Assert(err, IsNil) x := http.Server{Handler: s.Handler} go x.Serve(l) defer l.Close() res, err := http.Get(fmt.Sprintf("http://%s/", l.Addr())) c.Assert(err, IsNil) return res }
func main() { flag.Parse() http.HandleFunc("/", accessHandler) http.HandleFunc("/_revoke/", revokeHandler) listener, err := net.Listen("tcp", *listenAddress) if err != nil { log.Fatal(err) } if *tlsCertPath != "" && *tlsKeyPath != "" { tlsConfig := &tls.Config{ NextProtos: []string{"http/1.1"}, Certificates: make([]tls.Certificate, 1), } tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(*tlsCertPath, *tlsKeyPath) if err != nil { log.Fatal(err) } listener = tls.NewListener(listener, tlsConfig) } srv := http.Server{Addr: *listenAddress} log.Fatal(srv.Serve(listener)) }
func serveHTTPS(ctx context.Context, httpServer *http.Server) error { log.Printf("Starting TLS server on %s", *httpsAddr) httpsServer := new(http.Server) *httpsServer = *httpServer httpsServer.Addr = *httpsAddr if !inProd { if *tlsCertFile == "" { return errors.New("unspecified --tlscert flag") } if *tlsKeyFile == "" { return errors.New("unspecified --tlskey flag") } return httpsServer.ListenAndServeTLS(*tlsCertFile, *tlsKeyFile) } cert, err := tlsCertFromGCS(ctx) if err != nil { return fmt.Errorf("error loading TLS certs from GCS: %v", err) } httpsServer.TLSConfig = &tls.Config{ Certificates: []tls.Certificate{*cert}, } log.Printf("Listening for HTTPS on %v", *httpsAddr) ln, err := net.Listen("tcp", *httpsAddr) if err != nil { return err } return httpsServer.Serve(tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, httpsServer.TLSConfig)) }
func (h *Handler) listenAndServe(proto, addr, group string) error { var ( start = make(chan struct{}) l net.Listener err error spec string ) server := http.Server{ Addr: addr, Handler: h.mux, } switch proto { case "tcp": l, spec, err = newTCPListener(group, addr, start) case "unix": l, spec, err = newUnixListener(addr, group, start) } if spec != "" { defer os.Remove(spec) } if err != nil { return err } close(start) return server.Serve(l) }
func main() { var socketPath string if len(os.Args) < 2 { socketPath = "" } else { socketPath = os.Args[1] } if socketPath == "" { socketPath = filepath.Join(os.TempDir(), "apple-ssl.sock") } ln, err := net.Listen("unix", socketPath) if err != nil { log.Fatalln("error listening:", err) } http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `<h1>Your SSN and CC are safe here<h1><input type="text"><br><input type="submit">`) }) server := http.Server{} if err := server.Serve(ln); err != nil { log.Fatalln("error serving", err) } }
func (r *Router) serveHTTPS(server *http.Server, errChan chan error) error { if r.config.EnableSSL { tlsConfig := &tls.Config{ Certificates: []tls.Certificate{r.config.SSLCertificate}, CipherSuites: r.config.CipherSuites, } tlsListener, err := tls.Listen("tcp", fmt.Sprintf(":%d", r.config.SSLPort), tlsConfig) if err != nil { r.logger.Fatalf("tls.Listen: %s", err) return err } r.tlsListener = tlsListener r.logger.Infof("Listening on %s", tlsListener.Addr()) go func() { err := server.Serve(tlsListener) r.stopLock.Lock() if !r.stopping { errChan <- err } r.stopLock.Unlock() close(r.tlsServeDone) }() } return nil }
// TestGoRPCGoClient tests the go client using goRPC func TestGoRPCGoClient(t *testing.T) { service := createService() // listen on a random port listener, err := net.Listen("tcp", ":0") if err != nil { t.Fatalf("Cannot listen: %v", err) } defer listener.Close() // Create a Go Rpc server and listen on the port server := rpcplus.NewServer() server.Register(gorpcvtgateservice.New(service)) // create the HTTP server, serve the server from it handler := http.NewServeMux() bsonrpc.ServeCustomRPC(handler, server, false) httpServer := http.Server{ Handler: handler, } go httpServer.Serve(listener) // and run the test suite testGoClient(t, "gorpc", listener.Addr().String()) }
func (r *Router) serveHTTP(server *http.Server, errChan chan error) error { listener, err := net.Listen("tcp", fmt.Sprintf(":%d", r.config.Port)) if err != nil { r.logger.Fatal("net.Listen: %s", err) return err } r.listener = listener if r.config.EnablePROXY { r.listener = &proxyproto.Listener{listener} } r.logger.Info(fmt.Sprintf("Listening on %s", r.listener.Addr())) go func() { err := server.Serve(r.listener) r.stopLock.Lock() if !r.stopping { errChan <- err } r.stopLock.Unlock() close(r.serveDone) }() return nil }
func listenAndServe(urlStr string, out beam.Sender) error { fmt.Println("Starting Docker server...") r, err := createRouter(out) if err != nil { return err } parsedUrl, err := url.Parse(urlStr) if err != nil { return err } var hostAndPath string // For Unix sockets we need to capture the path as well as the host if parsedUrl.Scheme == "unix" { hostAndPath = "/" + parsedUrl.Host + parsedUrl.Path } else { hostAndPath = parsedUrl.Host } l, err := net.Listen(parsedUrl.Scheme, hostAndPath) if err != nil { return err } httpSrv := http.Server{Addr: hostAndPath, Handler: r} return httpSrv.Serve(l) }
func startWebserver() (err error) { server := http.Server{Handler: gateKeeperMux} if cmdline.tls { // copied from net.http ListenAndServeTLS() // so we have a reference to the Listener to close it on /quit/ config := &tls.Config{} config.NextProtos = []string{"http/1.1"} config.Certificates = make([]tls.Certificate, 1) config.Certificates[0], err = tls.LoadX509KeyPair(cmdline.cert, cmdline.key) if err != nil { return } wsListener, err = net.Listen("tcp", cmdline.laddr) if err != nil { return } wsListener = tls.NewListener(wsListener, config) } else { wsListener, err = net.Listen("tcp", cmdline.laddr) if err != nil { return } } startCookieServer() err = server.Serve(wsListener) stopCookieServer() fmt.Println("Shutting down in", cmdline.quittimeout, "second(s)...") time.Sleep(time.Duration(cmdline.quittimeout) * time.Second) return err }
// StartWS will start a websocket RPC server on the given address and port. func StartWS(address string, port int, corsdomains []string, apis []API) error { wsServerMu.Lock() defer wsServerMu.Unlock() if wsRPCServer != nil { return fmt.Errorf("WS RPC interface already started on %s", wsListener.Addr()) } rpcServer := NewServer() for _, api := range apis { if err := rpcServer.RegisterName(api.Namespace, api.Service); err != nil { return err } } listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", address, port)) if err != nil { return err } wsServer := websocket.Server{Handshake: wsHandshakeValidator(corsdomains), Handler: wsHandler} wsHTTPServer := http.Server{Handler: wsServer} go wsHTTPServer.Serve(listener) wsListener = listener wsRPCServer = rpcServer return nil }
func TestMain(m *testing.M) { // fake service service := CreateFakeServer() // listen on a random port listener, err := net.Listen("tcp", ":0") if err != nil { panic(fmt.Sprintf("Cannot listen: %v", err)) } // Create a Go Rpc server and listen on the port server := rpcplus.NewServer() server.Register(gorpcvtgateservice.New(service)) // create the HTTP server, serve the server from it handler := http.NewServeMux() bsonrpc.ServeCustomRPC(handler, server, false) httpServer := http.Server{ Handler: handler, } go httpServer.Serve(listener) testAddress = listener.Addr().String() os.Exit(m.Run()) }
// ServeFD creates an http.Server and sets it up to serve given a socket activated // argument. func ServeFd(addr string, handle http.Handler) error { ls, e := systemd.ListenFD(addr) if e != nil { return e } chErrors := make(chan error, len(ls)) // Since ListenFD will return one or more sockets we have // to create a go func to spawn off multiple serves for i := range ls { listener := ls[i] go func() { httpSrv := http.Server{Handler: handle} chErrors <- httpSrv.Serve(listener) }() } for i := 0; i < len(ls); i += 1 { err := <-chErrors if err != nil { return err } } return nil }
func ServeFD(handle http.Handler) error { println("Looking for listeners") ls, e := listenFD() fmt.Printf("Got %d listeners", len(ls)) if e != nil { println(e.Error()) } chErrors := make(chan error, len(ls)) // Since listenFD will return one or more sockets we have // to create a go func to spawn off multiple serves for i, _ := range ls { listener := ls[i] go func() { httpSrv := http.Server{Handler: handle} chErrors <- httpSrv.Serve(listener) }() } for i := 0; i < len(ls); i += 1 { err := <-chErrors if err != nil { return err } } return nil }
// serveFd creates an http.Server and sets it up to serve given a socket activated // argument. func serveFd(addr string, job *engine.Job) error { r := createRouter(job.Eng, job.GetenvBool("Logging"), job.GetenvBool("EnableCors"), job.Getenv("Version")) ls, e := systemd.ListenFD(addr) if e != nil { return e } chErrors := make(chan error, len(ls)) // We don't want to start serving on these sockets until the // daemon is initialized and installed. Otherwise required handlers // won't be ready. <-activationLock // Since ListenFD will return one or more sockets we have // to create a go func to spawn off multiple serves for i := range ls { listener := ls[i] go func() { httpSrv := http.Server{Handler: r} chErrors <- httpSrv.Serve(listener) }() } for i := 0; i < len(ls); i++ { err := <-chErrors if err != nil { return err } } return nil }
func (h *Handler) listenAndServe(proto, addr, group string) error { server := http.Server{ Addr: addr, Handler: h.mux, } start := make(chan struct{}) var l net.Listener var err error switch proto { case "tcp": l, err = newTCPSocket(addr, nil, start) if err == nil { err = writeSpec(group, l.Addr().String()) } case "unix": var s string s, err = fullSocketAddr(addr) if err == nil { l, err = newUnixSocket(s, group, start) } } if err != nil { return err } close(start) return server.Serve(l) }
// StartActionLoop will start the action loop for a fake tablet, // using ft.FakeMysqlDaemon as the backing mysqld. func (ft *FakeTablet) StartActionLoop(t *testing.T, wr *wrangler.Wrangler) { if ft.Agent != nil { t.Fatalf("Agent for %v is already running", ft.Tablet.Alias) } // Listen on a random port var err error ft.Listener, err = net.Listen("tcp", ":0") if err != nil { t.Fatalf("Cannot listen: %v", err) } port := ft.Listener.Addr().(*net.TCPAddr).Port // create a test agent on that port, and re-read the record // (it has new ports and IP) ft.Agent = tabletmanager.NewTestActionAgent(wr.TopoServer(), ft.Tablet.Alias, port, ft.FakeMysqlDaemon) ft.Tablet = ft.Agent.Tablet().Tablet // create the RPC server ft.RpcServer = rpcplus.NewServer() gorpctmserver.RegisterForTest(ft.RpcServer, ft.Agent) // create the HTTP server, serve the server from it handler := http.NewServeMux() bsonrpc.ServeCustomRPC(handler, ft.RpcServer, false) httpServer := http.Server{ Handler: handler, } go httpServer.Serve(ft.Listener) }
func startP2PServer() { p2pListener, err := net.Listen("tcp", ":35800") if err != nil { log.Fatal(err) } p2psl, err = tcpNew(p2pListener) if err != nil { log.Fatal(err) } P2pRouter := httprouter.New() P2pRouter.GET("/", sayhello) P2pRouter.GET("/pull/:repo/:dataitem/:tag", p2p_pull) P2pRouter.GET("/health", p2pHealthyCheckHandler) p2pserver := http.Server{Handler: P2pRouter} wg.Add(1) defer wg.Done() log.Info("p2p server start") p2pserver.Serve(p2psl) log.Info("p2p server stop") }
func listenForCoordinator() { tlsCert, tlsKey := metadataValue("tls-cert"), metadataValue("tls-key") if (tlsCert == "") != (tlsKey == "") { log.Fatalf("tls-cert and tls-key must both be supplied, or neither.") } log.Printf("Listening on %s ...", *listenAddr) ln, err := net.Listen("tcp", *listenAddr) if err != nil { log.Fatalf("Failed to listen on %s: %v", *listenAddr, err) } ln = tcpKeepAliveListener{ln.(*net.TCPListener)} var srv http.Server if tlsCert != "" { cert, err := tls.X509KeyPair([]byte(tlsCert), []byte(tlsKey)) if err != nil { log.Fatalf("TLS cert error: %v", err) } tlsConf := &tls.Config{ Certificates: []tls.Certificate{cert}, } ln = tls.NewListener(ln, tlsConf) } log.Fatalf("Serve: %v", srv.Serve(ln)) }
func (p *Proxy) Listen() error { err := p.cleanup() if err != nil { return err } addr, err := net.ResolveUnixAddr("unix", "/var/run/docker.sock") if err != nil { return err } raw, err := net.ListenUnix("unix", addr) if err != nil { return err } listener := &stoppableListener{ UnixListener: raw, done: p.done, } err = os.Chmod("/var/run/docker.sock", 0777) if err != nil { return err } server := http.Server{ Handler: http.HandlerFunc(p.handler), } return server.Serve(listener) }
// the test here creates a fake server implementation, a fake client // implementation, and runs the test suite against the setup. func TestGoRPCBinlogStreamer(t *testing.T) { // Listen on a random port listener, err := net.Listen("tcp", ":0") if err != nil { t.Fatalf("Cannot listen: %v", err) } // Create a Go Rpc server and listen on the port server := rpcplus.NewServer() fakeUpdateStream := binlogplayertest.NewFakeBinlogStreamer(t) server.Register(gorpcbinlogstreamer.New(fakeUpdateStream)) // create the HTTP server, serve the server from it handler := http.NewServeMux() bsonrpc.ServeCustomRPC(handler, server, false) httpServer := http.Server{ Handler: handler, } go httpServer.Serve(listener) // Create a Go Rpc client to talk to the fake tablet client := &GoRpcBinlogPlayerClient{} // and send it to the test suite binlogplayertest.Run(t, client, listener.Addr().String(), fakeUpdateStream) }
func RunServer(listenAddress string) (*MemoDb, error) { fmt.Println("Nasluch na", listenAddress) listener, err := net.Listen("tcp", listenAddress) if err != nil { return nil, err } memoDb := &MemoDb{Objects: make(map[string]Object, 0), Listener: listener} // obsługa endpointów HTTP przez https://godoc.org/github.com/emicklei/go-restful container := restful.NewContainer() ws := &restful.WebService{} ws.Path("/") ws.Route(ws.GET("/").To(memoDb.Help)) ws.Route(ws.PUT("/v1/objects/{object_id}").To(memoDb.Put)) ws.Route(ws.GET("/v1/objects/{object_id}").To(memoDb.Get)) container.Add(ws) // nasłuch i obsługa zapytań w tle, w osobnej gorutynie go func() { server := http.Server{Handler: container} server.Serve(listener) }() return memoDb, nil }
func ListenAndServe(proto, addr string, srv *Server, logging bool) error { log.Printf("Listening for HTTP on %s (%s)\n", addr, proto) r, err := createRouter(srv, logging) if err != nil { return err } l, e := net.Listen(proto, addr) if e != nil { return e } if proto == "unix" { if err := os.Chmod(addr, 0660); err != nil { return err } groups, err := ioutil.ReadFile("/etc/group") if err != nil { return err } re := regexp.MustCompile("(^|\n)docker:.*?:([0-9]+)") if gidMatch := re.FindStringSubmatch(string(groups)); gidMatch != nil { gid, err := strconv.Atoi(gidMatch[2]) if err != nil { return err } utils.Debugf("docker group found. gid: %d", gid) if err := os.Chown(addr, 0, gid); err != nil { return err } } } httpSrv := http.Server{Addr: addr, Handler: r} return httpSrv.Serve(l) }
func ListenAndServe(s *http.Server, path string) error { ln, err := net.Listen("unix", path) if err != nil { return err } return s.Serve(ln) }