Golang ListenAndServeTLS示例

说明

golang listenandservetls示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: net/http

示例#1
文件: webrouter.go 项目: golangers/webrouter

func ListenAndServeTLS(addr, certFile, keyFile string, handler http.Handler) error {
	if handler == nil {
		return http.ListenAndServeTLS(addr, certFile, keyFile, DefauleRouter)
	}

	return http.ListenAndServeTLS(addr, certFile, keyFile, handler)
}

示例#2
文件: gophish.go 项目: StrangeUSB/gophish

func main() {
	// Setup the global variables and settings
	err := models.Setup()
	if err != nil {
		fmt.Println(err)
	}
	wg := &sync.WaitGroup{}
	wg.Add(1)
	// Start the web servers
	go func() {
		defer wg.Done()
		if config.Conf.AdminConf.UseTLS { // use TLS for Admin web server if available
			Logger.Printf("Starting admin server at https://%s\n", config.Conf.AdminConf.ListenURL)
			Logger.Fatal(http.ListenAndServeTLS(config.Conf.AdminConf.ListenURL, config.Conf.AdminConf.CertPath, config.Conf.AdminConf.KeyPath,
				handlers.CombinedLoggingHandler(os.Stdout, controllers.CreateAdminRouter())))
		} else {
			Logger.Printf("Starting admin server at http://%s\n", config.Conf.AdminConf.ListenURL)
			Logger.Fatal(http.ListenAndServe(config.Conf.AdminConf.ListenURL, handlers.CombinedLoggingHandler(os.Stdout, controllers.CreateAdminRouter())))
		}
	}()
	wg.Add(1)
	go func() {
		defer wg.Done()
		if config.Conf.PhishConf.UseTLS { // use TLS for Phish web server if available
			Logger.Printf("Starting phishing server at https://%s\n", config.Conf.PhishConf.ListenURL)
			Logger.Fatal(http.ListenAndServeTLS(config.Conf.PhishConf.ListenURL, config.Conf.PhishConf.CertPath, config.Conf.PhishConf.KeyPath,
				handlers.CombinedLoggingHandler(os.Stdout, controllers.CreatePhishingRouter())))
		} else {
			Logger.Printf("Starting phishing server at http://%s\n", config.Conf.PhishConf.ListenURL)
			Logger.Fatal(http.ListenAndServe(config.Conf.PhishConf.ListenURL, handlers.CombinedLoggingHandler(os.Stdout, controllers.CreatePhishingRouter())))
		}
	}()
	wg.Wait()
}

示例#3
文件: server.go 项目: shmifaats/gotosleep

func runServer(handler http.Handler) {
	// SETUP LOGGING

	// SETUP ADMIN HANDLER
	adminRouter := mux.NewRouter()
	adminRouter.HandleFunc("/ping", adminPingHandler)
	adminRouter.HandleFunc("/healthcheck", adminHealthCheck)

	// Setup HTTP endpoints
	appPort := serviceConfig.ApplicaitonConnector.Port
	adminPort := serviceConfig.AdminConnector.Port
	fmt.Println(appPort, adminPort)

	wg := &sync.WaitGroup{}

	wg.Add(1)
	go func() {
		http.ListenAndServe(fmt.Sprintf(":%d", appPort), handler)
		wg.Done()
	}()

	wg.Add(1)
	go func() {
		http.ListenAndServe(fmt.Sprintf(":%d", adminPort), adminRouter)
		wg.Done()
	}()

	// SETUP HTTPS ENDPOINTS - Default is none
	if serviceConfig.SecureAdminConnector != nil {
		wg.Add(1)
		go func() {
			certFile := serviceConfig.SecureApplicationConnector.CertFile
			keyFile := serviceConfig.SecureApplicationConnector.KeyFile
			port := serviceConfig.SecureApplicationConnector.Port
			http.ListenAndServeTLS(fmt.Sprintf(":%d", port), certFile, keyFile, handler)
			wg.Done()
		}()
	}

	if serviceConfig.SecureAdminConnector != nil {
		wg.Add(1)
		go func() {
			certFile := serviceConfig.SecureAdminConnector.CertFile
			keyFile := serviceConfig.SecureAdminConnector.KeyFile
			port := serviceConfig.SecureAdminConnector.Port
			http.ListenAndServeTLS(fmt.Sprintf(":%d", port), certFile, keyFile, adminRouter)
			wg.Done()
		}()
	}

	wg.Wait()

}

示例#4
文件: harness.go 项目: adarshaj/revel

// Run the harness, which listens for requests and proxies them to the app
// server, which it runs and rebuilds as necessary.
func (h *Harness) Run() {
	watcher = revel.NewWatcher()
	watcher.Listen(h, revel.CodePaths...)

	go func() {
		addr := fmt.Sprintf("%s:%d", revel.HttpAddr, revel.HttpPort)
		revel.INFO.Printf("Listening on %s", addr)

		var err error
		if revel.HttpSsl {
			err = http.ListenAndServeTLS(addr, revel.HttpSslCert,
				revel.HttpSslKey, h)
		} else {
			err = http.ListenAndServe(addr, h)
		}
		if err != nil {
			revel.ERROR.Fatalln("Failed to start reverse proxy:", err)
		}
	}()

	// Kill the app on signal.
	ch := make(chan os.Signal)
	signal.Notify(ch, os.Interrupt, os.Kill)
	<-ch
	if h.app != nil {
		h.app.Kill()
	}
	os.Exit(1)
}

示例#5
文件: gossip.go 项目: xuther/xuther

func main() {
	var port = flag.Int("port", 443, "The port number you want the server running on. Default is 8080")
	var db = flag.String("db", "gossip", "The Mongo Database name to use.")

	flag.Parse()

	dbName = *db
	sourceAddress = sourceAddress + ":" + strconv.Itoa(*port)

	fmt.Println("Database: ", dbName)
	fmt.Println("Port: ", sourceAddress)

	//We probably want to set the log path here.

	//load the configuration file with the known peers.

	http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("Static/"))))
	http.HandleFunc("/api/login", login)
	http.HandleFunc("/api/sendMessage", sendMessageHandle)
	http.HandleFunc("/api/getMessages", getMessagesHandle)
	http.HandleFunc("/api/register", registerHandle)
	http.HandleFunc("/api/addPeer", addPeerHandle)
	http.HandleFunc("/api/checkLogin", checkLogin)
	http.HandleFunc("/api/gossip", gossipHandle)

	//start our propagation thread.
	go PropagateRumors(PropagateRumorsChannel)
	//start our thread that will send out the "want" messages.
	go requestMessages()

	err := http.ListenAndServeTLS(":"+strconv.Itoa(*port), "server.pem", "server.key", nil)

	check(err)
}

示例#6
文件: example.go 项目: alytvynov/goa

func main() {
	if err := goa.Init(goa.Config{
		LoginPage:     "/login.html",
		HashKey:       []byte(hashKey),
		EncryptionKey: []byte(cryptoKey),
		CookieName:    "session",
		PQConfig:      "user=test_user password=test_pass dbname=goa",
	}); err != nil {
		log.Println(err)
		return
	}

	// public (no-auth-required) files
	http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
	// protected files, only for logged-in users
	http.Handle("/protected/", goa.NewHandler(http.StripPrefix("/protected/", http.FileServer(http.Dir("protected")))))
	// home handler
	http.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
		http.ServeFile(rw, req, "index.html")
	})
	http.HandleFunc("/login.html", func(rw http.ResponseWriter, req *http.Request) {
		http.ServeFile(rw, req, "login.html")
	})
	http.HandleFunc("/register.html", func(rw http.ResponseWriter, req *http.Request) {
		http.ServeFile(rw, req, "register.html")
	})

	if err := http.ListenAndServeTLS(":8080", "keys/cert.pem", "keys/key.pem", nil); err != nil {
		log.Println(err)
	}
}

示例#7
文件: route.go 项目: patosullivan/mf-proto

func runHTTPListeners(d db.DB) {
	httpMux, err := api.Routes(source)
	if err != nil {
		log.Fatalf("router setup failed: %s\n", err.Error())
	}

	httpsMux, err := api.Routes(
		api.Admin(d),
		api.User(d),
		api.Task(d),
	)
	if err != nil {
		log.Fatalf("router setup failed: %s\n", err.Error())
	}

	var (
		httpErr  = make(chan error)
		httpsErr = make(chan error)
	)

	log.Printf("mf-proto hosting source on HTTP 25000")
	log.Printf("mf-proto listening on HTTPS 25001")

	go func() { httpsErr <- http.ListenAndServeTLS(":25001", "cert.pem", "key.key", httpsMux) }()
	go func() { httpErr <- http.ListenAndServe(":25000", httpMux) }()

	go func() {
		var e error
		select {
		case e = <-httpErr:
		case e = <-httpsErr:
		}
		log.Fatalf("error serving http(s): %s", e.Error())
	}()
}

示例#8
文件: harness.go 项目: runner-mei/revel_cmd

// Run the harness, which listens for requests and proxies them to the app
// server, which it runs and rebuilds as necessary.
func (h *Harness) Run() {
	var paths []string
	if revel.Config.BoolDefault("watch.gopath", false) {
		gopaths := filepath.SplitList(build.Default.GOPATH)
		paths = append(paths, gopaths...)
	}
	paths = append(paths, revel.CodePaths...)
	watcher = revel.NewWatcher()
	watcher.Listen(h, paths...)

	go func() {
		addr := fmt.Sprintf("%s:%d", revel.HttpAddr, revel.HttpPort)
		revel.INFO.Printf("Listening on %s", addr)

		var err error
		if revel.HttpSsl {
			err = http.ListenAndServeTLS(addr, revel.HttpSslCert,
				revel.HttpSslKey, h)
		} else {
			err = http.ListenAndServe(addr, h)
		}
		if err != nil {
			revel.ERROR.Fatalln("Failed to start reverse proxy:", err)
		}
	}()

	// Kill the app on signal.
	ch := make(chan os.Signal)
	signal.Notify(ch, os.Interrupt, os.Kill)
	<-ch
	if h.app != nil {
		h.app.Kill()
	}
	os.Exit(1)
}

示例#9
文件: drone.go 项目: rpeterson/drone

func main() {
	// parse command line flags
	flag.StringVar(&port, "port", ":8080", "")
	flag.StringVar(&driver, "driver", "sqlite3", "")
	flag.StringVar(&datasource, "datasource", "drone.sqlite", "")
	flag.StringVar(&sslcert, "sslcert", "", "")
	flag.StringVar(&sslkey, "sslkey", "", "")
	flag.DurationVar(&timeout, "timeout", 300*time.Minute, "")
	flag.IntVar(&workers, "workers", runtime.NumCPU(), "")
	flag.Parse()

	// validate the TLS arguments
	checkTLSFlags()

	// setup database and handlers
	if err := database.Init(driver, datasource); err != nil {
		log.Fatal("Can't initialize database: ", err)
	}
	discardOldBuilds()
	setupStatic()
	setupHandlers()

	// debug
	log.Printf("starting drone version %s on port %s\n", version, port)

	// start webserver using HTTPS or HTTP
	if sslcert != "" && sslkey != "" {
		panic(http.ListenAndServeTLS(port, sslcert, sslkey, nil))
	} else {
		panic(http.ListenAndServe(port, nil))
	}
}

示例#10
文件: main.go 项目: ProZachJ/appsensor-reverse-proxy

func main() {

	enableTls, port, certFile, keyFile, chainHandler := parseFlags()

	if connections.RedisPool != nil {
		defer connections.RedisPool.Close()
	}

	if *enableTls {

		// serve over https
		// if you want to test this locally, generate a cert and key file using
		// go by running a command similar to :
		// "go run /usr/local/go/src/crypto/tls/generate_cert.go --host localhost"
		// and change the location to wherever go is installed on your system
		err := http.ListenAndServeTLS(*port, *certFile, *keyFile, chainHandler)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		// serve over http (non-secure)
		glog.Infof("WARNING: Running over plaintext http (insecure). " +
			"To enable https, use '-enable-tls'")
		http.ListenAndServe(*port, chainHandler)
	}

}

示例#11
文件: server.go 项目: ggrajek/pynn

func main() {

	workingDirectory, err := os.Getwd()

	if err != nil {
		fmt.Println("working directory error")
		return
	}

	gothic.GetProviderName = func(req *http.Request) (string, error) {
		return "amazon", nil
	}

	goth.UseProviders(
		amazon.New(os.Getenv("AMAZON_KEY"), os.Getenv("AMAZON_SECRET"), "https://ecloud.nimbostrati.com:9898/auth/amazon/callback", "profile"),
	)

	router.HandleFunc("/", makeIndexPageHandler(workingDirectory+"/app/splash.html"))
	router.HandleFunc("/auth/amazon/callback", callbackPageHandler)
	router.HandleFunc("/auth/amazon", startAuthHandler)

	ServeStatic(router, workingDirectory)

	http.Handle("/", router)

	fmt.Println("About to listen and serve from(", workingDirectory, ").")
	http.ListenAndServeTLS(":9898", os.Getenv("GOTH_SSL_CERT"), os.Getenv("GOTH_SSL_KEY"), nil)
}

示例#12
文件: main.go 项目: yannk/simplehttpsproxy

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "simplehttpsproxy [flags]\n")
		fmt.Fprintf(os.Stderr, "Flags:\n")
		flag.PrintDefaults()
	}
	flag.Parse()

	proxy := &httputil.ReverseProxy{
		Director: func(req *http.Request) {
			req.URL.Host = *flagBackend
			req.URL.Scheme = "http"
			req.Header.Set("X-Forwarded-Proto", "https")
		},
	}

	var cert *tls.Certificate
	var err error
	if *flagSSLCertPath == "" || *flagSSLKeyPath == "" {
		if *flagSSLCertPath != "" || *flagSSLKeyPath != "" {
			log.Fatalf("cannot specify -cert without -key")
		}
		if cert, err = genSelfSignedCert(*flagHost); err != nil {
			log.Fatalf("cannot generate cert: %s", err)
		}
		log.Printf("starting proxying %s on %s with generated cert", *flagBackend, *flagListen)
		panic(listenAndServeTLS(*flagListen, cert, proxy))
	}

	log.Printf("starting proxying %s on %s with given cert", *flagBackend, *flagListen)
	panic(http.ListenAndServeTLS(*flagListen, *flagSSLCertPath, *flagSSLKeyPath, proxy))
}

示例#13
文件: main.go 项目: TupambaeNet/electrum-sync-server

func main() {
	flag.Parse()

	sm := newSyncMaster(*dbDir)
	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)

	router, err := rest.MakeRouter(
		&rest.Route{"GET", "/labels/since/:nonce/for/:mpk", sm.GetLabels},
		&rest.Route{"POST", "/label", sm.CreateLabel},
		&rest.Route{"POST", "/labels", sm.CreateLabels},
	)

	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)
	sm.logger.Info("Server started and listening on %s", *listenPort)
	if *useTLS {
		sm.logger.Info("Using SSL with certificate '%s' and keyfile '%s'", *certPath, *keyPath)
		log.Fatal(http.ListenAndServeTLS(*listenPort, *certPath, *keyPath, api.MakeHandler()))
	} else {
		log.Fatal(http.ListenAndServe(*listenPort, api.MakeHandler()))
	}
}

示例#14
文件: o3erp.go 项目: kevinhuo88888/o3erp

func Startup() {

	templating.Setup()

	mux := httprouter.New()

	for path := range PathMapForGet {
		mux.GET(path, PathMapForGet[path])
	}
	for path := range PathMapForPost {
		mux.POST(path, PathMapForPost[path])
	}

	// handle static files
	mux.ServeFiles("/assets/*filepath", http.Dir(config.PATH_BASE_GOLANG_ASSETS))

	var u *url.URL
	var err error
	u, err = url.Parse(config.BACK_END_URL)
	if err != nil {
		log.Fatal(err)
	}
	// handle reserve proxy
	proxy := handler(httputil.NewSingleHostReverseProxy(u))

	// set GET paths
	for _, path := range ProxyPathListForGet {
		mux.HandlerFunc("GET", path, proxy)
	}

	// set POST paths
	for _, path := range ProxyPathListForPost {
		mux.HandlerFunc("POST", path, proxy)
	}

	secureMiddleware := secure.New(secure.Options{
		SSLRedirect: true,
		SSLHost:     config.HOST,
	})
	app := authenticationHandler(secureMiddleware.Handler(mux))

	log.Println("Starting...")

	models.DbMap = initDbMap()
	defer models.DbMap.Close()
	err = models.DbMap.Ping()
	if err != nil {
		log.Fatal("ping:", err)
	}

	// HTTP
	go func() {
		log.Fatal(http.ListenAndServe(config.PORT_HTTP, mux))
	}()

	// HTTPS

	log.Fatal(http.ListenAndServeTLS(config.PORT_HTTPS, config.PATH_BASE_GOLANG_CERT+"/cert.pem", config.PATH_BASE_GOLANG_CERT+"/key.pem", app))

}

示例#15
文件: server.go 项目: Collinux/snap

func (s *Server) serveTLS(addrString string) {
	err := http.ListenAndServeTLS(addrString, s.tls.cert, s.tls.key, s.n)
	if err != nil {
		restLogger.Error(err)
		s.err <- err
	}
}

示例#16
文件: main.go 项目: intuxicated/gopkg

func run() error {
	flag.Parse()

	http.HandleFunc("/", handler)

	if *httpFlag == "" && *httpsFlag == "" {
		return fmt.Errorf("must provide -http and/or -https")
	}
	if (*httpsFlag != "" || *certFlag != "" || *keyFlag != "") && (*httpsFlag == "" || *certFlag == "" || *keyFlag == "") {
		return fmt.Errorf("-https -cert and -key must be used together")
	}

	ch := make(chan error, 2)

	if *httpFlag != "" {
		go func() {
			ch <- http.ListenAndServe(*httpFlag, nil)
		}()
	}
	if *httpsFlag != "" {
		go func() {
			ch <- http.ListenAndServeTLS(*httpsFlag, *certFlag, *keyFlag, nil)
		}()
	}
	return <-ch
}

示例#17
文件: dmcagent.go 项目: mikechack/wsrouter

func httpTlsListener(c chan bool) {
	log.Printf("About to listen on 443. Go to https://127.0.0.1:443/")
	err := http.ListenAndServeTLS(":443", "certs/server.pem", "certs/server.key", nil)
	if err != nil {
		log.Fatal(err)
	}
}

示例#18
文件: susi-webstack.go 项目: webvariants/susi-gowebstack

func main() {
	flag.Parse()
	s, err := susigo.NewSusi(*susiaddr, *cert, *key)
	if err != nil {
		log.Printf("Error while creating susi connection: %v", err)
		return
	}
	susi = s
	log.Println("successfully create susi connection")
	sessionTimeouts = make(map[string]time.Time)

	if *user == "" && *pass == "" {
		http.HandleFunc("/publish", publishHandler)
		http.HandleFunc("/upload", uploadHandler)
		http.Handle("/ws", websocket.Handler(websocketHandler))
		http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir(*assetDir))))
		http.HandleFunc("/", redirectToIndex)
	} else {
		http.HandleFunc("/publish", BasicAuth(publishHandler))
		http.HandleFunc("/upload", BasicAuth(uploadHandler))
		http.HandleFunc("/ws", BasicAuth(websocket.Handler(websocketHandler).ServeHTTP))
		http.HandleFunc("/assets/", BasicAuth(http.StripPrefix("/assets/", http.FileServer(http.Dir(*assetDir))).ServeHTTP))
		http.HandleFunc("/", BasicAuth(redirectToIndex))
	}

	log.Printf("starting http server on %v...", *webaddr)
	if *useHTTPS {
		log.Fatal(http.ListenAndServeTLS(*webaddr, *cert, *key, context.ClearHandler(http.DefaultServeMux)))
	} else {
		log.Fatal(http.ListenAndServe(*webaddr, context.ClearHandler(http.DefaultServeMux)))
	}
}

示例#19
文件: main.go 项目: bpadilla11/IntroWebDevS15

func main() {
	http.HandleFunc("/", thisLittleWebpage) // set the path URL

	fmt.Println("server is now running...")                                               // display when server is running
	go http.ListenAndServe(":8080", http.RedirectHandler("https://localhost:2525/", 301)) // redirect from HTTP to HTTPS
	http.ListenAndServeTLS(":2525", "cert/cert.pem", "cert/key.pem", nil)                 // server is now running on HTTPS and load certificates
}

示例#20
文件: eden.go 项目: bwinterton/eden

// RunTLS runs a TLS server listening on the given address with the given cert and key
func (r *Router) RunTLS(address string, cert string, key string) error {
	log.Printf("Starting TLS server on %s", address)
	if err := http.ListenAndServeTLS(address, cert, key, r); err != nil {
		return err
	}
	return nil
}

示例#21
文件: server.go 项目: Juerd/Up1

func main() {
	http.HandleFunc("/", index)
	http.HandleFunc("/up", upload)
	http.HandleFunc("/del", delfile)
	http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir("static"))))
	http.Handle("/i/", http.StripPrefix("/i", http.FileServer(http.Dir("i"))))

	config = readConfig()
	validateConfig(config)

	var wg sync.WaitGroup
	wg.Add(2)

	go func() {
		defer wg.Done()
		if config.Http.Enabled {
			log.Printf("Starting HTTP server on %s\n", config.Http.Listen)
			log.Println(http.ListenAndServe(config.Http.Listen, nil))
		}
	}()

	go func() {
		defer wg.Done()
		if config.Https.Enabled {
			log.Printf("Starting HTTPS server on %s\n", config.Https.Listen)
			log.Println(http.ListenAndServeTLS(config.Https.Listen, config.Https.Cert, config.Https.Key, nil))
		}
	}()

	wg.Wait()
}

示例#22
文件: main.go 项目: mscherer/deb-simple

func main() {
	flag.Parse()
	file, err := ioutil.ReadFile(*configFile)
	if err != nil {
		log.Fatal("unable to read config file, exiting...")
	}
	if err := json.Unmarshal(file, &parsedConfig); err != nil {
		log.Fatal("unable to marshal config file, exiting...")
	}

	if err := createDirs(parsedConfig); err != nil {
		log.Println(err)
		log.Fatalf("error creating directory structure, exiting")
	}

	http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir(parsedConfig.RootRepoPath))))
	http.Handle("/upload", uploadHandler(parsedConfig))
	http.Handle("/delete", deleteHandler(parsedConfig))

	if parsedConfig.EnableSSL {
		log.Println("running with SSL enabled")
		log.Fatal(http.ListenAndServeTLS(":"+parsedConfig.ListenPort, parsedConfig.SSLCert, parsedConfig.SSLKey, nil))
	} else {
		log.Println("running without SSL enabled")
		log.Fatal(http.ListenAndServe(":"+parsedConfig.ListenPort, nil))
	}
}

示例#23
文件: server.go 项目: huzorro/martini-api-example

func main() {
	go func() {
		// Listen on http: to raise an error and indicate that https: is required.
		//
		// This could also be achieved by passing the same `m` martini instance as
		// used by the https server, and by using a middleware that checks for https
		// and returns an error if it is not a secure connection. This would have the benefit
		// of handling only the defined routes. However, it is common practice to define
		// APIs on separate web servers from the web (html) pages, for maintenance and
		// scalability purposes, so it's not like it will block otherwise valid routes.
		//
		// It is also common practice to use a different subdomain so that cookies are
		// not transfered with every API request.
		// So with that in mind, it seems reasonable to refuse each and every request
		// on the non-https server, regardless of the route. This could of course be done
		// on a reverse-proxy in front of this web server.
		//
		if err := http.ListenAndServe(":8000", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			http.Error(w, "https scheme is required", http.StatusBadRequest)
		})); err != nil {
			log.Fatal(err)
		}
	}()

	// Listen on https: with the preconfigured martini instance. The certificate files
	// can be created using this command in this repository's root directory:
	//
	// go run /path/to/goroot/src/pkg/crypto/tls/generate_cert.go --host="localhost"
	//
	if err := http.ListenAndServeTLS(":8001", "cert.pem", "key.pem", m); err != nil {
		log.Fatal(err)
	}
}

示例#24
文件: web.go 项目: jefflaplante/traefik

func (provider *WebProvider) Provide(configurationChan chan<- *Configuration) {
	systemRouter := mux.NewRouter()
	systemRouter.Methods("GET").Path("/").Handler(http.HandlerFunc(GetHtmlConfigHandler))
	systemRouter.Methods("GET").Path("/health").Handler(http.HandlerFunc(GetHealthHandler))
	systemRouter.Methods("GET").Path("/api").Handler(http.HandlerFunc(GetConfigHandler))
	systemRouter.Methods("PUT").Path("/api").Handler(http.HandlerFunc(
		func(rw http.ResponseWriter, r *http.Request) {
			configuration := new(Configuration)
			b, _ := ioutil.ReadAll(r.Body)
			err := json.Unmarshal(b, configuration)
			if err == nil {
				configurationChan <- configuration
				GetConfigHandler(rw, r)
			} else {
				log.Error("Error parsing configuration %+v\n", err)
				http.Error(rw, fmt.Sprintf("%+v", err), http.StatusBadRequest)
			}
		}))
	systemRouter.Methods("GET").Path("/api/backends").Handler(http.HandlerFunc(GetBackendsHandler))
	systemRouter.Methods("GET").Path("/api/backends/{backend}").Handler(http.HandlerFunc(GetBackendHandler))
	systemRouter.Methods("GET").Path("/api/backends/{backend}/servers").Handler(http.HandlerFunc(GetServersHandler))
	systemRouter.Methods("GET").Path("/api/backends/{backend}/servers/{server}").Handler(http.HandlerFunc(GetServerHandler))
	systemRouter.Methods("GET").Path("/api/frontends").Handler(http.HandlerFunc(GetFrontendsHandler))
	systemRouter.Methods("GET").Path("/api/frontends/{frontend}").Handler(http.HandlerFunc(GetFrontendHandler))
	systemRouter.Methods("GET").PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"})))

	go func() {
		if len(provider.CertFile) > 0 && len(provider.KeyFile) > 0 {
			http.ListenAndServeTLS(provider.Address, provider.CertFile, provider.KeyFile, systemRouter)
		} else {
			http.ListenAndServe(provider.Address, systemRouter)
		}
	}()
}

示例#25
文件: main.go 项目: twanies/jinx-proxy

func main() {
	var (
		conf = flag.String("conf", "conf/jinx.conf", "config filename")
	)
	flag.Parse()

	cfg := proxy.LoadConfig(*conf)
	p := proxy.NewReverseProxy()

	for address, settings := range cfg.Servers {
		if isHTTPS(address) {
			cfg.TLS = true
		}
		if settings.Scheme == "" {
			settings.Scheme = "http"
		}
		target := &url.URL{
			Scheme: settings.Scheme,
			Host:   parseHost(settings.Proxy),
			Path:   settings.Path,
		}
		up := proxy.NewUpstream(parseHost(address), target)
		p.AddUpstream(up)
	}

	listen := defaultAddr
	if cfg.Listen > 0 {
		listen = fmt.Sprintf(":%d", cfg.Listen)
	}
	if cfg.TLS {
		log.Fatal(http.ListenAndServeTLS(listen, cfg.CertFile, cfg.KeyFile, p))
	}
	log.Fatal(http.ListenAndServe(listen, p))
}

示例#26
文件: btsyncinator.go 项目: snarlysodboxer/BTSyncInator

func main() {
	// Parse Command line flags
	flag.Parse()
	if *debug {
		log.Println("Debug mode enabled")
	}

	loadSettings()

	setupDaemonsFromConfig()

	var digestAuth auth.DigestAuth
	if settings.DigestPath != "" {
		digestAuth = loadDigestAuth("BTSyncInator")
	}

	// Respond to http resquests
	http.HandleFunc("/config", useDigestAuthOrNot(digestAuth, configViewHandler))
	http.HandleFunc("/config/delete", useDigestAuthOrNot(digestAuth, configDeleteHandler))
	http.HandleFunc("/config/create", useDigestAuthOrNot(digestAuth, configCreateHandler))
	http.HandleFunc("/folder/add/new", useDigestAuthOrNot(digestAuth, folderAddNewHandler))
	http.HandleFunc("/folder/add/existing", useDigestAuthOrNot(digestAuth, folderAddExistingHandler))
	http.HandleFunc("/folder/remove", useDigestAuthOrNot(digestAuth, folderRemoveHandler))
	http.HandleFunc("/", useDigestAuthOrNot(digestAuth, rootHandler))
	if settings.UseTLS {
		http.ListenAndServeTLS(settings.ServeAddress, settings.TLSCertPath, settings.TLSKeyPath, nil)
	} else {
		http.ListenAndServe(settings.ServeAddress, nil)
	}
}

示例#27
文件: drone.go 项目: happypancakerd/drone

func main() {
	// parse command line flags
	flag.StringVar(&path, "path", "", "")
	flag.StringVar(&port, "port", ":8080", "")
	flag.StringVar(&driver, "driver", "sqlite3", "")
	flag.StringVar(&datasource, "datasource", "drone.sqlite", "")
	flag.StringVar(&sslcert, "sslcert", "", "")
	flag.StringVar(&sslkey, "sslkey", "", "")
	flag.DurationVar(&timeout, "timeout", 300*time.Minute, "")
	flag.Parse()

	// validate the TLS arguments
	checkTLSFlags()

	// setup database and handlers
	setupDatabase()
	setupStatic()
	setupHandlers()

	// debug
	log.Printf("starting drone version %s on port %s\n", version, port)

	// start webserver using HTTPS or HTTP
	if sslcert != "" && sslkey != "" {
		panic(http.ListenAndServeTLS(port, sslcert, sslkey, nil))
	} else {
		panic(http.ListenAndServe(port, nil))
	}
}

示例#28
文件: gin.go 项目: ketan-ghumatkar/cowboy

// The router is attached to a http.Server and starts listening and serving HTTPS requests.
// It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router)
// Note: this method will block the calling goroutine undefinitelly unless an error happens.
func (engine *Engine) RunTLS(addr string, certFile string, keyFile string) (err error) {
	debugPrint("Listening and serving HTTPS on %s\n", addr)
	defer func() { debugPrintError(err) }()

	err = http.ListenAndServeTLS(addr, certFile, keyFile, engine)
	return
}

示例#29
文件: duoauth.go 项目: sajeetharan/v6engine

func runRestFul() {
	gorest.RegisterService(new(authlib.Auth))
	gorest.RegisterService(new(authlib.TenantSvc))
	gorest.RegisterService(new(pog.POGSvc))
	gorest.RegisterService(new(applib.AppSvc))
	gorest.RegisterService(new(config.ConfigSvc))
	gorest.RegisterService(new(statservice.StatSvc))
	gorest.RegisterService(new(apisvc.ApiSvc))

	c := authlib.GetConfig()
	email.EmailAddress = c.Smtpusername
	email.Password = c.Smtppassword
	email.SMTPServer = c.Smtpserver

	if c.Https_Enabled {
		err := http.ListenAndServeTLS(":3048", c.Cirtifcate, c.PrivateKey, gorest.Handle())
		if err != nil {
			term.Write(err.Error(), term.Error)
			return
		}
	} else {
		err := http.ListenAndServe(":3048", gorest.Handle())
		if err != nil {
			term.Write(err.Error(), term.Error)
			return
		}
	}

}

示例#30
文件: main.go 项目: cmars/shadowfax

func run() error {
	kingpin.Parse()

	db, err := newDB()
	if err != nil {
		return errgo.Mask(err)
	}
	keyPair, err := loadKeyPair()
	if err != nil {
		return errgo.Mask(err)
	}
	service := boltstorage.NewService(db)
	handler := sfhttp.NewHandler(keyPair, service)

	r := httprouter.New()
	handler.Register(r)

	var t tomb.Tomb
	if *httpFlag != "" {
		t.Go(func() error {
			return http.ListenAndServe(*httpFlag, r)
		})
	}
	if *httpsFlag != "" && *certFlag != "" && *keyFlag != "" {
		t.Go(func() error {
			return http.ListenAndServeTLS(*httpsFlag, *certFlag, *keyFlag, r)
		})
	}

	log.Printf("public key: %s", keyPair.PublicKey.Encode())
	return t.Wait()
}

展开阅读全文