Example #1
1
func ExampleClient_Listen() {
	config := &ClientConfig{
		User: "******",
		Auth: []AuthMethod{
			Password("password"),
		},
	}
	// Dial your ssh server.
	conn, err := Dial("tcp", "localhost:22", config)
	if err != nil {
		log.Fatalf("unable to connect: %s", err)
	}
	defer conn.Close()

	// Request the remote side to open port 8080 on all interfaces.
	l, err := conn.Listen("tcp", "0.0.0.0:8080")
	if err != nil {
		log.Fatalf("unable to register tcp forward: %v", err)
	}
	defer l.Close()

	// Serve HTTP with your SSH server acting as a reverse proxy.
	http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(resp, "Hello world!\n")
	}))
}
Example #2
1
File: serve.go Project: logan/heim
func (cmd *serveEmbedCmd) run(ctx scope.Context, args []string) error {
	listener, err := net.Listen("tcp", cmd.addr)
	if err != nil {
		return err
	}

	closed := false
	m := sync.Mutex{}
	closeListener := func() {
		m.Lock()
		if !closed {
			listener.Close()
			closed = true
		}
		m.Unlock()
	}

	// Spin off goroutine to watch ctx and close listener if shutdown requested.
	go func() {
		<-ctx.Done()
		closeListener()
	}()

	if err := http.Serve(listener, cmd); err != nil {
		fmt.Printf("http[%s]: %s\n", cmd.addr, err)
		return err
	}

	closeListener()
	ctx.WaitGroup().Done()
	return ctx.Err()
}
Example #3
1
func main() {
	certpath := flag.String("cert", "", "The path to a PEM certificate")
	keypath := flag.String("key", "", "The path to a PEM key")
	flag.Parse()
	if len(*certpath) == 0 || len(*keypath) == 0 {
		flag.PrintDefaults()
		return
	}
	ctx := gossl.NewContext(gossl.SSLv3Method())
	ctx.SetOptions(gossl.OpNoCompression)
	err := ctx.UsePrivateKeyFile(*keypath, gossl.FileTypePem)
	if err != nil {
		panic(err)
	}
	ctx.UseCertificateFile(*certpath, gossl.FileTypePem)
	if err != nil {
		panic(err)
	}
	l, err := net.Listen("tcp", ":8000")
	if err != nil {
		panic(err)
	}
	l, err = gossl.NewListener(l, ctx)
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, %q\n", html.EscapeString(r.URL.Path))
	})
	http.Serve(l, nil)

}
Example #4
0
func (herd *Herd) startServer(portNum uint, daemon bool) error {
	listener, err := net.Listen("tcp", fmt.Sprintf(":%d", portNum))
	if err != nil {
		return err
	}
	http.HandleFunc("/", herd.statusHandler)
	http.HandleFunc("/listReachableSubs", herd.listReachableSubsHandler)
	http.HandleFunc("/listSubs", herd.listSubsHandler)
	http.HandleFunc("/showAliveSubs",
		html.BenchmarkedHandler(herd.showAliveSubsHandler))
	http.HandleFunc("/showAllSubs",
		html.BenchmarkedHandler(herd.showAllSubsHandler))
	http.HandleFunc("/showCompliantSubs",
		html.BenchmarkedHandler(herd.showCompliantSubsHandler))
	http.HandleFunc("/showDeviantSubs",
		html.BenchmarkedHandler(herd.showDeviantSubsHandler))
	http.HandleFunc("/showReachableSubs",
		html.BenchmarkedHandler(herd.showReachableSubsHandler))
	http.HandleFunc("/showSub", html.BenchmarkedHandler(herd.showSubHandler))
	if daemon {
		go http.Serve(listener, nil)
	} else {
		http.Serve(listener, nil)
	}
	return nil
}
Example #5
0
func main() {
	flag.Parse()

	host := *vhost
	if strings.Contains(*vhost, ":") {
		var err error
		shost, port, err := net.SplitHostPort(*vhost)
		if err != nil {
			log.Fatalf("unable to parse httpsAddr: %s", err)
		}
		host = shost
		if port != "443" {
			host = *vhost
		}
	}

	apiVars.Set("requests", apiRequests)
	staticVars.Set("requests", staticRequests)
	webVars.Set("requests", webRequests)

	index = loadIndex()
	tlsConf := makeTLSConfig(*certPath, *keyPath)

	tlsListener, err := tls.Listen("tcp", *httpsAddr, tlsConf)
	if err != nil {
		log.Fatalf("unable to listen for the HTTPS server on %s: %s", *httpsAddr, err)
	}
	plaintextListener, err := net.Listen("tcp", *httpAddr)
	if err != nil {
		log.Fatalf("unable to listen for the HTTP server on %s: %s", *httpAddr, err)
	}
	l := &listener{tlsListener}

	m := tlsMux(
		host,
		makeStaticHandler())

	adminAddr := net.JoinHostPort("localhost", *adminPort)
	go func() {
		err := http.ListenAndServe(adminAddr, nil)
		if err != nil {
			log.Fatalf("unable to open admin server: %s", err)
		}
	}()

	log.Printf("Booting HTTPS on %s and HTTP on %s", *httpsAddr, *httpAddr)
	go func() {
		err := http.Serve(l, m)
		if err != nil {
			log.Fatalf("https server error: %s", err)
		}
	}()
	err = http.Serve(plaintextListener, plaintextMux(host))
	if err != nil {
		log.Fatalf("http server error: %s", err)
	}
}
Example #6
0
File: main.go Project: rmg/tyk
func main() {
	displayConfig()

	if doMemoryProfile {
		log.Info("Memory profiling active")
		profileFile, _ = os.Create("tyk.mprof")
		defer profileFile.Close()
	}

	targetPort := fmt.Sprintf(":%d", config.ListenPort)
	loadAPIEndpoints(http.DefaultServeMux)

	// Handle reload when SIGUSR2 is received
	l, err := goagain.Listener()
	if nil != err {

		// Listen on a TCP or a UNIX domain socket (TCP here).
		l, err = net.Listen("tcp", targetPort)
		if nil != err {
			log.Fatalln(err)
		}
		log.Println("Listening on", l.Addr())

		// Accept connections in a new goroutine.
		specs := getAPISpecs()
		loadApps(specs, http.DefaultServeMux)
		go http.Serve(l, nil)

	} else {

		// Resume accepting connections in a new goroutine.
		log.Println("Resuming listening on", l.Addr())
		specs := getAPISpecs()
		loadApps(specs, http.DefaultServeMux)
		go http.Serve(l, nil)

		// Kill the parent, now that the child has started successfully.
		if err := goagain.Kill(); nil != err {
			log.Fatalln(err)
		}

	}

	// Block the main goroutine awaiting signals.
	if _, err := goagain.Wait(l); nil != err {
		log.Fatalln(err)
	}

	// Do whatever's necessary to ensure a graceful exit like waiting for
	// goroutines to terminate or a channel to become closed.
	//
	// In this case, we'll simply stop listening and wait one second.
	if err := l.Close(); nil != err {
		log.Fatalln(err)
	}
	time.Sleep(1e9)
}
Example #7
0
func main() {
	flag.Parse()

	routeHost, redirectHost := calculateDomains(*rawVHost, *httpsAddr)

	apiVars.Set("requests", apiRequests)
	staticVars.Set("requests", staticRequests)
	webVars.Set("requests", webRequests)

	index = loadIndex()
	tlsConf := makeTLSConfig(*certPath, *keyPath)

	tlsListener, err := tls.Listen("tcp", *httpsAddr, tlsConf)
	if err != nil {
		log.Fatalf("unable to listen for the HTTPS server on %s: %s", *httpsAddr, err)
	}
	plaintextListener, err := net.Listen("tcp", *httpAddr)
	if err != nil {
		log.Fatalf("unable to listen for the HTTP server on %s: %s", *httpAddr, err)
	}
	l := &listener{tlsListener}

	if *acmeURL != "" {
		if !strings.HasPrefix(*acmeURL, "/") &&
			!strings.HasPrefix(*acmeURL, "https://") &&
			!strings.HasPrefix(*acmeURL, "http://") {
			fmt.Fprintf(os.Stderr, "acmeRedirect must start with 'http://', 'https://', or '/' but does not: %#v\n", *acmeURL)
			os.Exit(1)
		}
	}

	m := tlsMux(
		routeHost,
		redirectHost,
		*acmeURL,
		makeStaticHandler(*staticDir, staticVars))

	adminAddr := net.JoinHostPort("localhost", *adminPort)
	go func() {
		err := http.ListenAndServe(adminAddr, nil)
		if err != nil {
			log.Fatalf("unable to open admin server: %s", err)
		}
	}()

	log.Printf("Booting HTTPS on %s and HTTP on %s", *httpsAddr, *httpAddr)
	go func() {
		err := http.Serve(l, m)
		if err != nil {
			log.Fatalf("https server error: %s", err)
		}
	}()
	err = http.Serve(plaintextListener, plaintextMux(redirectHost))
	if err != nil {
		log.Fatalf("http server error: %s", err)
	}
}
Example #8
0
File: proxy.go Project: 205c/git
func (p *Proxy) Run() error {
	hl, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		return fmt.Errorf("http listen failed: %v", err)
	}
	defer hl.Close()

	hsl, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		return fmt.Errorf("https listen failed: %v", err)
	}
	defer hsl.Close()

	p.ul, err = DefaultSocket.Listen()
	if err != nil {
		c, derr := DefaultSocket.Dial()
		if derr == nil {
			c.Close()
			fmt.Println("OK\nA proxy is already running... exiting")
			return nil
		} else if e, ok := derr.(*net.OpError); ok && e.Err == syscall.ECONNREFUSED {
			// Nothing is listening on the socket, unlink it and try again.
			syscall.Unlink(DefaultSocket.Path())
			p.ul, err = DefaultSocket.Listen()
		}
		if err != nil {
			return fmt.Errorf("unix listen failed on %v: %v", DefaultSocket.Path(), err)
		}
	}
	defer p.ul.Close()
	go p.closeOnSignal()
	go p.closeOnUpdate()

	p.httpAddr = hl.Addr().String()
	p.httpsAddr = hsl.Addr().String()
	fmt.Printf("OK\nListening on unix socket=%v http=%v https=%v\n",
		p.ul.Addr(), p.httpAddr, p.httpsAddr)

	result := make(chan error, 2)
	go p.serveUnix(result)
	go func() {
		result <- http.Serve(hl, &httputil.ReverseProxy{
			FlushInterval: 500 * time.Millisecond,
			Director:      func(r *http.Request) {},
		})
	}()
	go func() {
		result <- http.Serve(hsl, &httputil.ReverseProxy{
			FlushInterval: 500 * time.Millisecond,
			Director: func(r *http.Request) {
				r.URL.Scheme = "https"
			},
		})
	}()
	return <-result
}
Example #9
0
func (this *FrontEnd) Run() error {
	err := make(chan error)
	go func() {
		err <- http.Serve(this.https, this.proxy)
	}()
	go func() {
		err <- http.Serve(this.http, this.proxy)
	}()
	return <-err
}
Example #10
0
File: main.go Project: QY-Y/flynn
// openHTTPServer initializes and opens the HTTP server.
// The store must already be open.
func (m *Main) openHTTPServer(ln net.Listener, peers []string) error {
	// If we have no store then simply start a proxy handler.
	if m.store == nil {
		go http.Serve(ln, &server.ProxyHandler{Peers: peers})
		return nil
	}

	// Otherwise initialize and start handler.
	h := server.NewHandler()
	h.Store = m.store
	go http.Serve(ln, h)

	return nil
}
Example #11
0
File: server.go Project: xgdapg/wtk
func (this *Server) Run(mode string, addr string, port int) error {
	var tlsConfig *tls.Config
	var err error
	if mode == "https" {
		tlsConfig = &tls.Config{}
		if tlsConfig.NextProtos == nil {
			tlsConfig.NextProtos = []string{"http/1.1"}
		}
		tlsConfig.Certificates = make([]tls.Certificate, 1)
		tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(SslCertificate, SslCertificateKey)
		if err != nil {
			return err
		}
	}

	listenUnix := false
	if strings.HasPrefix(addr, "unix:") {
		listenUnix = true
		addr = addr[5:]
	}

	if listenUnix {
		os.Remove(addr)
		this.listener, err = net.Listen("unix", addr)
		if err == nil {
			os.Chmod(addr, os.FileMode(0666))
			defer os.Remove(addr)
		}
	} else {
		listenAddr := net.JoinHostPort(addr, fmt.Sprintf("%d", port))
		this.listener, err = net.Listen("tcp", listenAddr)
	}
	if err != nil {
		return err
	}
	// defer this.listener.Close()
	this.RunMode = mode

	switch mode {
	case "http":
		http.Serve(this.listener, this.router)
	case "fcgi":
		fcgi.Serve(this.listener, this.router)
	case "https":
		http.Serve(tls.NewListener(this.listener, tlsConfig), this.router)
	default:
		http.Serve(this.listener, this.router)
	}
	return nil
}
Example #12
0
func httpServer(sn *subnet.SubnetManager, publicIP, port string) error {
	overlayListener, err := net.Listen("tcp", net.JoinHostPort(sn.Lease().Network.IP.String(), port))
	if err != nil {
		return err
	}
	publicListener, err := net.Listen("tcp", net.JoinHostPort(publicIP, port))

	http.HandleFunc("/ping", func(http.ResponseWriter, *http.Request) {})
	status.AddHandler(status.SimpleHandler(func() error {
		return pingLeases(sn.Leases())
	}))
	go http.Serve(overlayListener, nil)
	go http.Serve(publicListener, nil)
	return nil
}
Example #13
0
func StartServer(portNum uint, manager *filegen.Manager, daemon bool) error {
	listener, err := net.Listen("tcp", fmt.Sprintf(":%d", portNum))
	if err != nil {
		return err
	}
	myState := &state{manager}
	http.HandleFunc("/", myState.statusHandler)
	http.HandleFunc("/listGenerators", myState.listGeneratorsHandler)
	if daemon {
		go http.Serve(listener, nil)
	} else {
		http.Serve(listener, nil)
	}
	return nil
}
Example #14
0
// NewTribServer creates, starts and returns a new TribServer. masterServerHostPort
// is the master storage server's host:port and port is this port number on which
// the TribServer should listen. A non-nil error should be returned if the TribServer
// could not be started.
//
// For hints on how to properly setup RPC, see the rpc/tribrpc package.
func NewTribServer(masterServerHostPort, myHostPort string) (TribServer, error) {
	newStore, err := libstore.NewLibstore(masterServerHostPort, myHostPort, libstore.Never)
	if err != nil {
		return nil, err
	}

	ts := &tribServer{
		myHostPort: myHostPort,
		Libstore:   newStore,
	}

	err = rpc.RegisterName("TribServer", tribrpc.Wrap(ts))
	if err != nil {
		return nil, err
	}

	rpc.HandleHTTP()
	l, err := net.Listen("tcp", myHostPort)
	if err != nil {
		return nil, err
	}
	go http.Serve(l, nil)

	return ts, nil
}
// NewTribServer creates, starts and returns a new TribServer. masterServerHostPort
// is the master storage server's host:port and port is this port number on which
// the TribServer should listen. A non-nil error should be returned if the TribServer
// could not be started.
//
// For hints on how to properly setup RPC, see the rpc/tribrpc package.
func NewTribServer(masterServerHostPort, myHostPort string) (TribServer, error) {
	libStore, err := libstore.NewLibstore(masterServerHostPort, myHostPort, libstore.Never)
	//fmt.Println("Creating new tribServer...")
	if err != nil {
		return nil, err
	}

	var tribServ tribServer = tribServer{
		libStore: libStore,
	}
	l, err2 := net.Listen("tcp", myHostPort)
	if err2 != nil {
		fmt.Println(err2)
		return nil, err2
	}
	//go http.Serve(l, nil)
	err1 := rpc.RegisterName("TribServer", tribrpc.Wrap(&tribServ))
	if err1 != nil {
		fmt.Println(err1)
		return nil, err1
	}
	rpc.HandleHTTP()
	go http.Serve(l, nil)

	return &tribServ, nil
}
Example #16
0
func startLocalHttpServer(ch chan ForceCredentials) (port int, err error) {
	listener, err := net.Listen("tcp", ":3835")
	if err != nil {
		return
	}
	port = listener.Addr().(*net.TCPAddr).Port
	h := http.NewServeMux()
	h.HandleFunc("/oauth/callback", func(w http.ResponseWriter, r *http.Request) {
		query := r.URL.Query()
		if r.Method == "POST" {
			var creds ForceCredentials
			creds.AccessToken = query.Get("access_token")
			creds.RefreshToken = query.Get("refresh_token")
			creds.Id = query.Get("id")
			creds.InstanceUrl = query.Get("instance_url")
			creds.IssuedAt = query.Get("issued_at")
			creds.Scope = query.Get("scope")
			ch <- creds
			LogAuth()
			listener.Close()
		} else {
			io.WriteString(w, oauthCallbackHtml())
		}
	})
	go http.Serve(listener, h)
	return
}
Example #17
0
func NewServer(config *Config) (*Server, error) {
	listenAddress := "localhost:0"

	if config == nil {
		config = &Config{}
	}

	if config.ListenAddress != "" {
		listenAddress = config.ListenAddress
	}

	if config.Clock == nil {
		config.Clock = &realClock{}
	}

	l, err := net.Listen("tcp", listenAddress)
	if err != nil {
		return nil, fmt.Errorf("cannot listen on localhost: %v", err)
	}
	srv := &Server{
		listener: l,
		url:      "http://" + l.Addr().String(),
		buckets:  make(map[string]*bucket),
		config:   config,
	}
	go http.Serve(l, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		srv.serveHTTP(w, req)
	}))
	return srv, nil
}
Example #18
0
// NewTLSServer creates and starts a TLS-enabled testing server.
func NewTLSServer(bind string, containerChan chan<- *docker.Container, hook func(*http.Request), tlsConfig TLSConfig) (*DockerServer, error) {
	listener, err := net.Listen("tcp", bind)
	if err != nil {
		return nil, err
	}
	defaultCertificate, err := tls.LoadX509KeyPair(tlsConfig.CertPath, tlsConfig.CertKeyPath)
	if err != nil {
		return nil, err
	}
	tlsServerConfig := new(tls.Config)
	tlsServerConfig.Certificates = []tls.Certificate{defaultCertificate}
	if tlsConfig.RootCAPath != "" {
		rootCertPEM, err := ioutil.ReadFile(tlsConfig.RootCAPath)
		if err != nil {
			return nil, err
		}
		certsPool := x509.NewCertPool()
		certsPool.AppendCertsFromPEM(rootCertPEM)
		tlsServerConfig.RootCAs = certsPool
	}
	tlsListener := tls.NewListener(listener, tlsServerConfig)
	server := buildDockerServer(tlsListener, containerChan, hook)
	go http.Serve(tlsListener, server)
	return server, nil
}
Example #19
0
File: main.go Project: polvi/rolo
func getJWT(c *oidc.Client, listenAddr string) (*oauth2.Client, chan *oauth2.TokenResponse, error) {
	jwtChan := make(chan *oauth2.TokenResponse)
	l, err := net.Listen("tcp", listenAddr)
	if err != nil {
		return nil, nil, err
	}
	oac, err := c.OAuthClient()
	if err != nil {
		return nil, nil, err
	}
	f := func(w http.ResponseWriter, r *http.Request) {
		code := r.URL.Query().Get("code")
		if code == "" {
			return
		}
		token, err := oac.RequestToken(oauth2.GrantTypeAuthCode, code)
		if err != nil {
			fmt.Fprintf(w, "error: %s", err)
			return
		}
		jwtChan <- &token
		fmt.Fprintf(w, "Success! You can now close this window and go back to the CLI")
		l.Close()
	}
	go http.Serve(l, http.HandlerFunc(f))
	return oac, jwtChan, err
}
Example #20
0
func StartServer(args []string) {
	var err error
	const port_usage = "Port on which to serve HTTP API"

	flags := flag.NewFlagSet("start", flag.ExitOnError)
	flags.IntVar(&port, "port", 8080, port_usage)
	flags.IntVar(&port, "p", 8080, port_usage+" (shorthand)")
	flags.StringVar(&rpcSock, "sock", sock_default, sock_usage)
	flags.StringVar(&rpcSock, "s", sock_default, sock_usage+" (shorthand)")
	flags.Parse(args)

	adb, err = GetAndInitDB()
	if err != nil {
		panic(err)
	}

	rpcTornDown := make(chan int)
	go StartRPC(rpcSock, rpcTornDown, adb)

	http.HandleFunc("/", rootHandler)
	http.HandleFunc("/events", eventHandler)
	http.HandleFunc("/events/", eventHandler)

	//TODO add HTTPS, something like http://golang.org/pkg/net/http/#ListenAndServeTLS
	l, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
	if err != nil {
		panic(err)
	}
	defer l.Close()
	go http.Serve(l, nil)
	//TODO handle errors from http.Serve?

	asink.WaitOnExit()
	<-rpcTornDown
}
Example #21
0
func serveHTTP() {
	parsedAddr := fmt.Sprintf("%s:%d", host, port)
	if development {
		log.Println("Listening for WebSocket connections without TLS on " + parsedAddr)
		log.Fatal(http.ListenAndServe(parsedAddr, nil))
		return
	}
	// Requires cert.pem and cert.key to be present. See cert_setup.sh
	log.Println("Listening for WebSocket connections with TLS on " + parsedAddr)
	certificate, err := tls.X509KeyPair(
		[]byte(os.Getenv("WS_CERT")),
		[]byte(os.Getenv("WS_KEY")),
	)
	if err != nil {
		log.Fatal(err)
	}
	listener, err := tls.Listen(
		"tcp",
		parsedAddr,
		&tls.Config{Certificates: []tls.Certificate{certificate}},
	)
	if err != nil {
		log.Fatal(err)
	}
	log.Fatal(http.Serve(listener, nil))
}
Example #22
0
// setupTestServer creates a listener for the rest requests.
func setupTestServer() {

	router := mux.NewRouter()

	// register handlers for cni
	t := router.Headers("Content-Type", "application/json").Methods("POST").Subrouter()
	t.HandleFunc(cniapi.EPAddURL, httpWrapper(stubAddPod))
	t.HandleFunc(cniapi.EPDelURL, httpWrapper(stubDeletePod))

	driverPath := cniapi.ContivCniSocket
	os.Remove(driverPath)
	os.MkdirAll(cniapi.PluginPath, 0700)

	go func() {
		l, err := net.ListenUnix("unix", &net.UnixAddr{Name: driverPath, Net: "unix"})
		if err != nil {
			panic(err)
		}

		logger.Infof("k8s test plugin listening on %s", driverPath)
		http.Serve(l, router)
		l.Close()
		logger.Infof("k8s test plugin closing %s", driverPath)
	}()

}
Example #23
0
// startServingTLS creates and registers a secure listener and begins serving traffic.
func (s *TestHttpService) startServingTLS(addr string, cert []byte, key []byte, caCert []byte, handler http.Handler) error {
	tlsCert, err := tls.X509KeyPair(append(cert, caCert...), key)

	if err != nil {
		return err
	}

	cfg := &tls.Config{
		Certificates: []tls.Certificate{tlsCert},
	}

	listener, err := tls.Listen("tcp", addr, cfg)

	if err != nil {
		return err
	}

	s.listeners = append(s.listeners, listener)
	glog.Infof("Started, serving TLS at %s\n", listener.Addr().String())

	go func() {
		if err := http.Serve(listener, handler); err != nil {
			glog.Errorf("HTTPS server failed: %v", err)
		}
	}()

	return nil
}
Example #24
0
func main() {
	flag.Parse()

	loggo.ConfigureLoggers(fmt.Sprintf("<root>=%s", *loglevel))
	if carpo_version == "" {
		carpo_version = fmt.Sprintf("%d", time.Now().Unix())
	}
	logger.Infof("carpo '%s' started at port %d...\n", carpo_version, *port)

	ws := wks
	if ws == nil {
		wd, err := os.Getwd()
		if err != nil {
			log.Fatal(err)
		}
		ws = &wd
	}
	if len([]byte(*clientpath)) > 0 {
		client.Init(*clientpath)
	} else {
		client.InitResources()
	}
	err := workspace.NewWorkspace(*ws, carpo_version)
	if err != nil {
		log.Fatal(err)
	}
	l, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
	if err != nil {
		log.Fatal(err)
	}
	if *browser {
		startBrowser(fmt.Sprintf("http://localhost:%d", *port))
	}
	http.Serve(l, nil)
}
Example #25
0
File: web.go Project: 2722/lantern
func startHttp() {
	http.HandleFunc("/register", register)
	http.HandleFunc("/unregister", unregister)
	laddr := fmt.Sprintf(":%d", *port)

	tlsConfig := tlsdefaults.Server()
	_, _, err := keyman.StoredPKAndCert(PKFile, CertFile, "Lantern", "localhost")
	if err != nil {
		log.Fatalf("Unable to initialize private key and certificate: %v", err)
	}
	cert, err := tls.LoadX509KeyPair(CertFile, PKFile)
	if err != nil {
		log.Fatalf("Unable to load certificate and key from %s and %s: %s", CertFile, PKFile, err)
	}
	tlsConfig.Certificates = []tls.Certificate{cert}

	log.Debugf("About to listen at %v", laddr)
	l, err := tls.Listen("tcp", laddr, tlsConfig)
	if err != nil {
		log.Fatalf("Unable to listen for tls connections at %s: %s", laddr, err)
	}

	log.Debug("About to serve")
	err = http.Serve(l, nil)
	if err != nil {
		log.Fatalf("Unable to serve: %s", err)
	}
}
Example #26
0
// NewTribServer creates, starts and returns a new TribServer. masterServerHostPort
// is the master storage server's host:port and port is this port number on which
// the TribServer should listen. A non-nil error should be returned if the TribServer
// could not be started.
//
// For hints on how to properly setup RPC, see the rpc/tribrpc package.
func NewTribServer(masterServerHostPort, myHostPort string) (TribServer, error) {
	tribServer := new(tribServer)

	// Create the server socket that will listen for incoming RPCs.
	listener, err := net.Listen("tcp", myHostPort)
	if err != nil {
		return nil, err
	}

	// Wrap the tribServer before registering it for RPC.
	err = rpc.RegisterName("TribServer", tribrpc.Wrap(tribServer))
	if err != nil {
		return nil, err
	}

	// Setup the HTTP handler that will server incoming RPCs and
	// serve requests in a background goroutine.
	rpc.HandleHTTP()
	go http.Serve(listener, nil)

	storage, err := libstore.NewLibstore(masterServerHostPort, myHostPort, libstore.Never)
	if err != nil {
		return nil, err
	}

	tribServer.storage = storage

	return tribServer, nil
}
Example #27
0
// listen and run
func ListenAndServe(addr string) error {
	var netaddr net.Addr
	var err error
	if strings.Contains(addr, "/") {
		netaddr, err = net.ResolveUnixAddr("unix", addr)
		if err != nil {
			return err
		}
	} else {
		netaddr, err = net.ResolveTCPAddr("tcp", addr)
		if err != nil {
			return err
		}
	}
	// listen
	l, err := net.Listen(netaddr.Network(), netaddr.String())
	if err != nil {
		return err
	}
	// same with ServeRpc
	http.Handle(GetRpcPath(codecName), &rpcHandler{NewServerCodec})

	err = http.Serve(l, nil)
	return err
}
Example #28
0
// RunAdminServer starts tsuru administrative api
func RunAdminServer(dry bool) {
	log.Init()
	connString, err := config.GetString("database:url")
	if err != nil {
		connString = db.DefaultDatabaseURL
	}
	dbName, err := config.GetString("database:name")
	if err != nil {
		dbName = db.DefaultDatabaseName
	}
	fmt.Printf("Using the database %q from the server %q.\n\n", dbName, connString)
	if !dry {
		provisioner, err := getProvisioner()
		if err != nil {
			fmt.Printf("Warning: configuration didn't declare a provisioner, using default provisioner.\n")
		}
		app.Provisioner, err = provision.Get(provisioner)
		if err != nil {
			fatal(err)
		}
		fmt.Printf("Using %q provisioner.\n\n", provisioner)

		listen, err := config.GetString("admin-listen")
		if err != nil {
			fatal(err)
		}
		listener, err := net.Listen("tcp", listen)
		if err != nil {
			fatal(err)
		}
		fmt.Printf("tsuru HTTP server listening at %s...\n", listen)
		http.Handle("/", m)
		fatal(http.Serve(listener, nil))
	}
}
Example #29
0
func MakeLockService(servers []string, me int) *LockService {
	gob.Register(Op{})

	ls := new(LockService)
	ls.me = me
	ls.servers = servers
	ls.max = -1
	ls.locks = make(map[int]int)
	ls.requests = make(chan Request, 256)

	go ls.dequeueRequests()

	rpc.Register(ls)
	ls.px = MakePaxos(servers, me)
	rpc.HandleHTTP()
	listener, err := net.Listen("tcp", servers[me])

	if err != nil {
		panic(err)
	}

	http.Serve(listener, nil)

	return ls
}
Example #30
0
func main() {
	fmt.Printf("node %d starts\n", nid)
	node, err := paxos.NewPaxosNode(nid, numNodes, fakecallback)
	if err != nil {
		fmt.Println("Cannot start node.\n")
		fmt.Println(err)
		return
	}
	listener, err := net.Listen("tcp", fmt.Sprintf(":%d", config.Nodes[nid].Port))
	if err != nil {
		fmt.Printf("node %d cannot listen to port:%s\n", err)
		return
	}
	node.SetListener(&listener)
	rpc.HandleHTTP()
	go http.Serve(listener, nil)

	time.Sleep(5 * time.Second)

	for i := 0; i < 2; i++ {
		c := command.Command{strconv.Itoa(nid), strconv.Itoa(i), command.Put, i, ""}
		node.Replicate(&c)
	}

	for res := 0; res < 4; res++ {
		_, ok := <-done
		if !ok {
			break
		}
	}
	node.DumpLog()
	fmt.Printf("node %d closes\n", nid)
}