Exemplo n.º 1
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 {}
}
Exemplo n.º 2
0
func (e *endpoint) Serve() error {
	// TODO: Currently only support single server per endpoint
	if len(e.OriginServers) > 1 {
		return errors.New("Currently only 1 origin server per endpoint is supported.")
	}

	// Create http2 server
	var srv http.Server

	// Set Port
	srv.Addr = e.Address

	// Mux setup
	router := http.NewServeMux()

	// Set mux
	srv.Handler = router

	// Set handlers
	setHandlers(router, e)

	err := http2.ConfigureServer(&srv, &http2.Server{})
	if err != nil {
		return err
	}

	log.Printf("Listening on %s", srv.Addr)
	srv.ListenAndServeTLS(e.Certs.CertFile, e.Certs.KeyFile)

	return nil
}
Exemplo n.º 3
0
// Run starts an http server using the provided config struct.
//
// This method configures the process to listen for termination signals (SIGINT
// and SIGTERM) to trigger a graceful shutdown by way of the graceful package
// (https://github.com/tylerb/graceful).
func Run(conf Config) {
	srv := setup(conf)

	http2.ConfigureServer(srv.Server, nil)

	if conf.OnStarting != nil {
		conf.OnStarting()
	}

	var err error
	if conf.TLSCert != "" {
		err = srv.ListenAndServeTLS(conf.TLSCert, conf.TLSKey)
	} else {
		err = srv.ListenAndServe()
	}

	if err != nil {
		log.Error(errors.Wrap(err, "failed to start server"))
		os.Exit(1)
	}

	if conf.OnStopped != nil {
		conf.OnStopped()
	}
	os.Exit(0)
}
Exemplo n.º 4
0
func listenAndServeProtoHTTP(listener net.Listener, tlsConfig *tls.Config) error {
	srv := http.Server{
		TLSConfig: tlsConfig,
		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			reqBody, err := ioutil.ReadAll(r.Body)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			if err := r.Body.Close(); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			args := EchoRequest{}
			if err := proto.Unmarshal(reqBody, &args); err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}
			reply := EchoResponse{Msg: args.Msg}
			respBody, err := proto.Marshal(&reply)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			w.Header().Set(contentType, xProtobuf)
			w.Write(respBody)
		}),
	}

	http2.ConfigureServer(&srv, nil)

	return srv.Serve(listener)
}
Exemplo n.º 5
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 {}
}
Exemplo n.º 6
0
func startTLS() {
	srv := &http.Server{Addr: *tlsListeningAddr}
	http2.ConfigureServer(srv, nil)

	log.Printf("TLS HTTP2 server listening on %q", *tlsListeningAddr)
	log.Fatal(srv.ListenAndServeTLS(*tlsCertFile, *tlsKeyFile))
}
Exemplo n.º 7
0
func (s *Server) newH2Server(tlsConfig *tls.Config, laddr string) (*http.Server, func(error)) {
	var mu sync.Mutex
	var h2sleep time.Duration = 1
	h2Server := &http.Server{
		Addr:      laddr,
		Handler:   http.HandlerFunc(s.serveH2),
		TLSConfig: tlsConfig,
		ConnState: func(c net.Conn, s http.ConnState) {
			if s == http.StateNew {
				mu.Lock()
				h2sleep = 1
				mu.Unlock()
			}
		},
	}
	http2.ConfigureServer(h2Server, &http2.Server{
		MaxReadFrameSize: s.H2BufSize,
	})

	afterServeError := func(err error) {
		Log.Error("h2 server failed", zap.Error(err))
		mu.Lock()
		if h2sleep < s.H2RetryMaxSecond {
			h2sleep++
		}
		sec := h2sleep
		mu.Unlock()
		time.Sleep(time.Second * sec)
	}
	return h2Server, afterServeError
}
Exemplo n.º 8
0
func main() {
	var httpServer http.Server
	var httpsServer http.Server
	http2.VerboseLogs = true
	http2.ConfigureServer(&httpsServer, nil)

	http.HandleFunc("/auth", authHandler)
	http.HandleFunc("/", handler)
	http.HandleFunc("/js", jsHandler)

	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		log.Println("start http listening :18888")
		httpServer.Addr = ":18888"
		log.Println(httpServer.ListenAndServe())
		wg.Done()
	}()
	go func() {
		log.Println("start https listening :18889")
		httpsServer.Addr = ":18889"
		log.Println(httpsServer.ListenAndServeTLS("server.crt", "server.key"))
		wg.Done()
	}()
	wg.Wait()
}
Exemplo n.º 9
0
func main() {
	router := lib.NewRouter()
	srvTLS := &http.Server{Addr: ":4000", Handler: router}

	log.Println("Listening...")
	http2.ConfigureServer(srvTLS, &http2.Server{})
	srvTLS.ListenAndServeTLS("openssl/server.crt", "openssl/server.key")
}
Exemplo n.º 10
0
// Server returns the internal *http.Server.
func (e *Echo) Server(addr string) *http.Server {
	s := &http.Server{Addr: addr}
	s.Handler = e
	if e.http2 {
		http2.ConfigureServer(s, nil)
	}
	return s
}
Exemplo n.º 11
0
// Server returns the internal *http.Server.
func (e *Echo) Server(addr string) *http.Server {
	s := &http.Server{Addr: addr, Handler: e}
	// TODO: Remove in Go 1.6+
	if e.http2 {
		http2.ConfigureServer(s, nil)
	}
	return s
}
Exemplo n.º 12
0
func NewServer(port string, handler http.Handler) ListenAndServer {
	addr := fmt.Sprintf(":%s", port)
	server := &http.Server{
		Addr:    addr,
		Handler: handler,
	}
	http2.ConfigureServer(server, nil)
	return server
}
Exemplo n.º 13
0
func startWebServer() {
	key := "/" + *accessKey + "/"
	mux := http.NewServeMux()
	mux.HandleFunc(key+"upload", upload)
	mux.Handle(key, http.StripPrefix(key, http.FileServer(assetFS())))
	mux.Handle(key+"f/", http.StripPrefix(key+"f/", http.FileServer(http.Dir(*rootDir))))

	if *h1Port != "" {
		log.Println("http://localhost" + *h1Port + key)
		s := &http.Server{
			Addr:    *h1Port,
			Handler: mux,
		}

		http2.ConfigureServer(s, nil)

		go func() {
			err := s.ListenAndServe()
			if err != nil {
				log.Fatal("HTTP server error:", err)
			}
		}()
	}

	if *h2Port != "" {
		log.Println("https://localhost" + *h2Port + key)

		s := &http.Server{
			Addr:      *h2Port,
			Handler:   mux,
			TLSConfig: CreateTLS(),
		}

		http2.ConfigureServer(s, nil)

		go func() {
			err := s.ListenAndServeTLS("", "")
			if err != nil {
				log.Fatal("HTTPS/2 server error:", err)
			}
		}()
	}
}
Exemplo n.º 14
0
func main() {
	var srv http.Server

	srv.Addr = ":8000"
	http2.ConfigureServer(&srv, nil)

	http.HandleFunc("/", HelloWorld)
	http.HandleFunc("/favicon.ico", Error404)
	log.Fatal(srv.ListenAndServeTLS("localhost.crt", "localhost.key"))
}
Exemplo n.º 15
0
func main() {
	var srv http.Server
	srv.Addr = ":12345"
	authenticator := auth.NewDigestAuthenticator("063.jp", secret)
	http.HandleFunc("/", authenticator.Wrap(func(res http.ResponseWriter, req *auth.AuthenticatedRequest) {
		http.FileServer(http.Dir("/var/www/html/SS/")).ServeHTTP(res, &req.Request)
	}))
	http2.ConfigureServer(&srv, &http2.Server{})
	srv.ListenAndServeTLS("../key/server.crt", "../key/server.key")
}
Exemplo n.º 16
0
// startClusterListener starts cluster request listeners during postunseal. It
// is assumed that the state lock is held while this is run.
func (c *Core) startClusterListener() error {
	if c.clusterListenerShutdownCh != nil {
		c.logger.Printf("[ERR] core/startClusterListener: attempt to set up cluster listeners when already set up")
		return fmt.Errorf("cluster listeners already setup")
	}

	if c.clusterListenerSetupFunc == nil {
		c.logger.Printf("[ERR] core/startClusterListener: cluster listener setup function has not been set")
		return fmt.Errorf("cluster listener setup function has not been set")
	}

	if c.clusterAddr == "" {
		c.logger.Printf("[TRACE] core/startClusterListener: clustering disabled, starting listeners")
		return nil
	}

	c.logger.Printf("[TRACE] core/startClusterListener: starting listeners")

	lns, handler, err := c.clusterListenerSetupFunc()
	if err != nil {
		return err
	}

	tlsConfig, err := c.ClusterTLSConfig()
	if err != nil {
		c.logger.Printf("[ERR] core/startClusterListener: failed to get tls configuration: %v", err)
		return err
	}

	tlsLns := make([]net.Listener, 0, len(lns))
	for _, ln := range lns {
		tlsLn := tls.NewListener(ln, tlsConfig)
		tlsLns = append(tlsLns, tlsLn)
		server := &http.Server{
			Handler: handler,
		}
		http2.ConfigureServer(server, nil)
		c.logger.Printf("[TRACE] core/startClusterListener: serving cluster requests on %s", tlsLn.Addr())
		go server.Serve(tlsLn)
	}

	c.clusterListenerShutdownCh = make(chan struct{})
	c.clusterListenerShutdownSuccessCh = make(chan struct{})

	go func() {
		<-c.clusterListenerShutdownCh
		c.logger.Printf("[TRACE] core/startClusterListener: shutting down listeners")
		for _, tlsLn := range tlsLns {
			tlsLn.Close()
		}
		close(c.clusterListenerShutdownSuccessCh)
	}()

	return nil
}
Exemplo n.º 17
0
func main() {
	var httpServer http.Server
	http2.VerboseLogs = true
	httpServer.Addr = ":8080"
	http2.ConfigureServer(&httpServer, nil)
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Welcome to test HTTP2 page %q\n", html.EscapeString(r.URL.Path))
		ShowRequestInfoHandler(w, r)
	})
	log.Fatal(httpServer.ListenAndServeTLS("localhost.cert", "localhost.key"))
}
Exemplo n.º 18
0
func main() {
	var srv http.Server
	//http2.VerboseLogs = true
	srv.Addr = ":8443"
	http2.ConfigureServer(&srv, nil)
	http.HandleFunc("/", get)
	err := srv.ListenAndServeTLS("cert.pem", "key.pem")
	if err != nil {
		log.Fatal(err)
	}
}
Exemplo n.º 19
0
func main() {
	var srv core.Server

	srv.Addr = ":8080"
	http2.ConfigureServer(&srv.Server, nil)

	http.HandleFunc("/", handlers.NewDirList().Reply)

	srv.Init()
	srv.Run()
	srv.Quit()
}
Exemplo n.º 20
0
func (s *Http2Server) ListenAndServeTLS(config *tls.Config) error {
	srv := http.Server{
		Addr:      s.Base.Node.Addr,
		Handler:   s.Handler,
		TLSConfig: config,
	}
	if srv.Handler == nil {
		srv.Handler = http.HandlerFunc(s.HandleRequest)
	}
	http2.ConfigureServer(&srv, nil)
	return srv.ListenAndServeTLS("", "")
}
Exemplo n.º 21
0
func main() {
	//TODO os.Getenv("DOMAIN")
	configureSocial()
	// Load all configuration
	appCfg = &AppConfig{}
	rdisCfg := &RedisConfig{}
	natsCfg := &NatsConfig{}
	loadConfiguration(appCfg, rdisCfg, natsCfg)

	//Mongo configuration
	log.Infoln("Loading configuration of Redis")
	rdisStorage := storage.NewRedisStorage()
	rdisStorage.URL = rdisCfg.URI
	rdisStorage.Password = rdisCfg.Password
	rdisStorage.Database = rdisCfg.DB
	tokenStorage = rdisStorage
	err := tokenStorage.OpenSession()
	defer tokenStorage.CloseSession()
	if err != nil {
		log.Panic(err)
	}

	log.Infoln("Initializing NATS proxy")
	proxyConn, _ := nats.Connect(natsCfg.Endpoint)
	multiProxy, err := natsproxy.NewNatsProxy(proxyConn)
	multiProxy.AddHook("/login.*", loginHook)
	defer proxyConn.Close()
	if err != nil {
		log.Panic("Cannot initialize NATS proxy")
	}

	log.Infoln("Registering handlers")
	//Handle login and register
	mux := http.NewServeMux()
	log.Infoln("Start listening on " + appCfg.Port)
	mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
		log.Println("Handling")
		transformToken(req)
		log.Println(req.Header)
		multiProxy.ServeHTTP(rw, req)
	})

	//Init HTTP2 server
	srv := &http.Server{
		Addr:    ":" + appCfg.Port,
		Handler: mux,
	}
	http2.ConfigureServer(srv, nil)
	serveErr := srv.ListenAndServe()
	if serveErr != nil {
		log.Errorln(serveErr)
	}
}
Exemplo n.º 22
0
// ListenAndServe creates a listener and serves handler on it, closing
// the listener when signalled by the stopper.
func ListenAndServe(stopper *stop.Stopper, handler http.Handler, addr net.Addr, tlsConfig *tls.Config) (net.Listener, error) {
	ln, err := Listen(addr, tlsConfig)
	if err != nil {
		return nil, err
	}

	var mu sync.Mutex
	activeConns := make(map[net.Conn]struct{})

	httpServer := http.Server{
		TLSConfig: tlsConfig,
		Handler:   handler,
		ConnState: func(conn net.Conn, state http.ConnState) {
			mu.Lock()
			switch state {
			case http.StateNew:
				activeConns[conn] = struct{}{}
			case http.StateClosed:
				delete(activeConns, conn)
			}
			mu.Unlock()
		},
	}
	if err := http2.ConfigureServer(&httpServer, nil); err != nil {
		return nil, err
	}

	stopper.RunWorker(func() {
		if err := httpServer.Serve(ln); err != nil && !IsClosedConnection(err) {
			log.Fatal(err)
		}

		<-stopper.ShouldStop()

		mu.Lock()
		for conn := range activeConns {
			conn.Close()
		}
		mu.Unlock()
	})

	stopper.RunWorker(func() {
		<-stopper.ShouldDrain()
		// Some unit tests manually close `ln`, so it may already be closed
		// when we get here.
		if err := ln.Close(); err != nil && !IsClosedConnection(err) {
			log.Fatal(err)
		}
	})

	return ln, nil
}
Exemplo n.º 23
0
func main() {
	cwd, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}

	srv := &http.Server{
		Addr:    ":8000", // Normally ":443"
		Handler: http.FileServer(http.Dir(cwd)),
	}
	http2.ConfigureServer(srv, &http2.Server{})
	log.Fatal(srv.ListenAndServe())
}
Exemplo n.º 24
0
func main() {
	var src http.Server
	http2.VerboseLogs = true
	src.Addr = ":8080"
	http2.ConfigureServer(&src, nil)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hi testerer %q \n", html.EscapeString(r.URL.Path))
		ShowRequestInfoHandler(w, r)

	})
	log.Fatal(src.ListenAndServeTLS("server.crt", "server.key"))
}
Exemplo n.º 25
0
// Serve starts the server. It blocks until the server quits.
func (s *Server) Serve() error {
	server := &http.Server{
		Addr:    s.address,
		Handler: s,
	}

	if s.HTTP2 {
		// TODO: This call may not be necessary after HTTP/2 is merged into std lib
		http2.ConfigureServer(server, nil)
	}

	for _, vh := range s.vhosts {
		// Execute startup functions now
		for _, start := range vh.config.Startup {
			err := start()
			if err != nil {
				return err
			}
		}

		// Execute shutdown commands on exit
		if len(vh.config.Shutdown) > 0 {
			go func(vh virtualHost) {
				// Wait for signal
				interrupt := make(chan os.Signal, 1)
				signal.Notify(interrupt, os.Interrupt, os.Kill)
				<-interrupt

				// Run callbacks
				exitCode := 0
				for _, shutdownFunc := range vh.config.Shutdown {
					err := shutdownFunc()
					if err != nil {
						exitCode = 1
						log.Println(err)
					}
				}
				os.Exit(exitCode) // BUG: Other shutdown goroutines might be running; use sync.WaitGroup
			}(vh)
		}
	}

	if s.tls {
		var tlsConfigs []TLSConfig
		for _, vh := range s.vhosts {
			tlsConfigs = append(tlsConfigs, vh.config.TLS)
		}
		return ListenAndServeTLSWithSNI(server, tlsConfigs)
	}
	return server.ListenAndServe()
}
Exemplo n.º 26
0
func (e *Echo) run(s *http.Server, files ...string) {
	s.Handler = e
	// TODO: Remove in Go 1.6+
	if e.http2 {
		http2.ConfigureServer(s, nil)
	}
	if len(files) == 0 {
		e.logger.Fatal(s.ListenAndServe())
	} else if len(files) == 2 {
		e.logger.Fatal(s.ListenAndServeTLS(files[0], files[1]))
	} else {
		e.logger.Fatal("invalid TLS configuration")
	}
}
Exemplo n.º 27
0
// Init initializes the server
func (srv *Server) Init() error {
	// Settings
	srv.Addr = ":8080"
	http2.VerboseLogs = true

	http2.ConfigureServer(&srv.Server, nil)

	// Gorilla's mux router
	srv.mux = mux.NewRouter()

	// Handlers
	/// http.HandleFunc("/", testResponse)
	return nil
}
Exemplo n.º 28
0
func main() {
	var s http.Server
	http2.VerboseLogs = true
	s.Addr = ":8080"

	http2.ConfigureServer(&s, nil)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain")
		fmt.Fprintf(w, "Hello World")
	})

	log.Fatal(s.ListenAndServeTLS("key/server.crt", "key/server.key"))
}
Exemplo n.º 29
0
func main() {
	var server http.Server

	http2.VerboseLogs = false //set true for verbose console output
	server.Addr = ":8080"

	log.Println("Starting server on localhost port 8080...")

	http2.ConfigureServer(&server, nil)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "URL: %q\n", html.EscapeString(r.URL.Path))
		ShowRequestInfoHandler(w, r)
	})

	log.Fatal(server.ListenAndServeTLS("localhost.cert", "localhost.key"))
}
Exemplo n.º 30
0
func main() {
	router := httprouter.New()

	router.GET("/", api.Index)
	router.POST("/bench", api.Bench)

	srv := http.Server{
		Addr:    ":8080",
		Handler: router,
	}

	http2.ConfigureServer(&srv, &http2.Server{})

	log.Printf("%s\n", HEADER)
	log.Printf("Starting server on %s\n", srv.Addr)
	log.Fatal(srv.ListenAndServe())
}