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)) }
func main() { flag.Parse() ln, err := net.Listen("tcp", ":"+PORT) if err != nil { glog.Fatalf("Listen(%s) error: %s", PORT, err) } cert, err := getCertificate(nil) if err != nil { glog.Fatalf("getCertificate error: %s", err) } tlsConfig := &tls.Config{ Certificates: []tls.Certificate{*cert}, // GetCertificate: getCertificate, } s := &http.Server{ Handler: http.HandlerFunc(handler), TLSConfig: tlsConfig, } http2.ConfigureServer(s, &http2.Server{}) glog.Infof("ListenAndServe on %s\n", ln.Addr().String()) s.Serve(tls.NewListener(ln, tlsConfig)) }
func main() { flag.Parse() addr := fmt.Sprintf("%s:%s", os.Getenv("HOST"), os.Getenv("PORT")) ln, err := net.Listen("tcp", addr) if err != nil { glog.Fatalf("Listen(%s) error: %s", addr, err) } cert, err := getCertificate(nil) if err != nil { glog.Fatalf("getCertificate error: %s", err) } tlsConfig := &tls.Config{ Certificates: []tls.Certificate{*cert}, // GetCertificate: getCertificate, } s := &http.Server{ Handler: http.HandlerFunc(handler), TLSConfig: tlsConfig, } // http2.VerboseLogs = true http2.ConfigureServer(s, &http2.Server{}) glog.Infof("ListenAndServe on %s\n", ln.Addr().String()) s.Serve(tls.NewListener(ln, tlsConfig)) }
func ListenAndServeSecure(addr string, certFile string, keyFile string, numOfServers int, handler http.Handler) error { port, err := parsePort(addr) if err != nil { return err } if handler == nil { handler = http.DefaultServeMux } go func() { httpServer := &http.Server{Addr: addr, Handler: altProtoMiddleware(handler, port)} http2.ConfigureServer(httpServer, nil) err := httpServer.ListenAndServeTLS(certFile, keyFile) if err != nil { panic(err) } }() cert, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { return err } server := &QuicSpdyServer{Addr: addr, Handler: handler, numOfServers: numOfServers, Certificate: cert, isSecure: true} return server.ListenAndServe() }
func (this *Server) Start() error { logger.Debug("serverConfig is %#v", this.config) this.router.matcher.sort() conf := this.config server := &http.Server{Handler: http.HandlerFunc(this.serverHttpHandler), MaxHeaderBytes: conf.MaxHeaderBytes, TLSConfig: conf.TLSConfig} if conf.ReadTimeout > 0 { server.ReadTimeout = conf.ReadTimeout } if conf.WriteTimeout > 0 { server.WriteTimeout = conf.WriteTimeout } http2.ConfigureServer(server, &http2.Server{}) var err error this.listener, err = net.Listen("tcp", conf.serverAddr) if err != nil { return errors.New(logger.Error("listen [%s] fail:%s", conf.serverAddr, err)) } logger.Info("start HttpServer :%s", conf.serverAddr) keepAliveListrener := tcpKeepAliveListener{this.listener.(*net.TCPListener)} if conf.TLSConfig != nil { conf.TLSConfig.NextProtos = append(conf.TLSConfig.NextProtos, "http/1.1") go server.Serve(tls.NewListener(keepAliveListrener, conf.TLSConfig)) } else { go server.Serve(keepAliveListrener) } return nil }
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 {} }
func listenHttp() { log.Printf("Listening on port :%s\n", *httpport) port := fmt.Sprintf(":%s", *httpport) if secure { log.Println("Serving via TLS") server := &http.Server{Addr: port, Handler: nil} if os.Getenv("DISABLE_HTTP2") == "" { http2.ConfigureServer(server, nil) log.Println("HTTP/2 support is enabled.") } else { log.Println("HTTP/2 support is disabled.") } if err := server.ListenAndServeTLS(CertFilePath, KeyFilePath); err != nil { log.Fatalf("Error starting server: %s\n", err.Error()) } } else { if err := http.ListenAndServe(port, nil); err != nil { log.Fatalf("Error starting server: %s\n", err.Error()) } } }
// Create a new graceful server configuration func newGracefulServer(mux *http.ServeMux, http2support bool, addr string, shutdownTimeout time.Duration) *graceful.Server { // Server configuration s := &http.Server{ Addr: addr, Handler: mux, // The timeout values is also the maximum time it can take // for a complete page of Server-Sent Events (SSE). ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } if http2support { // Enable HTTP/2 support http2.ConfigureServer(s, nil) } gracefulServer := &graceful.Server{ Server: s, Timeout: shutdownTimeout, } // Handle ctrl-c gracefulServer.ShutdownInitiated = runShutdown return gracefulServer }
// 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 }
// 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 }
func newServer(addr string, h http.Handler, HTTP2 bool) *http.Server { srv := &http.Server{ Addr: addr, Handler: h, ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, } if HTTP2 { http2.ConfigureServer(srv, &http2.Server{}) } return srv }
func (e *Echo) run(s *http.Server, files ...string) { s.Handler = e if e.http2 { http2.ConfigureServer(s, nil) } if len(files) == 0 { log.Fatal(s.ListenAndServe()) } else if len(files) == 2 { log.Fatal(s.ListenAndServeTLS(files[0], files[1])) } else { log.Fatal("echo => invalid TLS configuration") } }
// 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() }
func (s *Server) Serve() error { server := &http.Server{ Addr: s.address, Handler: s, } if s.HTTP2 { http2.ConfigureServer(server, nil) } for _, vh := range s.vhosts { 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) }(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() }
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") } }
func main() { r := httprouter.New() r.GET("/", index) r.ServeFiles("/webapp/*filepath", http.Dir("webapp")) r.GET("/api/fs/*filepath", fsRead) r.PUT("/api/fs/*filepath", fsWrite) r.DELETE("/api/fs/*filepath", fsDelete) r.POST("/api/fs/*filepath", fsSpecial) s := &http.Server{} s.Addr = ":8080" s.Handler = r http2.ConfigureServer(s, nil) log.Fatalln(s.ListenAndServeTLS("cert.pem", "key.pem")) }
func ListenAndServe(addr string, numOfServers int, handler http.Handler) error { port, err := parsePort(addr) if err != nil { return err } if handler == nil { handler = http.DefaultServeMux } httpServer := &http.Server{Addr: addr, Handler: altProtoMiddleware(handler, port)} http2.ConfigureServer(httpServer, nil) go httpServer.ListenAndServe() server := &QuicSpdyServer{Addr: addr, Handler: handler, numOfServers: numOfServers, isSecure: false} return server.ListenAndServe() }
// 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() { interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt, os.Kill) // TODO: syscall.SIGQUIT? (Ctrl+\, Unix-only) <-interrupt for _, shutdownFunc := range vh.config.Shutdown { err := shutdownFunc() if err != nil { log.Fatal(err) } } os.Exit(0) }() } } if s.tls { var tlsConfigs []TLSConfig for _, vh := range s.vhosts { tlsConfigs = append(tlsConfigs, vh.config.TLS) } return ListenAndServeTLSWithSNI(server, tlsConfigs) } return server.ListenAndServe() }
func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello world") }) var srv http.Server log.Printf("Listening on https://localhost:4430/") srv.Addr = "localhost:4430" http2.ConfigureServer(&srv, &http2.Server{}) closeFirefox() go func() { log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key")) }() time.Sleep(500 * time.Millisecond) exec.Command("open", "-b", "org.mozilla.nightly", "https://localhost:4430/").Run() select {} }
func standUpServer() error { srv := &http.Server{Addr: hostport} reg, router, cxt := cookoo.Cookoo() buildRegistry(reg, router, cxt) // Our main datasource is the Medium, which manages channels. m := pubsub.NewMedium() cxt.AddDatasource(pubsub.MediumDS, m) cxt.Put("routes", reg.Routes()) http2.ConfigureServer(srv, &http2.Server{}) srv.Handler = web.NewCookooHandler(reg, router, cxt) srv.ListenAndServeTLS("../server/server.crt", "../server/server.key") return nil }
func ListenAndServeRaw(addr string, certFile string, keyFile string, numOfServers int, quicHandler http.Handler, nonQuicHandler http.Handler) error { port, err := parsePort(addr) if err != nil { return err } if quicHandler == nil { return errors.New("quic handler should be provided") } if nonQuicHandler != nil { go func() { httpServer := &http.Server{Addr: addr, Handler: AltProtoMiddleware(nonQuicHandler, port)} http2.ConfigureServer(httpServer, nil) if certFile != "" && keyFile != "" { if err := httpServer.ListenAndServeTLS(certFile, keyFile); err != nil { panic(err) } } else { if err := httpServer.ListenAndServe(); err != nil { panic(err) } } }() } server := &QuicSpdyServer{Addr: addr, Handler: quicHandler, numOfServers: numOfServers} if certFile != "" && keyFile != "" { cert, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { panic(err) } server.isSecure = true server.Certificate = cert } else { server.isSecure = false } return server.ListenAndServe() }
func main() { srv := &http.Server{ Addr: ":5500", } reg, router, cxt := cookoo.Cookoo() buildRegistry(reg, router, cxt) // Our main datasource is the Medium, which manages channels. m := pubsub.NewMedium() cxt.AddDatasource(pubsub.MediumDS, m) cxt.Put("routes", reg.Routes()) http2.ConfigureServer(srv, &http2.Server{}) srv.Handler = web.NewCookooHandler(reg, router, cxt) srv.ListenAndServeTLS("server.crt", "server.key") }
func serveProdTLS() error { c, err := googlestorage.NewServiceClient() if err != nil { return err } slurp := func(key string) ([]byte, error) { const bucket = "http2-demo-server-tls" rc, _, err := c.GetObject(&googlestorage.Object{ Bucket: bucket, Key: key, }) if err != nil { return nil, fmt.Errorf("Error fetching GCS object %q in bucket %q: %v", key, bucket, err) } defer rc.Close() return ioutil.ReadAll(rc) } certPem, err := slurp("http2.golang.org.chained.pem") if err != nil { return err } keyPem, err := slurp("http2.golang.org.key") if err != nil { return err } cert, err := tls.X509KeyPair(certPem, keyPem) if err != nil { return err } srv := &http.Server{ TLSConfig: &tls.Config{ Certificates: []tls.Certificate{cert}, }, } http2.ConfigureServer(srv, &http2.Server{}) ln, err := net.Listen("tcp", ":443") if err != nil { return err } return srv.Serve(tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, srv.TLSConfig)) }
// NewApp creates a new App func NewApp(port int) *App { a := &App{} certRoot := "/etc/ssl/zqz/zqzca" a.certPath = fmt.Sprintf("%s.crt", certRoot) a.keyPath = fmt.Sprintf("%s.key", certRoot) a.port = fmt.Sprintf(":%d", port) a.Router = mux.NewRouter().StrictSlash(true) chain := alice.New().Then(a.Router) a.Server = &http.Server{ Addr: a.port, Handler: chain, } http2.ConfigureServer(a.Server, nil) return a }
func (s *Server) Serve() { if err := s.Listen(""); err != nil { s.fatalf("Listen error: %v", err) } go runTestHarnessIntegration(s.listener) srv := &http.Server{ Handler: s, } // TODO: allow configuring src.ErrorLog (and plumb through to // Google Cloud Logging when run on GCE, eventually) // Setup the NPN NextProto map for HTTP/2 support: http2.ConfigureServer(srv, &s.H2Server) err := srv.Serve(s.throttleListener()) if err != nil { s.printf("Error in http server: %v\n", err) os.Exit(1) } }
func main() { // Initialize server and parse flags. var s http.Server flag.BoolVar(&http2.VerboseLogs, "verbose", false, "verbose HTTP/2 debugging") flag.Parse() s.Addr = *addr // Open database and retrieve posts. p, err := database.GetPosts() if err != nil { log.Fatal(err) } // Registers handlers and logs URL // and port, configured for HTTP/2. registerHandlers(p) url := "https://" + *addr + "/" log.Printf("Listening on " + url) http2.ConfigureServer(&s, &http2.Server{}) // Starts listening over regular HTTP // if the "-http" flag is non-empty. if *httpAddr != "" { go func() { log.Fatal(http.ListenAndServe(*httpAddr, nil)) }() } // Concurrently begins listening at URL for // tls encrypted HTTP/2 communications. go func() { log.Fatal(s.ListenAndServeTLS("out/dev.crt", "out/dev.key")) }() // Blocks forever. select {} }
func main() { fmt.Printf("Starting nano server...\nServing directory: %s\n", dir) if crtFile != "" && keyFile != "" { fmt.Printf("Using certificate: %s\nUsing private key: %s\n", crtFile, keyFile) } else { fmt.Println("No certificate and/or key provided!") } srv := &http.Server{ Addr: port, Handler: &requestLogger{http.FileServer(http.Dir(dir))}, } http2.ConfigureServer(srv, nil) if crtFile != "" && keyFile != "" { fmt.Printf("Starting HTTPS server on port %s... Kill with [Ctrl]-[C]!\n", port) if err := srv.ListenAndServeTLS(crtFile, keyFile); err != nil { fmt.Printf("Error: %s\n", err) } } else { fmt.Printf("Starting HTTP server on port %s... Kill with [Ctrl]-[C]!\n", port) if err := srv.ListenAndServe(); err != nil { fmt.Printf("Error: %s\n", err) } } }
func main() { initFlags() if len(options.Configs) > 0 { for _, configDef := range options.Configs { log.Printf("Creating config file: %v => %v\n", configDef.template, configDef.output) createConfig(configDef.template, configDef.output) } log.Println() } if len(options.Services) > 0 { tlsConfig := &tls.Config{ RootCAs: x509.NewCertPool(), InsecureSkipVerify: options.SkipCertValidation, } transport := &http.Transport{TLSClientConfig: tlsConfig} if len(options.CACerts) > 0 { for _, caFile := range options.CACerts { // Load our trusted certificate path pemData, err := ioutil.ReadFile(caFile) if err != nil { log.Fatal("Couldn't read CA file, ", caFile, ": ", err) } if ok := tlsConfig.RootCAs.AppendCertsFromPEM(pemData); !ok { log.Fatal("Couldn't load PEM data from CA file, ", caFile) } } } for _, serviceDef := range options.Services { actualHost, port, err := validateServiceHost(serviceDef.url.Host) if err != nil { if options.FailOnUnknownServices { log.Fatalf("Unknown service host: %s", serviceDef.url.Host) } else { log.Printf("Unknown service host: %s", serviceDef.url.Host) } } else { if len(port) > 0 { actualHost += ":" + port } serviceDef.url.Host = actualHost } log.Printf("Creating service proxy: %v => %v\n", serviceDef.prefix, serviceDef.url.String()) rp := httputil.NewSingleHostReverseProxy(serviceDef.url) rp.Transport = transport http.Handle(serviceDef.prefix, http.StripPrefix(serviceDef.prefix, rp)) } log.Println() } if options.ServeWww { httpDir := http.Dir(options.StaticDir) staticHandler := http.FileServer(httpDir) if options.StaticCacheMaxAge > 0 { staticHandler = maxAgeHandler(options.StaticCacheMaxAge.Seconds(), staticHandler) } if len(options.DefaultPage) > 0 { staticHandler = defaultPageHandler(options.DefaultPage, httpDir, staticHandler) } if options.CompressHandler { staticHandler = handlers.CompressHandler(staticHandler) } http.Handle(options.StaticPrefix, staticHandler) } log.Printf("Listening on :%d\n", options.Port) log.Println() registerMimeTypes() srv := &http.Server{ Addr: fmt.Sprintf(":%d", options.Port), } http2.ConfigureServer(srv, &http2.Server{}) var handler http.Handler = http.DefaultServeMux if options.AccessLogging { handler = handlers.CombinedLoggingHandler(os.Stdout, handler) } srv.Handler = handler if len(options.TlsCertFile) > 0 && len(options.TlsKeyFile) > 0 { log.Fatal(srv.ListenAndServeTLS(options.TlsCertFile, options.TlsKeyFile)) } else { log.Fatal(srv.ListenAndServe()) } }