コード例 #1
0
ファイル: app.go プロジェクト: jacksonh/go-horizon
// 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()
}
コード例 #2
0
// 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()
}
コード例 #3
0
ファイル: serve.go プロジェクト: gunosy/kami
// 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()
}
コード例 #4
0
ファイル: gossip.go プロジェクト: parkr/gossip
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()
}
コード例 #5
0
ファイル: saypi.go プロジェクト: antifuchs/saypi
func main() {
	appCfg, srvCfg, err := readConfiguration()
	if err != nil {
		log.Fatalf("Error parsing configuration. event=config_error error=%q", err)
	}

	a, err := app.New(appCfg)
	if err != nil {
		log.Fatalf("Error initializing app event=init_error error=%q", err)
	}
	defer a.Close()

	listener, err := net.Listen("tcp", srvCfg.HTTPAddr)
	if err != nil {
		log.Fatalf("Error attempting to listen on port, event=listen_error address=%q error=%q", err, srvCfg.HTTPAddr)
	}

	graceful.Timeout(httpGrace)
	graceful.HandleSignals()
	graceful.PreHook(func() {
		log.Print("Shutting down. event=app_stop")
	})
	log.Printf("Starting. event=app_start address=%q", listener.Addr())
	bind.Ready()
	err = graceful.Serve(listener, a)
	if err != nil {
		log.Fatalf("Shutting down after a fatal error. event=fatal_error error=%q", err)
	}
}
コード例 #6
0
ファイル: app.go プロジェクト: zenododobird/horizon
// 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()
}
コード例 #7
0
ファイル: router.go プロジェクト: keimoon/voicewiki
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()
}
コード例 #8
0
ファイル: server.go プロジェクト: carriercomm/veneur
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()
}
コード例 #9
0
ファイル: server.go プロジェクト: backerman/eveindy
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()
}
コード例 #10
0
ファイル: main.go プロジェクト: rightscale/go-boilerplate
// 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()
}
コード例 #11
0
ファイル: kami-tls.go プロジェクト: yauhen-l/petrucho
/**
*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()
}
コード例 #12
0
ファイル: main.go プロジェクト: Zenithar/golang-base-project
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()
}
コード例 #13
0
ファイル: detailed.go プロジェクト: ivanol/grapi
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()
}
コード例 #14
0
ファイル: main.go プロジェクト: carriercomm/api-1
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()
}