本文整理汇总了Golang中net/http.ListenAndServeTLS函数的典型用法代码示例。如果您正苦于以下问题:Golang ListenAndServeTLS函数的具体用法?Golang ListenAndServeTLS怎么用?Golang ListenAndServeTLS使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ListenAndServeTLS函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ListenAndServeTLS
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: main
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: runServer
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: Run
// 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: main
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: main
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: runHTTPListeners
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: Run
// 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: main
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
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: main
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
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
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: Startup
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: serveTLS
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
}
}