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

Golang graceful.Wait函数代码示例

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

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



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

示例1: main

func main() {
	var err error
	flags.Parse(os.Args[1:])

	conf, err := server.NewConfigFromFile(*confFile, os.Getenv("CONFIG"))
	if err != nil {
		log.Fatal(err)
	}

	srv := server.New(conf)
	if err := srv.Configure(); err != nil {
		log.Fatal(err)
	}

	lg.Infof("** Imgry Server v%s at %s **", imgry.VERSION, srv.Config.Bind)
	lg.Infof("** Engine: %s", srv.ImageEngine.Version())

	graceful.AddSignal(syscall.SIGINT, syscall.SIGTERM)
	graceful.Timeout(30 * time.Second)
	graceful.PreHook(srv.Close)
	graceful.PostHook(srv.Shutdown)

	err = graceful.ListenAndServe(srv.Config.Bind, srv.NewRouter())
	if err != nil {
		lg.Fatal(err.Error())
	}
	graceful.Wait()
}
开发者ID:palaiyacw,项目名称:imgry,代码行数:28,代码来源:main.go


示例2: Serve

// Serve starts the go-horizon system, binding it to a socket, setting up
// the shutdown signals and starting the appropriate db-streaming pumps.
func (a *App) Serve() {

	a.web.router.Compile()
	http.Handle("/", a.web.router)

	listenStr := fmt.Sprintf(":%d", a.config.Port)
	listener := bind.Socket(listenStr)
	log.Infof(a.ctx, "Starting horizon on %s", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()
	graceful.PreHook(func() {
		log.Info(a.ctx, "received signal, gracefully stopping")
		a.Cancel()
	})
	graceful.PostHook(func() {
		log.Info(a.ctx, "stopped")
	})

	if a.config.Autopump {
		sse.SetPump(a.ctx, sse.AutoPump)
	} else {
		sse.SetPump(a.ctx, db.NewLedgerClosePump(a.ctx, a.historyDb))
	}

	err := graceful.Serve(listener, http.DefaultServeMux)

	if err != nil {
		log.Panic(a.ctx, err)
	}

	graceful.Wait()
}
开发者ID:jacksonh,项目名称:go-horizon,代码行数:35,代码来源:app.go


示例3: Serve

// Serve starts the horizon system, binding it to a socket, setting up
// the shutdown signals and starting the appropriate db-streaming pumps.
func (a *App) Serve() {

	a.web.router.Compile()
	http.Handle("/", a.web.router)

	listenStr := fmt.Sprintf(":%d", a.config.Port)
	listener := bind.Socket(listenStr)
	log.Infof("Starting horizon on %s", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()
	graceful.PreHook(func() {
		log.Info("received signal, gracefully stopping")
		a.Close()
	})
	graceful.PostHook(func() {
		log.Info("stopped")
	})

	sse.SetPump(a.pump.Subscribe())

	err := graceful.Serve(listener, http.DefaultServeMux)

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

	graceful.Wait()
}
开发者ID:zenododobird,项目名称:horizon,代码行数:31,代码来源:app.go


示例4: main

func main() {
	flags.Parse(os.Args[1:])

	// Override config file by the CONFIG env var, if specified.
	if os.Getenv("CONFIG") != "" {
		*confFile = os.Getenv("CONFIG")
	}

	// Read Config.
	conf, err := config.New(*confFile)
	if err != nil {
		log.Fatal(err)
	}

	// Run QMD.
	app, err := qmd.New(conf)
	if err != nil {
		log.Fatal(err)
	}
	go app.WatchScripts()
	go app.StartWorkers()
	go app.ListenQueue()

	graceful.AddSignal(syscall.SIGINT, syscall.SIGTERM)
	graceful.PreHook(app.Close)

	// Start the API server.
	log.Printf("Starting QMD API at %s\n", conf.Bind)
	err = graceful.ListenAndServe(conf.Bind, rest.Routes(app))
	if err != nil {
		log.Fatal(err)
	}
	graceful.Wait()
}
开发者ID:pressly,项目名称:qmd,代码行数:34,代码来源:main.go


示例5: Serve

// Serve starts kami with reasonable defaults.
// It works (exactly) like Goji, looking for Einhorn, the bind flag, GOJI_BIND...
func Serve() {
	if !flag.Parsed() {
		flag.Parse()
	}

	// Install our handler at the root of the standard net/http default mux.
	// This allows packages like expvar to continue working as expected.
	http.Handle("/", Handler())

	listener := bind.Default()
	log.Println("Starting kami on", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()
	graceful.PreHook(func() { log.Printf("kami received signal, gracefully stopping") })
	graceful.PostHook(func() { log.Printf("kami stopped") })

	err := graceful.Serve(listener, http.DefaultServeMux)

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

	graceful.Wait()
}
开发者ID:gunosy,项目名称:kami,代码行数:27,代码来源:serve.go


示例6: main

func main() {
	var err error
	flags.Parse(os.Args[1:])

	conf, err := server.NewConfigFromFile(*confFile, os.Getenv("CONFIG"))
	if err != nil {
		log.Fatal(err)
	}

	srv := server.New(conf)

	graceful.AddSignal(syscall.SIGINT, syscall.SIGTERM)
	graceful.PreHook(func() { srv.Close() })

	if err := srv.Configure(); err != nil {
		log.Fatal(err)
	}

	lg.Infof("** Imgry Server v%s at %s **\n", imgry.VERSION, srv.Config.Server.Addr)
	lg.Infof("** Engine: %s", imagick.Engine{}.Version())

	err = graceful.ListenAndServe(srv.Config.Server.Addr, srv.NewRouter())
	if err != nil {
		lg.Fatal(err.Error())
	}
	graceful.Wait()
}
开发者ID:cinderalla,项目名称:imgry,代码行数:27,代码来源:main.go


示例7: main

func main() {
	start := time.Now()
	defer func() {
		end := time.Now()
		fmt.Printf("The call took %v to run.\n", end.Sub(start))
	}()
	if len(os.Args) == 1 {
		help("unkown")
		return
	}
	switch cmd := os.Args[1]; {
	case cmd == "server" || cmd == "s":
		startServer()
		defer graceful.Wait()
	case cmd == "generate" || cmd == "g":
		generate()
	case cmd == "init" || cmd == "i":
		workspace()
	case cmd == "new" || cmd == "n":
		article(os.Args[2:])
	case cmd == "help" || cmd == "h":
		if len(os.Args) > 2 {
			help(os.Args[2])
		}
	case cmd == "deploy" || cmd == "d":
		server.Deploy()
	default:
		help("unkown")
	}
}
开发者ID:gssdromen,项目名称:goblog,代码行数:30,代码来源:command.go


示例8: Serve

// Serve starts Goji using reasonable defaults.
func Serve() {
	if !flag.Parsed() {
		flag.Parse()
	}

	log.SetFlags(log.Flags() | log.Lmicroseconds)

	// Install our handler at the root of the standard net/http default mux.
	// This allows packages like expvar to continue working as expected.
	http.Handle("/", DefaultMux)

	listener := bind.Default()
	log.Println("Starting Goji on", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()

	err := graceful.Serve(listener, http.DefaultServeMux)

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

	graceful.Wait()
}
开发者ID:brandonparsons,项目名称:simulation.retirementplan.io,代码行数:26,代码来源:goji.go


示例9: serve

func serve() {
	goji.DefaultMux.Compile()
	// Install our handler at the root of the standard net/http default mux.
	// This allows packages like expvar to continue working as expected.
	http.Handle("/", goji.DefaultMux)

	listener := bind.Socket(bind.Sniff())
	log.Println("Starting Goji on", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()
	graceful.PreHook(func() { log.Printf("Goji received signal, gracefully stopping") })
	graceful.PostHook(func() {
		log.Printf("Goji stopped")
		log.Printf("Shutting down the server")
		handler.DB.Close()
		log.Printf("Database shut down. Terminating the process.")
	})

	err := graceful.Serve(listener, http.DefaultServeMux)

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

	graceful.Wait()
}
开发者ID:parkr,项目名称:gossip,代码行数:27,代码来源:gossip.go


示例10: Run

func Run() {
	http.Handle("/", DefaultServerMux)
	listener, err := net.Listen("tcp", Config.App.Bind)
	if err != nil {
		panic(err)
	}
	err = graceful.Serve(listener, DefaultServerMux)
	if err != nil {
		panic(err)
	}
	graceful.Wait()
}
开发者ID:keimoon,项目名称:voicewiki,代码行数:12,代码来源:router.go


示例11: HTTPServe

func (s *Server) HTTPServe() {
	httpSocket := bind.Socket(s.HTTPAddr)
	graceful.Timeout(10 * time.Second)
	graceful.PreHook(func() {
		s.logger.Info("Terminating HTTP listener")
	})
	graceful.HandleSignals()
	s.logger.WithField("address", s.HTTPAddr).Info("HTTP server listening")
	bind.Ready()

	if err := graceful.Serve(httpSocket, s.Handler()); err != nil {
		s.logger.WithError(err).Error("HTTP server shut down due to error")
	}
	graceful.Wait()
}
开发者ID:carriercomm,项目名称:veneur,代码行数:15,代码来源:server.go


示例12: main

func main() {
	// sets the maximum number of CPUs that can be executing simultaneously
	runtime.GOMAXPROCS(runtime.NumCPU())

	// override defaults via env vars
	if os.Getenv("ES_HOST") != "" {
		esHost = os.Getenv("ES_HOST")
	}
	if os.Getenv("ES_PORT") != "" {
		esPort = os.Getenv("ES_PORT")
	}
	if os.Getenv("REDIS_HOST") != "" {
		redisHost = os.Getenv("REDIS_HOST")
	}
	if os.Getenv("REDIS_PORT") != "" {
		redisPort = os.Getenv("REDIS_PORT")
	}
	if os.Getenv("PUBLIC_DIR") != "" {
		publicDir = os.Getenv("PUBLIC_DIR")
	}

	// log endpoints
	log.Infof("Redis endpoint set to %s:%s", redisHost, redisPort)
	log.Infof("Elasticsearch endpoint set to %s:%s", esHost, esPort)

	// register available tiling types
	tile.Register("heatmap", elastic.NewHeatmapTile(esHost, esPort))
	tile.Register("topic_count", elastic.NewTopCountTile(esHost, esPort))
	// register available meta data types
	meta.Register("default", elastic.NewDefaultMeta(esHost, esPort))
	// register available store types
	store.Register("redis", redis.NewConnection(redisHost, redisPort))

	// create server
	app := api.New(publicDir)

	// catch kill signals for graceful shutdown
	graceful.AddSignal(syscall.SIGINT, syscall.SIGTERM)
	// start server
	log.Infof("Prism server listening on port %s", port)
	err := graceful.ListenAndServe(":"+port, app)
	if err != nil {
		log.Error(err)
	}
	// wait until server gracefully exits
	graceful.Wait()
}
开发者ID:unchartedsoftware,项目名称:census-hackathon-2016,代码行数:47,代码来源:main.go


示例13: serve

func serve(mux *web.Mux, bindProtocol, bindPort string) {
	// For now, this is completely lifted from goji's default handler.
	http.Handle("/", mux)
	log.Printf("Starting on %v/%v", bindProtocol, bindPort)
	graceful.HandleSignals()
	listener, err := net.Listen(bindProtocol, bindPort)
	if err != nil {
		log.Fatalf("Couldn't open socket on %v/%v: %v", bindProtocol, bindPort, err)
	}
	graceful.PreHook(func() { log.Info("Received signal, gracefully stopping.") })
	graceful.PostHook(func() { log.Info("Stopped.") })
	err = graceful.Serve(listener, http.DefaultServeMux)
	if err != nil {
		log.Fatalf("Couldn't serve on %v/%v: %v", bindProtocol, bindPort, err)
	}
	graceful.Wait()
}
开发者ID:backerman,项目名称:eveindy,代码行数:17,代码来源:server.go


示例14: SetupMainServer

// SetupMainServer allocates a listener socket and starts a web server with graceful restart
// on the specified IP address and port. The ipPort has the format "ip_address:port" or
// ":port" for 0.0.0.0/port.
func SetupMainServer(ipPort string, mux *web.Mux) {
	listener, err := net.Listen("tcp4", ipPort)
	if err != nil {
		FatalError(err.Error())
	}

	// Install our handler at the root of the standard net/http default mux.
	// This allows packages like expvar to continue working as expected.
	mux.Compile()
	http.Handle("/", mux)

	graceful.HandleSignals()
	graceful.PreHook(func() { log15.Warn("Gracefully stopping on signal") })
	graceful.PostHook(func() { log.Printf("Gracefully stopped") })

	err = graceful.Serve(listener, http.DefaultServeMux)
	if err != nil {
		FatalError(err.Error())
	}

	graceful.Wait()
}
开发者ID:rightscale,项目名称:go-boilerplate,代码行数:25,代码来源:main.go


示例15: main

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	// Parse the flags and store them as a conf struct
	flag.Parse()
	conf := skeletor.Conf{
		Prod:    *prod,
		Version: version,
	}
	skeletor.SaveConf(&conf)

	// Start the web server
	graceful.AddSignal(syscall.SIGINT, syscall.SIGTERM)
	app := api.New()
	log.Println("Skeletor server listening on", *bind)
	err := graceful.ListenAndServe(*bind, app)
	if err != nil {
		log.Fatal(err)
	}

	graceful.Wait()
}
开发者ID:crowdriff,项目名称:skeletor,代码行数:22,代码来源:main.go


示例16: ServeTLS

/**
*There was no support of TLS in kami
*Copy-paste from Goji
**/
func ServeTLS(config *tls.Config) {
	if !flag.Parsed() {
		flag.Parse()
	}

	http.Handle("/", kami.Handler())

	listener := tls.NewListener(bind.Default(), config)
	log.Println("Starting kami on", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()
	graceful.PreHook(func() { log.Printf("kami received signal, gracefully stopping") })
	graceful.PostHook(func() { log.Printf("kami stopped") })

	err := graceful.Serve(listener, http.DefaultServeMux)

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

	graceful.Wait()
}
开发者ID:yauhen-l,项目名称:petrucho,代码行数:27,代码来源:kami-tls.go


示例17: main

func main() {
	// Create a DB with the test table and seed data
	db, _ := gorm.Open("sqlite3", "./grapi-example.db")
	seedDb(&db)

	// Create an API server. We need to supply JwtKey if we're doing authentication.
	// We pass db.Debug() instead of &db so you can see the sql queries in the log.
	a := grapi.New(grapi.Options{Db: db.Debug(), JwtKey: "SomethingLongAndDifficultToGuess"})
	http.Handle("/api/", a)
	http.HandleFunc("/", indexHandler)

	// Allow logging in with the User model at /api/login. Details will be checked by User.CheckLoginDetails()
	a.SetAuth(&User{}, "login")

	// Setup some useful RouteOptions that we will use for adding authenticated routs.

	// This one allows only authenticated users (ie. they've logged in at "/login" above).
	onlyAuthenticated := grapi.RouteOptions{UseDefaultAuth: true}

	// Only Allow Admin
	onlyAdmin := grapi.RouteOptions{
		UseDefaultAuth: true,
		// Add an authorize callback. This is a Martini handler, and can access the LoginModel
		// used for authentication. As we called API.SetAuth with &User{} this is guaranteed to
		// be a *User, so we can do a type assertion.
		Authorize: func(req grapi.ReqToAuthorize) bool {
			user := req.GetLoginObject().(*User)
			if !user.Admin {
				http.Error(req.GetResponseWriter(), `{"error":"You need to be admin to do that"}`, 403)
				return false
			}
			return true
		}}

	// This RouteOptions can be used for any table with a user_id field. If logged in as admin
	// it allows anything. If logged in as user it limits GETs to those of own user_id, and
	// delete to own user_id. It also prevents changing user ownership.
	onlyOwnUnlessAdmin := grapi.RouteOptions{
		UseDefaultAuth: true,
		Query: func(req grapi.ReqToLimit) bool {
			user := req.GetLoginObject().(*User)
			// Scope the requests database to only contain owned items. This prevents unauthorized
			// GET, DELETE, and PATCH requests, and limits the index to own items.
			if !user.Admin {
				req.SetDB(req.GetDB().Where("user_id = ?", user.ID))
			}
			return true
		},
		CheckUpload: func(req grapi.ReqULToCheck) bool {
			user := req.GetLoginObject().(*User)
			uploaded := req.GetUpload().(BelongsToUser)
			// For PATCH and POST routes we also need to check that the uploaded object has the correct user_id
			if !user.Admin && user.ID != uploaded.UserId() {
				http.Error(req.GetResponseWriter(), `{"error":"Only admin can change a user_id"}`, 403)
				return false
			}
			return true
		}}

	// Add the Default REST routes for User.
	// If two RouteOptions structures are provided the first is used for Read routes,
	// and the second for Write routes. If three are given then the third is used for
	// DELETE requests.
	a.AddDefaultRoutes(&User{}, onlyAuthenticated, onlyAdmin)

	// We want people to only see their own widgets, unless they are admin.
	a.AddDefaultRoutes(&PrivateWidget{}, onlyOwnUnlessAdmin)

	// We are going to make the widget list available to view by user at
	// /api/user/:user_id/private_widgets
	a.AddIndexRoute(&PrivateWidget{},
		&grapi.RouteOptions{
			Prefix: "/user/:user_id",
			Query: func(req grapi.ReqToLimit) bool {
				req.SetDB(req.GetDB().Where("user_id = ?", req.Param("user_id")))
				return true
			}})

	// Run the server.
	listener, err := net.Listen("tcp", "127.0.0.1:3000")
	if err != nil {
		panic(err.Error())
	}
	err = graceful.Serve(listener, http.DefaultServeMux)
	if err != nil {
		panic(err.Error())
	}

	graceful.Wait()
}
开发者ID:ivanol,项目名称:grapi,代码行数:90,代码来源:detailed.go


示例18: main

func main() {
	// Parse the flags
	flag.Parse()

	logrus.Infoln("**********************************************************")
	logrus.Infoln("goproject server starting ...")
	logrus.Infof("Version : %s (%s-%s)", version.Version, version.Revision, version.Branch)

	// Set localtime to UTC
	time.Local = time.UTC

	// Put config into the environment package
	shared.Config = &shared.Flags{
		BindAddress:      *bindAddress,
		LogFormatterType: *logFormatterType,
		ForceColors:      *forceColors,
		RavenDSN:         *ravenDSN,

		DatabaseDriver:    *databaseDriver,
		DatabaseHost:      *databaseHost,
		DatabaseNamespace: *databaseNamespace,
		DatabaseUser:      *databaseUser,
		DatabasePassword:  *databasePassword,

		MemcachedHosts: *memcachedHosts,
		RedisHost:      *redisHost,
	}

	// Generate a mux
	mux := system.Setup(shared.Config)

	// Make the mux handle every request
	http.Handle("/", mux)

	// Log that we're starting the server
	shared.Log.WithFields(logrus.Fields{
		"address": shared.Config.BindAddress,
	}).Info("Starting the HTTP server")

	// Initialize the goroutine listening to signals passed to the app
	graceful.HandleSignals()

	// Pre-graceful shutdown event
	graceful.PreHook(func() {
		shared.Log.Info("Received a signal, stopping the application")
	})

	// Post-shutdown event
	graceful.PostHook(func() {
		shared.Log.Info("Stopped the application")
	})

	// Listen to the passed address
	listener, err := net.Listen("tcp", shared.Config.BindAddress)
	if err != nil {
		shared.Log.WithFields(logrus.Fields{
			"error":   err,
			"address": *bindAddress,
		}).Fatal("Cannot set up a TCP listener")
	}

	// Start the listening
	err = graceful.Serve(listener, http.DefaultServeMux)
	if err != nil {
		// Don't use .Fatal! We need the code to shut down properly.
		shared.Log.Error(err)
	}

	// If code reaches this place, it means that it was forcefully closed.

	// Wait until open connections close.
	graceful.Wait()
}
开发者ID:Zenithar,项目名称:golang-base-project,代码行数:73,代码来源:main.go


示例19: main

func main() {
	// Parse the flags
	flag.Parse()

	// Put config into the environment package
	env.Config = &env.Flags{
		BindAddress:      *bindAddress,
		APIVersion:       *apiVersion,
		LogFormatterType: *logFormatterType,
		ForceColors:      *forceColors,
		EmailDomain:      *emailDomain,

		SessionDuration: *sessionDuration,

		RedisAddress:  *redisAddress,
		RedisDatabase: *redisDatabase,
		RedisPassword: *redisPassword,

		RethinkDBAddress:  *rethinkdbAddress,
		RethinkDBKey:      *rethinkdbKey,
		RethinkDBDatabase: *rethinkdbDatabase,

		NSQdAddress:    *nsqdAddress,
		LookupdAddress: *lookupdAddress,

		YubiCloudID:  *yubiCloudID,
		YubiCloudKey: *yubiCloudKey,

		SlackURL:      *slackURL,
		SlackLevels:   *slackLevels,
		SlackChannel:  *slackChannel,
		SlackIcon:     *slackIcon,
		SlackUsername: *slackUsername,

		BloomFilter: *bloomFilter,
		BloomCount:  *bloomCount,

		RavenDSN: *ravenDSN,
	}

	// Generate a mux
	mux := setup.PrepareMux(env.Config)

	// Make the mux handle every request
	http.Handle("/", mux)

	// Log that we're starting the server
	env.Log.WithFields(logrus.Fields{
		"address": env.Config.BindAddress,
	}).Info("Starting the HTTP server")

	// Initialize the goroutine listening to signals passed to the app
	graceful.HandleSignals()

	// Pre-graceful shutdown event
	graceful.PreHook(func() {
		env.Log.Info("Received a singnal, stopping the application")
	})

	// Post-shutdown event
	graceful.PostHook(func() {
		env.Log.Info("Stopped the application")
	})

	// Listen to the passed address
	listener, err := net.Listen("tcp", env.Config.BindAddress)
	if err != nil {
		env.Log.WithFields(logrus.Fields{
			"error":   err,
			"address": *bindAddress,
		}).Fatal("Cannot set up a TCP listener")
	}

	// Start the listening
	err = graceful.Serve(listener, http.DefaultServeMux)
	if err != nil {
		// Don't use .Fatal! We need the code to shut down properly.
		env.Log.Error(err)
	}

	// If code reaches this place, it means that it was forcefully closed.

	// Wait until open connections close.
	graceful.Wait()
}
开发者ID:carriercomm,项目名称:api-1,代码行数:85,代码来源:main.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang web.New函数代码示例发布时间:2022-05-28
下一篇:
Golang graceful.PostHook函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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