Ejemplo n.º 1
0
func runHostCmd(cmd *cobra.Command, args []string) {
	router := httprouter.New()
	serverHandler := &server.Handler{}
	serverHandler.Start(c, router)

	if ok, _ := cmd.Flags().GetBool("dangerous-auto-logon"); ok {
		logrus.Warnln("Do not use flag --dangerous-auto-logon in production.")
		err := c.Persist()
		pkg.Must(err, "Could not write configuration file: %s", err)
	}

	http.Handle("/", router)

	var srv = http.Server{
		Addr: c.GetAddress(),
		TLSConfig: &tls.Config{
			Certificates: []tls.Certificate{
				getOrCreateTLSCertificate(cmd),
			},
		},
	}

	var err error
	logrus.Infof("Starting server on %s", c.GetAddress())
	if ok, _ := cmd.Flags().GetBool("force-dangerous-http"); ok {
		logrus.Warnln("HTTPS disabled. Never do this in production.")
		err = srv.ListenAndServe()
	} else {
		err = srv.ListenAndServeTLS("", "")
	}
	pkg.Must(err, "Could not start server: %s %s.", err)
}
Ejemplo 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
}
Ejemplo n.º 3
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 {}
}
Ejemplo n.º 4
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()
}
Ejemplo n.º 5
0
/*
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)
	}

}
Ejemplo n.º 6
0
Archivo: server.go Proyecto: jf/gwp
func main() {
	server := http.Server{
		Addr:    "127.0.0.1:8080",
		Handler: nil,
	}
	server.ListenAndServeTLS("cert.pem", "key.pem")
}
Ejemplo n.º 7
0
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
	cacheFile := "letsencrypt.cache"
	if !inProd {
		if *tlsCertFile != "" && *tlsKeyFile != "" {
			return httpsServer.ListenAndServeTLS(*tlsCertFile, *tlsKeyFile)
		}
		// Otherwise use Let's Encrypt, i.e. same use case as in prod
	} else {
		cacheFile = prodLECache
		if err := os.MkdirAll(filepath.Dir(cacheFile), 0755); err != nil {
			return err
		}
	}
	var m letsencrypt.Manager
	if err := m.CacheFile(cacheFile); err != nil {
		return err
	}
	httpsServer.TLSConfig = &tls.Config{
		GetCertificate: m.GetCertificate,
	}
	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))
}
Ejemplo n.º 8
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 {}
}
Ejemplo n.º 9
0
func main() {
	if _, err := fs.Mount(); err != nil {
		log.Printf("fs-mounting %v\n", err)
		os.Exit(-1)
	}

	var server http.Server
	server.Addr = envGetOrAlternatives(EnvCachyServerAddress, ":8080")

	log.Printf("cachy server running on %q\n", server.Addr)

	http.HandleFunc("/", Cache)
	http.HandleFunc("/cache", Cache)

	certFilepath := envGetOrAlternatives(EnvCachyCertFile, "cachy.cert")
	keyFilepath := envGetOrAlternatives(EnvCachyKeyFile, "cachy.key")

	if envGetOrAlternatives("http1") != "" {
		if err := server.ListenAndServe(); err != nil {
			log.Printf("serving http: %v\n", err)
		}
	} else {
		if err := server.ListenAndServeTLS(certFilepath, keyFilepath); err != nil {
			log.Printf("servingTLS: %v\n", err)
		}
	}
}
Ejemplo n.º 10
0
func runServer(mux *http.ServeMux, c *serverConfig) {
	h := httpxtra.Handler{
		Handler:  mux,
		XHeaders: c.XHeaders,
	}
	if c.Log {
		h.Logger = httpLogger
	}
	s := http.Server{
		Addr:         c.Addr,
		Handler:      h,
		ReadTimeout:  15 * time.Second,
		WriteTimeout: 15 * time.Second,
	}
	if len(c.KeyFile) > 0 && len(c.CertFile) > 0 {
		log.Printf("Starting HTTPS server on tcp/%s "+
			"log=%t xheaders=%t cert=%s key=%s",
			c.Addr,
			c.Log,
			c.XHeaders,
			c.CertFile,
			c.KeyFile,
		)
		log.Fatal(s.ListenAndServeTLS(c.CertFile, c.KeyFile))
	} else {
		log.Printf("Starting HTTP server on tcp/%s "+
			"log=%t xheaders=%t",
			c.Addr,
			c.Log,
			c.XHeaders,
		)
		log.Fatal(httpxtra.ListenAndServe(s))
	}
}
Ejemplo n.º 11
0
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))
}
Ejemplo n.º 12
0
func main() {
	port := 8080

	var srv http.Server

	router := mux.NewRouter()

	router.HandleFunc("/hello", hello)
	router.HandleFunc("/welcome", welcome)
	router.PathPrefix("/").Handler(http.FileServer(http.Dir(".")))

	srv.Addr = Sprintf(":%d", port)

	/* set the http handler */
	srv.Handler = &gpp.Handler{EnableProxy: true, Handler: router}

	/* initial http2 support */
	http2.ConfigureServer(&srv, nil)

	log.Print("Listen on: ", Sprintf("https://0.0.0.0:%d", port))
	srv.ListenAndServeTLS("server.crt", "server.key")
	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 13
0
Archivo: main.go Proyecto: nyarla/sslr
func main() {
	destURL, err := url.Parse(destURL)
	if err != nil {
		log.Fatalf("failed to parse destination URL: %v", err)
	}

	certPool := x509.NewCertPool()
	{
		fh, err2 := os.Open(clientFile)
		if err2 != nil {
			log.Fatalf("failed to parse root certificate file: %v", err2)
		}
		defer fh.Close()

		buf := new(bytes.Buffer)
		rh := bufio.NewReader(fh)
		io.Copy(buf, rh)
		ok := certPool.AppendCertsFromPEM(buf.Bytes())
		if !ok {
			log.Fatalf("failed to append PEM file.")
		}
	}

	proxyHandler := httputil.NewSingleHostReverseProxy(destURL)
	proxyServer := http.Server{
		Addr:    listenAddr,
		Handler: proxyHandler,
		TLSConfig: &tls.Config{
			ClientAuth: tls.RequireAndVerifyClientCert,
			ClientCAs:  certPool,
		},
	}

	log.Fatal(proxyServer.ListenAndServeTLS(certFile, keyFile))
}
Ejemplo n.º 14
0
// BackgroundRunHttps runs an https server in a goroutine.
// Returns a send-only channel to watch for errors.
func BackgroundRunHttps(server *http.Server, conf *BaseConfiguration) chan error {
	https := make(chan error)
	go func() {
		server.Addr = fmt.Sprintf("%s:%d", conf.BindAddress, int(conf.BindHttpsPort))
		https <- server.ListenAndServeTLS(conf.CertFile, conf.KeyFile)
	}()
	return https
}
Ejemplo n.º 15
0
func ListenHTTPS() {
	s := http.Server{
		Addr:    cfg.HTTPS.Addr,
		Handler: httpxtra.Handler{Logger: _logger},
	}
	log.Println("Starting HTTPS server on", cfg.HTTPS.Addr)
	log.Fatal(s.ListenAndServeTLS(cfg.HTTPS.CertFile, cfg.HTTPS.KeyFile))
}
Ejemplo n.º 16
0
func (e *Echo) run(s *http.Server, files ...string) {
	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")
	}
}
Ejemplo n.º 17
0
func main() {
	cf := flag.String("config", "freegeoip.conf", "set config file")
	flag.Parse()
	if buf, err := ioutil.ReadFile(*cf); err != nil {
		log.Fatal(err)
	} else {
		conf = &Settings{}
		if err := xml.Unmarshal(buf, conf); err != nil {
			log.Fatal(err)
		}
	}
	runtime.GOMAXPROCS(runtime.NumCPU())
	log.Printf("FreeGeoIP server starting. debug=%t", conf.Debug)
	http.Handle("/", http.FileServer(http.Dir(conf.DocumentRoot)))
	h := GeoipHandler()
	http.HandleFunc("/csv/", h)
	http.HandleFunc("/xml/", h)
	http.HandleFunc("/json/", h)
	wg := new(sync.WaitGroup)
	for _, l := range conf.Listen {
		if l.Addr == "" {
			continue
		}
		wg.Add(1)
		h := httpxtra.Handler{XHeaders: l.XHeaders}
		if l.Log {
			h.Logger = logger
		}
		s := http.Server{
			Addr:         l.Addr,
			Handler:      h,
			ReadTimeout:  15 * time.Second,
			WriteTimeout: 15 * time.Second,
		}
		if l.KeyFile == "" {
			log.Printf("Listening HTTP on %s "+
				"log=%t xheaders=%t",
				l.Addr, l.Log, l.XHeaders)
			go func() {
				log.Fatal(httpxtra.ListenAndServe(s))
			}()
		} else {
			log.Printf("Listening HTTPS on %s "+
				"log=%t xheaders=%t cert=%s key=%s",
				l.Addr, l.Log, l.XHeaders,
				l.CertFile, l.KeyFile)
			go func() {
				log.Fatal(s.ListenAndServeTLS(
					l.CertFile,
					l.KeyFile,
				))
			}()
		}
	}
	wg.Wait()
}
Ejemplo n.º 18
0
func (e *Echo) run(s *http.Server, files ...string) {
	s.Handler = e
	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")
	}
}
Ejemplo n.º 19
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")
}
Ejemplo n.º 20
0
func startServer(port int, path string, cert string, key string) error {
	mux := http.NewServeMux()
	mux.HandleFunc(path, handler)
	srv := http.Server{
		Handler: mux,
		Addr:    fmt.Sprintf(":%d", port),
	}

	return srv.ListenAndServeTLS(cert, key)
}
Ejemplo n.º 21
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"))
}
Ejemplo n.º 22
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"))
}
Ejemplo n.º 23
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)
	}
}
Ejemplo n.º 24
0
func (context *Context) ListenAndServeTLS(port string, certFile string, keyFile string) {
	var httpServer http.Server
	httpServer.Addr = ":" + port
	httpServer.Handler = http.HandlerFunc(serverHandler)

	go func() {
		err := httpServer.ListenAndServeTLS(certFile, keyFile)
		if err != nil {
			log.Printf("Listen error: %s", err)
		}
	}()
}
Ejemplo n.º 25
0
func Go(listenAddr string, cpu game.Player, cert, key string) {
	mux := gohttp.NewServeMux()

	cpuPlayer = cpu

	mux.HandleFunc("/", func(w gohttp.ResponseWriter, r *gohttp.Request) {
		w.Header().Set("Content-Type", "text/html")
		w.WriteHeader(gohttp.StatusOK)
		w.Write(MustAsset("combo.html"))
	})

	for _, js := range []string{"combo.js", "jquery.min.js", "jquery-ui.min.js"} {
		js := js
		mux.HandleFunc("/"+js, func(w gohttp.ResponseWriter, r *gohttp.Request) {
			w.Header().Set("Content-Type", "application/javascript")
			w.WriteHeader(gohttp.StatusOK)
			w.Write(MustAsset(js))
		})
	}

	mux.HandleFunc("/combo.css", func(w gohttp.ResponseWriter, r *gohttp.Request) {
		w.Header().Set("Content-Type", "text/css")
		w.WriteHeader(gohttp.StatusOK)
		w.Write(MustAsset("combo.css"))
	})

	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	mux.HandleFunc("/connect", func(w gohttp.ResponseWriter, r *gohttp.Request) {
		conn, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Printf("error making websocket: %s", err)
			return
		}
		handleConnect(conn)
	})

	fmt.Fprintf(os.Stdout, "Listening on %s...\n", listenAddr)

	server := gohttp.Server{
		Addr:    listenAddr,
		Handler: mux,
	}

	if cert != "" && key != "" {
		panic(server.ListenAndServeTLS(cert, key))
	} else {
		panic(server.ListenAndServe())
	}
}
Ejemplo n.º 26
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("", "")
}
Ejemplo n.º 27
0
func New() {

	flag.Parse()
	LoadConfig(*configPath)

	server := &Server{
		Docs:        make(map[string]*Doc, 0),
		sortedDocs:  make([]*Doc, 0),
		DocLock:     &sync.RWMutex{},
		Tags:        make(map[string][]*Doc, 0),
		TagLock:     &sync.RWMutex{},
		StaticFiles: make([]string, 0),
		Version:     Version,
		StopWatch:   make(chan bool)}

	server.Reset()
	if err := server.LoadTempalte(); err != nil {
		log.Fatal(err)
	}
	server.LoadStaticFiles()
	server.LoadAllDocs()
	if err := server.SaveAllDocs(); err != nil {
		log.Fatal(err)
	}
	server.MakeHome()
	log.Print(server.MakeSitemap())
	log.Print(Cfg)
	server.Watch()
	server.ConfigWatch()

	admin := map[string]http.HandlerFunc{
		".add":    server.Add,
		".edit":   server.Edit,
		".quit":   server.Quit,
		".upload": server.UploadMedia,
	}

	for k, v := range admin {
		http.HandleFunc(path.Join(Cfg.BasePath, k), server.auth(v))
	}

	http.Handle("/", http.FileServer(http.Dir(Cfg.PublicPath)))

	if Cfg.TLSKeyFile != "" && Cfg.TLSCertFile != "" {

		tls_server := http.Server{Addr: Cfg.Addr, Handler: nil,
			TLSConfig: &tls.Config{ClientSessionCache: tls.NewLRUClientSessionCache(100)}}
		log.Fatal(tls_server.ListenAndServeTLS(Cfg.TLSCertFile, Cfg.TLSKeyFile))
	} else {
		log.Fatal(http.ListenAndServe(Cfg.Addr, nil))
	}
}
Ejemplo n.º 28
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"))
}
Ejemplo n.º 29
0
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")
	}
}
Ejemplo n.º 30
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"))
}