예제 #1
1
파일: web.go 프로젝트: remogatto/trs80
// Serve the website. This function blocks.
func serveWebsite() {
	port := 8080

	// Sanity check to make sure we're in the right directory.
	_, err := os.Stat("static/font.png")
	if err != nil {
		log.Fatal("You must be in the trs80 source directory (github.com/lkesteloot/trs80)")
	}

	// Create handlers.
	handlers := http.NewServeMux()
	handlers.Handle("/", webutil.GetHandler(http.HandlerFunc(homeHandler)))
	handlers.Handle("/ws", websocket.Handler(wsHandler))
	handlers.Handle("/static/", http.StripPrefix("/static/",
		http.FileServer(http.Dir("static"))))

	// Create server.
	address := fmt.Sprintf(":%d", port)
	server := http.Server{
		Addr:           address,
		Handler:        webutil.LoggingHandler(handlers),
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: http.DefaultMaxHeaderBytes,
	}

	// Start serving.
	log.Printf("Serving website on %s", address)
	err = server.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}
예제 #2
0
// 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)
}
예제 #3
0
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
}
예제 #4
0
파일: main.go 프로젝트: pedrohms/learninggo
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()
}
예제 #5
0
파일: server.go 프로젝트: houbl/docker
// 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
}
예제 #6
0
파일: server.go 프로젝트: jf/gwp
func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/process", process)
	server.ListenAndServe()
}
예제 #7
0
// 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
}
예제 #8
0
func main() {
	Values[1] = "z"
	Values[2] = "y"
	Values[3] = "x"
	Values[4] = "q"
	Values[5] = "w"
	Values[6] = "v"
	Values[7] = "u"
	Values[8] = "t"
	Values[9] = "s"
	Values[10] = "r"

	for _, each := range ListOfServers {
		HashingMapping[calculateHashValue(each)] = each
	}

	for k, _ := range Values {
		HashingMapping[calculateHashValue(strconv.Itoa(k))] = strconv.Itoa(k)
	}

	for k, _ := range HashingMapping {
		SortedHashingMappingKeys = append(SortedHashingMappingKeys, k)
	}

	sort.Strings(SortedHashingMappingKeys)
	mux := httprouter.New()
	mux.PUT("/keys/:key/:value", putDataTo)
	mux.GET("/keys/:key", getRequest)
	server := http.Server{
		Addr:    "0.0.0.0:8000",
		Handler: mux,
	}
	server.ListenAndServe()
}
예제 #9
0
파일: main.go 프로젝트: truszkowski/gomemo
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
}
예제 #10
0
파일: proxy.go 프로젝트: carriercomm/dlite
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)
}
예제 #11
0
// Serve starts the server (http.DefaultServeMux) on given port, loops forever.
func (s *ProxyServer) Serve(port int) error {
	server := http.Server{
		Addr:    fmt.Sprintf(":%d", port),
		Handler: s.mux,
	}
	return server.ListenAndServe()
}
예제 #12
0
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")

}
예제 #13
0
파일: api.go 프로젝트: hustcat/degraph
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)
}
예제 #14
0
파일: oidc.go 프로젝트: develrns/resilient
/*
main registers this RP's HTTP request handlers; creates the HTTPS client for issuing OP ID Token requests and starts its HTTP server.
*/
func main() {
	var (
		certPool *x509.CertPool
		server   http.Server
		err      error
	)

	//This aeadCipher is used to encrypt/decrypt the Authn Request Cookie that is used to pass the Authn Request State value
	//from the Authn Request to the Authn Response.
	aeadCipher, err = aead.NewAEADCipher()
	if err != nil {
		return
	}

	//Initialize an HTTPS capable client and replace the default aws HTTP client that doesn't support HTTPS
	certPool = x509.NewCertPool()
	certPool.AppendCertsFromPEM([]byte(certbndl.PemCerts))
	opClient = &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{RootCAs: certPool},
		},
	}

	//Start the service
	server = http.Server{Addr: ":443", ReadTimeout: 10 * time.Minute, WriteTimeout: 10 * time.Minute, ErrorLog: logger.Logger()}
	http.HandleFunc("/login", handleLogin)
	http.HandleFunc("/authn-token", handleAuthnToken)
	logger.Println("Starting oidc on " + exthost + ":443")
	err = server.ListenAndServeTLS("resilient-networks.crt", "resilient-networks.key")
	if err != nil {
		logger.Fatal(err)
	}

}
예제 #15
0
파일: api.go 프로젝트: jpoimboe/docker
// 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
}
예제 #16
0
func main() {
	var srv http.Server
	flag.BoolVar(&http2.VerboseLogs, "verbose", false, "Verbose HTTP/2 debugging.")
	flag.Parse()
	srv.Addr = *httpsAddr
	srv.ConnState = idleTimeoutHook()

	registerHandlers()

	if *prod {
		*hostHTTP = "http2.golang.org"
		*hostHTTPS = "http2.golang.org"
		log.Fatal(serveProd())
	}

	url := "https://" + httpsHost() + "/"
	log.Printf("Listening on " + url)
	http2.ConfigureServer(&srv, &http2.Server{})

	if *httpAddr != "" {
		go func() {
			log.Printf("Listening on http://" + httpHost() + "/ (for unencrypted HTTP/1)")
			log.Fatal(http.ListenAndServe(*httpAddr, nil))
		}()
	}

	go func() {
		log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
	}()
	select {}
}
예제 #17
0
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
}
예제 #18
0
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)
}
예제 #19
0
// 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
}
예제 #20
0
func main() {
	server := http.Server{
		Addr:    ":8080",
		Handler: &myHandler{},
	}
	server.ListenAndServe()
}
예제 #21
0
// 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)
}
예제 #22
0
// 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
}
예제 #23
0
파일: buildlet.go 프로젝트: way-2-go/build
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))
}
예제 #24
0
// 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)
}
예제 #25
0
func ExampleSessionMux() {
	sb := NewSrvSessionBuilder("", "/", "example", 60*60*1000, 10000)
	mux := NewSessionMux("/example", sb)
	mux.HFilterFunc("^.*$", func(hs *HTTPSession) HResult {
		log.D("filt 001")
		return HRES_CONTINUE
	})
	//http://localhost:8080/example/ok
	mux.HFunc("^/ok(\\?.*)?$", func(hs *HTTPSession) HResult {
		hs.MsgRes("OK")
		return HRES_RETURN
	})
	//http://localhost:8080/example/data
	mux.HFunc("^/data(\\?.*)?$", func(hs *HTTPSession) HResult {
		var tid int64
		var name string
		err := hs.ValidRVal(`
			tid,R|I,R:0
			name,R|S,L:0`, //valid the argument
			&tid, &name)
		if err != nil {
			return hs.MsgResE(1, err.Error())
		}
		return hs.MsgRes(fmt.Sprintf("%v:%v", tid, name))
	})
	mux.HFunc("^/mdata(\\?.*)?$", func(hs *HTTPSession) HResult {
		hs.W.Write([]byte("some data\n"))
		return HRES_RETURN
	})
	s := http.Server{Addr: ":8080", Handler: mux}
	err := s.ListenAndServe()
	if err != nil {
		fmt.Println(err)
	}
}
예제 #26
0
func main() {
	var srv http.Server
	flag.BoolVar(&http2.VerboseLogs, "verbose", false, "Verbose HTTP/2 debugging.")
	flag.Parse()
	srv.Addr = *addr

	registerHandlers()

	if *prod {
		*httpAddr = "http2.golang.org"
		log.Fatal(serveProd())
	}

	url := "https://" + *addr + "/"
	log.Printf("Listening on " + url)
	http2.ConfigureServer(&srv, &http2.Server{})

	if *httpAddr != "" {
		go func() { log.Fatal(http.ListenAndServe(*httpAddr, nil)) }()
	}

	go func() {
		log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
	}()
	if *openFirefox && runtime.GOOS == "darwin" {
		time.Sleep(250 * time.Millisecond)
		exec.Command("open", "-b", "org.mozilla.nightly", "https://localhost:4430/").Run()
	}
	select {}
}
예제 #27
0
파일: webgo.go 프로젝트: IntelliQru/webgo
func Run() {
	var r *int = flag.Int("r", 0, "read timeout")
	var w *int = flag.Int("w", 0, "write timeout")

	port := CFG.Int("port")

	if port == 0 {
		port = 80
	}

	host := CFG.Str("host")
	if host == "" {
		host = "127.0.0.1"
	}

	address := fmt.Sprintf("%s:%d", host, port)
	LOGGER.Log("WebGO running", address)

	server := http.Server{
		Addr:         address,
		ReadTimeout:  time.Duration(*r) * time.Second,
		WriteTimeout: time.Duration(*w) * time.Second,
		Handler:      &app,
	}

	//server.SetKeepAlivesEnabled(false)

	err := server.ListenAndServe()
	if err != nil {
		LOGGER.Fatal(err)
	}

}
예제 #28
0
파일: server.go 프로젝트: jf/gwp
func main() {
	server := http.Server{
		Addr:    "127.0.0.1:8080",
		Handler: nil,
	}
	server.ListenAndServe()
}
예제 #29
0
파일: api.go 프로젝트: juniorz/docker
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)
}
예제 #30
0
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
}