• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang manners.NewWithServer函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/braintree/manners.NewWithServer函数的典型用法代码示例。如果您正苦于以下问题:Golang NewWithServer函数的具体用法?Golang NewWithServer怎么用?Golang NewWithServer使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewWithServer函数的18个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Initialize

func (rp *NativeReverseProxy) Initialize(rpConfig ReverseProxyConfig) (string, error) {
	var err error
	rp.ReverseProxyConfig = rpConfig
	rp.listener, err = net.Listen("tcp", rpConfig.Listen)
	if err != nil {
		return "", err
	}
	rp.server = manners.NewWithServer(&http.Server{Handler: rp})
	rp.dialer = &net.Dialer{
		Timeout:   rp.DialTimeout,
		KeepAlive: 30 * time.Second,
	}
	rp.Transport = http.Transport{
		Dial:                rp.dialer.Dial,
		TLSHandshakeTimeout: rp.DialTimeout,
		MaxIdleConnsPerHost: 100,
	}
	rp.rp = &httputil.ReverseProxy{
		Director:      noopDirector,
		Transport:     rp,
		FlushInterval: rp.FlushInterval,
		BufferPool:    &bufferPool{},
	}
	return rp.listener.Addr().String(), nil
}
开发者ID:txrxio,项目名称:planb,代码行数:25,代码来源:native.go


示例2: Run

// Run is called to start the web service.
func Run(host string, routes http.Handler, readTimeout, writeTimeout time.Duration) error {

	// Create a new server and set timeout values.
	server := manners.NewWithServer(&http.Server{
		Addr:           host,
		Handler:        routes,
		ReadTimeout:    readTimeout,
		WriteTimeout:   writeTimeout,
		MaxHeaderBytes: 1 << 20,
	})

	go func() {

		// Listen for an interrupt signal from the OS.
		osSignals := make(chan os.Signal)
		signal.Notify(osSignals, os.Interrupt)

		<-osSignals

		// Shut down the API server.
		server.Close()
	}()

	return server.ListenAndServe()
}
开发者ID:coralproject,项目名称:xenia,代码行数:26,代码来源:web.go


示例3: runServer

func runServer(c *cli.Context) {
	listener, err := net.Listen("tcp", c.String("listen"))
	if err != nil {
		log.Fatal(err)
	}
	router := Router{
		ReadRedisHost:  c.String("read-redis-host"),
		ReadRedisPort:  c.Int("read-redis-port"),
		WriteRedisHost: c.String("write-redis-host"),
		WriteRedisPort: c.Int("write-redis-port"),
		LogPath:        c.String("access-log"),
		RequestTimeout: time.Duration(c.Int("request-timeout")) * time.Second,
		DialTimeout:    time.Duration(c.Int("dial-timeout")) * time.Second,
		DeadBackendTTL: c.Int("dead-backend-time"),
		FlushInterval:  time.Duration(c.Int("flush-interval")) * time.Millisecond,
	}
	err = router.Init()
	if err != nil {
		log.Fatal(err)
	}
	s := manners.NewWithServer(&http.Server{Handler: &router})
	handleSignals(s)
	log.Printf("Listening on %v...\n", listener.Addr())
	err = s.Serve(listener)
	router.Stop()
	if err != nil {
		log.Fatal(err)
	}
}
开发者ID:gleicon,项目名称:planb,代码行数:29,代码来源:main.go


示例4: Run

// Runs HTTP server
func (wh *WorkerHttp) Run(wg *sync.WaitGroup, die chan bool) {
	defer wg.Done()

	server := manners.NewWithServer(&http.Server{
		Addr:    wh.addr,
		Handler: wh.getRouter(),
	})

	// Start goroutine which will gracefully close server
	go func(server *manners.GracefulServer) {
		for {
			select {
			case <-die:
				logger.Instance().
					Info("Stopping HTTP server")
				server.Close()
				return
			default:
			}

			time.Sleep(time.Second)
		}
	}(server)

	logger.Instance().
		WithField("addr", server.Addr).
		Info("HTTP server started")

	_ = server.ListenAndServe()
}
开发者ID:endeveit,项目名称:recause,代码行数:31,代码来源:http.go


示例5: startHttpServer

func (hd *HealthD) startHttpServer(hostPort string) {
	server := manners.NewWithServer(&http.Server{
		Addr:    hostPort,
		Handler: hd.apiRouter(),
	})
	hd.stopHTTP = server.Close
	server.ListenAndServe()
}
开发者ID:grepory,项目名称:awsthingy,代码行数:8,代码来源:api.go


示例6: Run

// Run starts the server
func (s *Server) Run(log *logrus.Entry) error {
	s.log = log.WithField("app", AppName)

	// Init the app
	s.InitStart(log)

	s.gracefulServer = manners.NewWithServer(s.httpServer(s.log))
	return s.gracefulServer.ListenAndServe()
}
开发者ID:odwrtw,项目名称:polochon,代码行数:10,代码来源:http.go


示例7: Start

// Start initializes and starts the web server
func Start() {

	srv = &Server{}
	srv.Router = mux.NewRouter()

	srv.Server = manners.NewWithServer(&http.Server{
		Addr:           ":8080",
		Handler:        srv.Router,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	})

	log.Printf("Starting Server v%s ...", meta.App.Version)
	api.InitAPI(srv.Router)
	startShutdownListener()
	srv.Server.ListenAndServe()
}
开发者ID:spohnan,项目名称:ws-test-01,代码行数:19,代码来源:server.go


示例8: main

func main() {

	shutdown := make(chan int)

	//create a notification channel to shutdown
	sigChan := make(chan os.Signal, 1)

	//start the main http server for serving traffic
	router := httprouter.New()
	router.GET("/", hello)
	server := manners.NewWithServer(&http.Server{Addr: ":80", Handler: router})
	go func() {
		server.ListenAndServe()
		shutdown <- 1
	}()

	//start the system server for health checks and shutdowns
	s := &status{
		ready: false,
	}

	hRouter := httprouter.New()
	hRouter.GET("/ready", makeReady(s))
	hRouter.GET("/prestop", makePrestop(s))
	go func() {
		http.ListenAndServe(":8080", hRouter)
	}()

	//register for interupt (Ctrl+C) and SIGTERM (docker)
	signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
	go func() {
		<-sigChan
		fmt.Println("Shutting down...")
		server.Close()
	}()

	//move server to ready state
	s.Lock()
	s.ready = true
	s.Unlock()

	<-shutdown
}
开发者ID:chriswhitcombe,项目名称:httpgraceful,代码行数:43,代码来源:main.go


示例9: main

func main() {
	// Initialize common startup setting
	common.Startup()

	// Load configs
	config := common.LoadGlobConfigs("config.*.yaml")
	// common.MergeConfigFromConsul(config)

	// Initialize store handler
	storeHandler, err := frontend.NewStoreHandler()
	if err != nil {
		log.Fatalf("Initialize store handler failed: %s", err)
	}

	apiMux := http.NewServeMux()
	apiMux.Handle("/store/", storeHandler)
	apiHandler := http.Handler(apiMux)

	rootMux := http.NewServeMux()
	rootMux.Handle("/_health", frontend.NewHealthCheckHandler())
	rootMux.Handle("/_version", frontend.NewVersionHandler())
	rootMux.Handle("/", apiHandler)

	log.Printf("Starting HTTP listener on %s...", config.GetString("http.endpoint"))
	httpServer := manners.NewWithServer(
		&http.Server{
			Addr:    config.GetString("http.endpoint"),
			Handler: rootMux,
		})

	// Listen for signals and do graceful shutdown
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		<-sigCh

		log.Printf("Shutting down...")

		// Stop catching signals, so that we can actually stop on second signal
		signal.Stop(sigCh)

		atomic.StoreInt32(&frontend.Shutdown, 1)

		// Slow down shutdown to get some extra time for graceful restart
		log.Printf("Sleeping...")
		time.Sleep(common.ParseDuration(config.GetString("shutdown.sleep")))
		log.Printf("Done sleeping!")

		// Shutdown HTTP
		httpServer.Close()
	}()

	var wg sync.WaitGroup

	wg.Add(1)
	go func() {
		defer wg.Done()
		err := httpServer.ListenAndServe()

		if err != nil {
			log.Fatalf("Listen error: %s", err)
		}
	}()

	wg.Wait()
}
开发者ID:caihua-yin,项目名称:hello-go,代码行数:67,代码来源:main.go


示例10: Run


//.........这里部分代码省略.........
		addr := l.Addr()
		endpoint = net.JoinHostPort(app.options.Address, strconv.Itoa(addr.(*net.TCPAddr).Port))
	} else {
		endpoint = net.JoinHostPort(app.options.Address, app.options.Port)
	}

	wsHandler := http.HandlerFunc(app.handleWS)
	customIndexHandler := http.HandlerFunc(app.handleCustomIndex)
	authTokenHandler := http.HandlerFunc(app.handleAuthToken)
	staticHandler := http.FileServer(
		&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"},
	)

	var siteMux = http.NewServeMux()

	if app.options.IndexFile != "" {
		log.Printf("Using index file at " + app.options.IndexFile)
		siteMux.Handle(path+"/", customIndexHandler)
	} else {
		siteMux.Handle(path+"/", http.StripPrefix(path+"/", staticHandler))
	}
	siteMux.Handle(path+"/auth_token.js", authTokenHandler)
	siteMux.Handle(path+"/js/", http.StripPrefix(path+"/", staticHandler))
	siteMux.Handle(path+"/favicon.png", http.StripPrefix(path+"/", staticHandler))

	siteHandler := http.Handler(siteMux)

	if app.options.EnableBasicAuth {
		log.Printf("Using Basic Authentication")
		siteHandler = wrapBasicAuth(siteHandler, app.options.Credential)
	}

	wsMux := http.NewServeMux()
	wsMux.Handle("/", siteHandler)
	wsMux.Handle(path+"/ws", wsHandler)
	siteHandler = (http.Handler(wsMux))

	siteHandler = wrapLogger(siteHandler)

	scheme := "http"
	if app.options.EnableTLS {
		scheme = "https"
	}
	log.Printf(
		"Server is starting with command: %s",
		strings.Join(app.command, " "),
	)
	if app.options.Address != "" {
		log.Printf(
			"URL: %s",
			(&url.URL{Scheme: scheme, Host: endpoint, Path: path + "/"}).String(),
		)
	} else {
		if app.options.EnalbeRandomPort {
			randomPort := strings.Split(endpoint, ":")[1]
			for _, address := range listAddresses() {
				log.Printf(
					"URL: %s",
					(&url.URL{
						Scheme: scheme,
						Host:   net.JoinHostPort(address, randomPort),
						Path:   path + "/",
					}).String(),
				)
			}
		} else {
			for _, address := range listAddresses() {
				log.Printf(
					"URL: %s",
					(&url.URL{
						Scheme: scheme,
						Host:   net.JoinHostPort(address, app.options.Port),
						Path:   path + "/",
					}).String(),
				)
			}
		}
	}

	var err error
	app.server = manners.NewWithServer(
		&http.Server{Addr: endpoint, Handler: siteHandler},
	)
	if app.options.EnableTLS {
		crtFile := ExpandHomeDir(app.options.TLSCrtFile)
		keyFile := ExpandHomeDir(app.options.TLSKeyFile)
		log.Printf("TLS crt file: " + crtFile)
		log.Printf("TLS key file: " + keyFile)
		err = app.server.ListenAndServeTLS(crtFile, keyFile)
	} else {
		err = app.server.ListenAndServe()
	}
	if err != nil {
		return err
	}

	log.Printf("Exiting...")

	return nil
}
开发者ID:wdxxs2z,项目名称:gotty,代码行数:101,代码来源:app.go


示例11: New

func New(svr *http.Server, sigs []os.Signal) *server {
	return &server{
		m:    manners.NewWithServer(svr),
		sigs: sigs,
	}
}
开发者ID:mix3,项目名称:ran,代码行数:6,代码来源:ran.go


示例12: Run


//.........这里部分代码省略.........
	siteMux.Handle(path+"/auth_token.js", authTokenHandler)
	siteMux.Handle(path+"/js/", http.StripPrefix(path+"/", staticHandler))
	siteMux.Handle(path+"/favicon.png", http.StripPrefix(path+"/", staticHandler))

	siteHandler := http.Handler(siteMux)

	if app.options.EnableBasicAuth {
		log.Printf("Using Basic Authentication")
		siteHandler = wrapBasicAuth(siteHandler, app.options.Credential)
	}

	wsMux := http.NewServeMux()
	wsMux.Handle("/", siteHandler)
	wsMux.Handle(path+"/ws", wsHandler)
	siteHandler = (http.Handler(wsMux))

	siteHandler = wrapLogger(siteHandler)

	scheme := "http"
	if app.options.EnableTLS {
		scheme = "https"
	}
	log.Printf(
		"Server is starting with command: %s",
		strings.Join(app.command, " "),
	)
	if app.options.Address != "" {
		log.Printf(
			"URL: %s",
			(&url.URL{Scheme: scheme, Host: endpoint, Path: path + "/"}).String(),
		)
	} else {
		for _, address := range listAddresses() {
			log.Printf(
				"URL: %s",
				(&url.URL{
					Scheme: scheme,
					Host:   net.JoinHostPort(address, app.options.Port),
					Path:   path + "/",
				}).String(),
			)
		}
	}

	serverMaker := func() *http.Server {
		return &http.Server{
			Addr:    endpoint,
			Handler: siteHandler}
	}
	if app.options.VerifyClientCert && app.options.EnableTLS {
		serverMaker = func() *http.Server {
			clientCaPool := x509.NewCertPool()
			for _, path := range app.options.ClientCAs {
				pem, err := ioutil.ReadFile(path)
				if err != nil {
					log.Printf("Could not read pem file at: " + path)
					return nil
				}
				if clientCaPool.AppendCertsFromPEM(pem) {
					log.Printf("Could not parse pem file at: " + path)
					return nil
				}
			}
			return &http.Server{
				Addr:    endpoint,
				Handler: siteHandler,
				TLSConfig: &tls.Config{
					ClientAuth:               tls.RequireAndVerifyClientCert,
					ClientCAs:                clientCaPool,
					PreferServerCipherSuites: true}}
		}
	}

	server := serverMaker()
	if server == nil {
		log.Printf("Failed to build server.")
		return errors.New("Failed to build server.")
	}

	var err error
	app.server = manners.NewWithServer(
		server,
	)
	if app.options.EnableTLS {
		crtFile := ExpandHomeDir(app.options.TLSCrtFile)
		keyFile := ExpandHomeDir(app.options.TLSKeyFile)
		log.Printf("TLS crt file: " + crtFile)
		log.Printf("TLS key file: " + keyFile)
		err = app.server.ListenAndServeTLS(crtFile, keyFile)
	} else {
		err = app.server.ListenAndServe()
	}
	if err != nil {
		return err
	}

	log.Printf("Exiting...")

	return nil
}
开发者ID:freakhill,项目名称:gotty,代码行数:101,代码来源:app.go


示例13: run

func run() error {
	var staticHandler http.Handler

	if GlobalOpt.Once {
		glog.V(3).Infof("Once option is provided, accepting only one client")
	}

	endpoint := net.JoinHostPort(GlobalOpt.Address, GlobalOpt.Port)

	staticHandler = http.FileServer(
		&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"})

	var siteMux = http.NewServeMux()
	siteMux.Handle("/", staticHandler)
	siteMux.Handle("/auth_token.js", http.HandlerFunc(daemon.handleAuthToken))
	if GlobalOpt.Debug {
		staticHandler = http.HandlerFunc(resourcesHandler)
	}
	siteMux.Handle("/js/", staticHandler)
	siteMux.Handle("/css/", staticHandler)
	siteMux.Handle("/font/", staticHandler)
	siteMux.Handle("/favicon.ico", staticHandler)

	//add demo handler
	if GlobalOpt.DemoEnable {
		siteMux.HandleFunc("/demo/", demoHandler)
		siteMux.HandleFunc("/cmd", demoCmdHandler)
	}

	siteHandler := http.Handler(siteMux)

	if GlobalOpt.EnableBasicAuth {
		glog.V(3).Infof("Using Basic Authentication")
		siteHandler = wrapBasicAuth(siteHandler, GlobalOpt.Credential)
	}

	wsMux := http.NewServeMux()
	wsMux.Handle("/", wrapHeaders(siteHandler))
	wsMux.Handle("/ws", http.HandlerFunc(wsHandler))
	siteHandler = wrapLogger(http.Handler(wsMux))

	scheme := "http"
	if GlobalOpt.EnableTLS {
		scheme = "https"
	}
	/*
		glog.Infof(
			"Server is starting with command: %s\n",
			strings.Join(session.command, " ")
		)
	*/
	if GlobalOpt.Address != "" {
		glog.V(0).Infof(
			"URL: %s",
			(&url.URL{Scheme: scheme, Host: endpoint, Path: "/"}).String(),
		)
	} else {
		for _, address := range listAddresses() {
			glog.V(0).Infof(
				"URL: %s",
				(&url.URL{
					Scheme: scheme,
					Host:   net.JoinHostPort(address, GlobalOpt.Port),
					Path:   "/",
				}).String(),
			)
		}
	}

	server, err := makeServer(daemon, endpoint, &siteHandler)
	if err != nil {
		return errors.New("Failed to build server: " + err.Error())
	}
	daemon.server = manners.NewWithServer(server)

	if GlobalOpt.EnableTLS {
		crtFile := expandHomeDir(GlobalOpt.TLSCrtFile)
		keyFile := expandHomeDir(GlobalOpt.TLSKeyFile)
		glog.V(0).Infof("TLS crt file: " + crtFile)
		glog.V(0).Infof("TLS key file: " + keyFile)

		err = daemon.server.ListenAndServeTLS(crtFile, keyFile)
	} else {
		err = daemon.server.ListenAndServe()
	}
	if err != nil {
		return err
	}

	glog.V(0).Infof("Exiting...")

	return nil
}
开发者ID:yubo,项目名称:gotty,代码行数:93,代码来源:tty.go


示例14: run

func run() error {

	if GlobalOpt.Once {
		glog.V(3).Infof("Once option is provided, accepting only one client")
	}

	path := ""
	if GlobalOpt.EnableRandomUrl {
		path += "/" + generateRandomString(GlobalOpt.RandomUrlLength)
	}

	endpoint := net.JoinHostPort(GlobalOpt.Address, GlobalOpt.Port)

	customIndexHandler := http.HandlerFunc(daemon.handleCustomIndex)
	authTokenHandler := http.HandlerFunc(daemon.handleAuthToken)
	staticHandler := http.FileServer(
		&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"},
	)

	var siteMux = http.NewServeMux()

	if GlobalOpt.IndexFile != "" {
		glog.V(3).Infof("Using index file at " + GlobalOpt.IndexFile)
		siteMux.Handle(path+"/", customIndexHandler)
	} else {
		siteMux.Handle(path+"/", http.StripPrefix(path+"/", staticHandler))
	}
	siteMux.Handle(path+"/auth_token.js", authTokenHandler)
	siteMux.Handle(path+"/js/", http.StripPrefix(path+"/", staticHandler))
	siteMux.Handle(path+"/favicon.png", http.StripPrefix(path+"/", staticHandler))

	siteHandler := http.Handler(siteMux)

	if GlobalOpt.EnableBasicAuth {
		glog.V(3).Infof("Using Basic Authentication")
		siteHandler = wrapBasicAuth(siteHandler, GlobalOpt.Credential)
	}

	siteHandler = wrapHeaders(siteHandler)

	wsMux := http.NewServeMux()
	wsMux.Handle("/", siteHandler)
	wsMux.Handle(path+"/ws", http.HandlerFunc(wsHandler))

	siteHandler = wrapLogger(http.Handler(wsMux))

	scheme := "http"
	if GlobalOpt.EnableTLS {
		scheme = "https"
	}
	/*
		glog.Infof(
			"Server is starting with command: %s\n",
			strings.Join(session.command, " ")
		)
	*/
	if GlobalOpt.Address != "" {
		glog.V(0).Infof(
			"URL: %s",
			(&url.URL{Scheme: scheme, Host: endpoint, Path: path + "/"}).String(),
		)
	} else {
		for _, address := range listAddresses() {
			glog.V(0).Infof(
				"URL: %s",
				(&url.URL{
					Scheme: scheme,
					Host:   net.JoinHostPort(address, GlobalOpt.Port),
					Path:   path + "/",
				}).String(),
			)
		}
	}

	server, err := makeServer(daemon, endpoint, &siteHandler)
	if err != nil {
		return errors.New("Failed to build server: " + err.Error())
	}
	daemon.server = manners.NewWithServer(server)

	if GlobalOpt.EnableTLS {
		crtFile := expandHomeDir(GlobalOpt.TLSCrtFile)
		keyFile := expandHomeDir(GlobalOpt.TLSKeyFile)
		glog.V(0).Infof("TLS crt file: " + crtFile)
		glog.V(0).Infof("TLS key file: " + keyFile)

		err = daemon.server.ListenAndServeTLS(crtFile, keyFile)
	} else {
		err = daemon.server.ListenAndServe()
	}
	if err != nil {
		return err
	}

	glog.V(0).Infof("Exiting...")

	return nil
}
开发者ID:DeanChina,项目名称:gotty,代码行数:98,代码来源:tty.go


示例15: Run

func (app *App) Run() error {
	if app.options.PermitWrite {
		log.Printf("Permitting clients to write input to the PTY.")
	}

	if app.options.Once {
		log.Printf("Once option is provided, accepting only one client")
	}

	path := ""
	if app.options.EnableRandomUrl {
		path += "/" + generateRandomString(app.options.RandomUrlLength)
	}

	endpoint := net.JoinHostPort(app.options.Address, app.options.Port)

	wsHandler := http.HandlerFunc(app.handleWS)
	customIndexHandler := http.HandlerFunc(app.handleCustomIndex)
	authTokenHandler := http.HandlerFunc(app.handleAuthToken)
	staticHandler := http.FileServer(
		&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"},
	)

	var siteMux = http.NewServeMux()

	if app.options.IndexFile != "" {
		log.Printf("Using index file at " + app.options.IndexFile)
		siteMux.Handle(path+"/", customIndexHandler)
	} else {
		siteMux.Handle(path+"/", http.StripPrefix(path+"/", staticHandler))
	}
	siteMux.Handle(path+"/auth_token.js", authTokenHandler)
	siteMux.Handle(path+"/js/", http.StripPrefix(path+"/", staticHandler))
	siteMux.Handle(path+"/favicon.png", http.StripPrefix(path+"/", staticHandler))

	siteHandler := http.Handler(siteMux)

	if app.options.EnableBasicAuth {
		log.Printf("Using Basic Authentication")
		siteHandler = wrapBasicAuth(siteHandler, app.options.Credential)
	}

	siteHandler = wrapHeaders(siteHandler)

	wsMux := http.NewServeMux()
	wsMux.Handle("/", siteHandler)
	wsMux.Handle(path+"/ws", wsHandler)
	siteHandler = (http.Handler(wsMux))

	siteHandler = wrapLogger(siteHandler)

	scheme := "http"
	if app.options.EnableTLS {
		scheme = "https"
	}
	log.Printf(
		"Server is starting with command: %s",
		strings.Join(app.command, " "),
	)
	if app.options.Address != "" {
		log.Printf(
			"URL: %s",
			(&url.URL{Scheme: scheme, Host: endpoint, Path: path + "/"}).String(),
		)
	} else {
		for _, address := range listAddresses() {
			log.Printf(
				"URL: %s",
				(&url.URL{
					Scheme: scheme,
					Host:   net.JoinHostPort(address, app.options.Port),
					Path:   path + "/",
				}).String(),
			)
		}
	}

	server, err := app.makeServer(endpoint, &siteHandler)
	if err != nil {
		return errors.New("Failed to build server: " + err.Error())
	}
	app.server = manners.NewWithServer(
		server,
	)

	if app.options.EnableTLS {
		crtFile := ExpandHomeDir(app.options.TLSCrtFile)
		keyFile := ExpandHomeDir(app.options.TLSKeyFile)
		log.Printf("TLS crt file: " + crtFile)
		log.Printf("TLS key file: " + keyFile)

		err = app.server.ListenAndServeTLS(crtFile, keyFile)
	} else {
		err = app.server.ListenAndServe()
	}
	if err != nil {
		return err
	}

	log.Printf("Exiting...")
//.........这里部分代码省略.........
开发者ID:yudai,项目名称:gotty,代码行数:101,代码来源:app.go


示例16: Run

func (app *App) Run() error {
	if app.options.PermitWrite {
		log.Printf("Permitting clients to write input to the PTY.")
	}

	path := ""
	if app.options.EnableRandomUrl {
		path += "/" + generateRandomString(app.options.RandomUrlLength)
	}

	endpoint := net.JoinHostPort(app.options.Address, app.options.Port)

	wsHandler := http.HandlerFunc(app.handleWS)
	staticHandler := http.FileServer(
		&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"},
	)

	if app.options.Once {
		log.Printf("Once option is provided, accepting only one client")
	}

	var siteMux = http.NewServeMux()

	if app.options.IndexFile != "" {
		log.Printf("Using index file at " + app.options.IndexFile)
		indexHandler := http.HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				http.ServeFile(w, r, ExpandHomeDir(app.options.IndexFile))
			},
		)
		siteMux.Handle(path+"/", indexHandler)
	} else {
		siteMux.Handle(path+"/", http.StripPrefix(path+"/", staticHandler))
	}

	siteMux.Handle(path+"/js/", http.StripPrefix(path+"/", staticHandler))
	siteMux.Handle(path+"/favicon.png", http.StripPrefix(path+"/", staticHandler))
	siteMux.Handle(path+"/ws", wsHandler)

	siteHandler := http.Handler(siteMux)

	if app.options.EnableBasicAuth {
		log.Printf("Using Basic Authentication")
		siteHandler = wrapBasicAuth(siteHandler, app.options.Credential)
	}

	siteHandler = wrapLogger(siteHandler)

	scheme := "http"
	if app.options.EnableTLS {
		scheme = "https"
	}
	log.Printf(
		"Server is starting with command: %s",
		strings.Join(app.command, " "),
	)
	if app.options.Address != "" {
		log.Printf(
			"URL: %s",
			(&url.URL{Scheme: scheme, Host: endpoint, Path: path + "/"}).String(),
		)
	} else {
		for _, address := range listAddresses() {
			log.Printf(
				"URL: %s",
				(&url.URL{
					Scheme: scheme,
					Host:   net.JoinHostPort(address, app.options.Port),
					Path:   path + "/",
				}).String(),
			)
		}
	}

	var err error
	app.server = manners.NewWithServer(
		&http.Server{Addr: endpoint, Handler: siteHandler},
	)
	if app.options.EnableTLS {
		err = app.server.ListenAndServeTLS(
			ExpandHomeDir(app.options.TLSCrtFile),
			ExpandHomeDir(app.options.TLSKeyFile),
		)
	} else {
		err = app.server.ListenAndServe()
	}
	if err != nil {
		return err
	}

	log.Printf("Exiting...")

	return nil
}
开发者ID:ujuettner,项目名称:gotty,代码行数:94,代码来源:app.go


示例17: Run

func (app *App) Run() error {
	if app.options.PermitWrite {
		log.Printf("Permitting clients to write input to the PTY.")
	}

	path := ""
	if app.options.RandomUrl {
		path += "/" + generateRandomString(8)
	}

	endpoint := net.JoinHostPort(app.options.Address, app.options.Port)

	wsHandler := http.HandlerFunc(app.handleWS)
	staticHandler := http.FileServer(
		&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"},
	)

	if app.options.Once {
		log.Printf("Once option is provided, accepting only one client")
		wsHandler = wrapOnce(wsHandler, app)
	}

	var siteMux = http.NewServeMux()
	siteMux.Handle(path+"/", http.StripPrefix(path+"/", staticHandler))
	siteMux.Handle(path+"/ws", wsHandler)

	siteHandler := http.Handler(siteMux)

	if app.options.Credential != "" {
		log.Printf("Using Basic Authentication")
		siteHandler = wrapBasicAuth(siteHandler, app.options.Credential)
	}

	siteHandler = wrapLogger(siteHandler)

	scheme := "http"
	if app.options.EnableTLS {
		scheme = "https"
	}
	log.Printf(
		"Server is starting with command: %s",
		strings.Join(app.options.Command, " "),
	)
	if app.options.Address != "" {
		log.Printf(
			"URL: %s",
			(&url.URL{Scheme: scheme, Host: endpoint, Path: path + "/"}).String(),
		)
	} else {
		for _, address := range listAddresses() {
			log.Printf(
				"URL: %s",
				(&url.URL{
					Scheme: scheme,
					Host:   net.JoinHostPort(address, app.options.Port),
					Path:   path + "/",
				}).String(),
			)
		}
	}

	var err error
	app.server = manners.NewWithServer(
		&http.Server{Addr: endpoint, Handler: siteHandler},
	)
	if app.options.EnableTLS {
		cert, key := app.loadTLSFiles()
		err = app.server.ListenAndServeTLS(cert, key)
	} else {
		err = app.server.ListenAndServe()
	}
	if err != nil {
		return err
	}

	log.Printf("Exiting...")

	return nil
}
开发者ID:kryptBlue,项目名称:gotty,代码行数:79,代码来源:app.go


示例18: GetUserToken

func GetUserToken(client_id string, client_secret string, socket string) (string, error) {
	mux := http.NewServeMux()

	result := make(chan string)
	error := make(chan error)

	redirect_uri := "http://" + socket + "/oauth"

	mux.HandleFunc("/oauth", func(w http.ResponseWriter, r *http.Request) {
		code := r.URL.Query().Get("code")
		if code == "" {
			w.WriteHeader(400)
			fmt.Fprintln(w, "You must specify code in querystring. Probably Oauth error...")
		}

		v := url.Values{}
		v.Set("client_id", client_id)
		v.Set("client_secret", client_secret)
		v.Set("grant_type", "authorization_code")
		v.Set("redirect_uri", redirect_uri)
		v.Set("code", code)

		resp, err := http.PostForm("https://api.twitch.tv/kraken/oauth2/token", v)
		if err != nil {
			error <- err
		}

		contents, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			error <- err
		}

		var tokenResp TokenResponse
		err2 := json.Unmarshal(contents, &tokenResp)

		if err2 != nil {
			error <- err2
		}
		w.Write([]byte("we got the token, close this now"))

		result <- tokenResp.AccessToken
	})

	mux.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {

		v := url.Values{}
		v.Set("client_id", client_id)
		v.Set("response_type", "code")
		v.Set("redirect_uri", redirect_uri)
		v.Set("scope", "user_read")

		url := "https://api.twitch.tv/kraken/oauth2/authorize?" + v.Encode()
		http.Redirect(w, r, url, 302)
	})

	s := manners.NewWithServer(&http.Server{
		Addr:    socket,
		Handler: mux,
	})
	defer s.Close()

	go func() {
		fmt.Println("Visit http://" + socket + "/authorize to get a key")
		s.ListenAndServe()
	}()

	select {
	case r := <-result:
		return r, nil
	case e := <-error:
		return "", e
	}
}
开发者ID:ubercow,项目名称:twitcher,代码行数:73,代码来源:twitch.go



注:本文中的github.com/braintree/manners.NewWithServer函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang bolt.DB类代码示例发布时间:2022-05-24
下一篇:
Golang slice.Sort函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap