本文整理匯總了Golang中github.com/golang/glog.Fatal函數的典型用法代碼示例。如果您正苦於以下問題:Golang Fatal函數的具體用法?Golang Fatal怎麽用?Golang Fatal使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Fatal函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: runBe
func runBe(configPath string) {
var config pb.BackendConfig
readConfig(configPath, &config)
if config.ServePath == "" {
glog.Fatal("No serving path was given in config.serve_path.")
}
srvConfig := config.GetServer()
glog.Infof("Serving path %v", config.ServePath)
l, err := net.Listen("tcp", srvConfig.Addr)
if err != nil {
glog.Fatalf("Failed to listen on %v: %v", srvConfig.Addr, err)
}
defer l.Close()
glog.Infof("Listening for requests on %v", l.Addr())
go updateFrontendPort(NewAEADOrDie(config.PortKey), l.Addr(), config.PortUpdateUrl)
server := &http.Server{
Handler: getBackendHTTPMux(&config),
}
if t := srvConfig.GetTls(); t != nil {
l = tls.NewListener(l, BackendTLSConfigOrDie(t))
} else if srvConfig.GetInsecure() {
PrintServerInsecureWarning()
} else {
glog.Fatalf("The config must specify one of 'insecure' or 'tls'")
}
glog.Fatal(server.Serve(l))
}
示例2: Save
func (asset *Asset) Save(session *gocql.Session) error {
if asset.Id.Timestamp() == 0 {
asset.Id = gocql.TimeUUID()
if err := session.Query(`INSERT INTO assets (id, name, path, contenttype, createdat, binary) VALUES (?, ?, ?, ?, ?, ?)`,
asset.Id, asset.Name, strings.Join(asset.Path, ","), asset.ContentType, asset.CreatedAt, asset.Binary).Exec(); err != nil {
glog.Fatal(err)
return err
}
if err := session.Query(`INSERT INTO assetbypaths (path, id, name) VALUES (?, ?, ?)`,
strings.Join(asset.Path, ","), asset.Id, asset.Name).Exec(); err != nil {
glog.Fatal(err)
return err
}
return nil
} else {
if err := session.Query(`UPDATE assets SET name = ?, path = ?, contenttype = ? WHERE id = ?`,
asset.Name, strings.Join(asset.Path, ","), asset.ContentType, asset.Id).Exec(); err != nil {
glog.Fatal(err)
return err
}
if err := session.Query(`UPDATE assetbypaths SET name = ?, path = ? WHERE id = ?`,
asset.Name, strings.Join(asset.Path, ","), asset.Id).Exec(); err != nil {
glog.Fatal(err)
return err
}
return nil
}
}
示例3: main
func main() {
flag.Parse()
storageDriver, err := NewStorageDriver(*argDbDriver)
if err != nil {
glog.Fatalf("Failed to connect to database: %s", err)
}
containerManager, err := manager.New(storageDriver)
if err != nil {
glog.Fatalf("Failed to create a Container Manager: %s", err)
}
// Register Docker.
if err := docker.Register(containerManager); err != nil {
glog.Errorf("Docker registration failed: %v.", err)
}
// Register the raw driver.
if err := raw.Register(containerManager); err != nil {
glog.Fatalf("raw registration failed: %v.", err)
}
// Handler for static content.
http.HandleFunc(static.StaticResource, func(w http.ResponseWriter, r *http.Request) {
err := static.HandleRequest(w, r.URL)
if err != nil {
fmt.Fprintf(w, "%s", err)
}
})
// Register API handler.
if err := api.RegisterHandlers(containerManager); err != nil {
glog.Fatalf("failed to register API handlers: %s", err)
}
// Redirect / to containers page.
http.Handle("/", http.RedirectHandler(pages.ContainersPage, http.StatusTemporaryRedirect))
// Register the handler for the containers page.
http.HandleFunc(pages.ContainersPage, func(w http.ResponseWriter, r *http.Request) {
err := pages.ServerContainersPage(containerManager, w, r.URL)
if err != nil {
fmt.Fprintf(w, "%s", err)
}
})
defer glog.Flush()
go func() {
glog.Fatal(containerManager.Start())
}()
glog.Infof("Starting cAdvisor version: %q", info.VERSION)
glog.Infof("About to serve on port ", *argPort)
addr := fmt.Sprintf(":%v", *argPort)
glog.Fatal(http.ListenAndServe(addr, nil))
}
示例4: RunV2
func (tunnel *Tunnel) RunV2() {
addr := fmt.Sprintf(":%d", config.tunnel_port_v2)
laddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
log.Fatal("resolve udp addr err:", err)
}
conn, err := net.ListenUDP("udp", laddr)
if err != nil {
log.Fatal("listen upd err:", err)
}
buff := make([]byte, 64*1024)
for {
n, raddr, err := conn.ReadFromUDP(buff)
if err != nil {
log.Warning("read udp err:", err)
continue
}
tunnel.HandleData(buff[:n], raddr, conn)
tunnel.GC()
}
}
示例5: HandleSignals
func HandleSignals(shutdownc <-chan io.Closer) {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP)
signal.Notify(c, syscall.SIGINT)
for {
sig := <-c
sysSig, ok := sig.(syscall.Signal)
if !ok {
glog.Fatal("Not a unix signal")
}
switch sysSig {
case syscall.SIGHUP:
case syscall.SIGINT:
glog.Warningln("Got SIGTERM: shutting down")
donec := make(chan bool)
go func() {
cl := <-shutdownc
if err := cl.Close(); err != nil {
exitf("Error shutting down: %v", err)
}
donec <- true
}()
select {
case <-donec:
glog.Infoln("Shut down completed.")
os.Exit(0)
case <-time.After(5 * time.Second):
exitf("Timeout shutting down. Exiting uncleanly.")
}
default:
glog.Fatal("Received another signal, should not happen.")
}
}
}
示例6: ListenAndServeKubeletServer
// ListenAndServeKubeletServer initializes a server to respond to HTTP network requests on the Kubelet.
func ListenAndServeKubeletServer(
host HostInterface,
resourceAnalyzer stats.ResourceAnalyzer,
address net.IP,
port uint,
tlsOptions *TLSOptions,
auth AuthInterface,
enableDebuggingHandlers bool,
runtime kubecontainer.Runtime) {
glog.Infof("Starting to listen on %s:%d", address, port)
handler := NewServer(host, resourceAnalyzer, auth, enableDebuggingHandlers, runtime)
s := &http.Server{
Addr: net.JoinHostPort(address.String(), strconv.FormatUint(uint64(port), 10)),
Handler: &handler,
ReadTimeout: 60 * time.Minute,
WriteTimeout: 60 * time.Minute,
MaxHeaderBytes: 1 << 20,
}
if tlsOptions != nil {
s.TLSConfig = tlsOptions.Config
glog.Fatal(s.ListenAndServeTLS(tlsOptions.CertFile, tlsOptions.KeyFile))
} else {
glog.Fatal(s.ListenAndServe())
}
}
示例7: main
func main() {
chain := gost.NewProxyChain()
if err := chain.AddProxyNodeString(options.ChainNodes...); err != nil {
glog.Fatal(err)
}
chain.Init()
var wg sync.WaitGroup
for _, ns := range options.ServeNodes {
serverNode, err := gost.ParseProxyNode(ns)
if err != nil {
glog.Fatal(err)
}
wg.Add(1)
go func(node gost.ProxyNode) {
defer wg.Done()
certFile, keyFile := node.Get("cert"), node.Get("key")
if certFile == "" {
certFile = gost.DefaultCertFile
}
if keyFile == "" {
keyFile = gost.DefaultKeyFile
}
cert, err := gost.LoadCertificate(certFile, keyFile)
if err != nil {
glog.Fatal(err)
}
server := gost.NewProxyServer(node, chain, &tls.Config{Certificates: []tls.Certificate{cert}})
glog.Fatal(server.Serve())
}(serverNode)
}
wg.Wait()
}
示例8: main
func main() {
flag.Parse()
glog.Infof("Starting Goship...")
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
auth.Initialize(auth.User{Name: *defaultUser, Avatar: *defaultAvatar}, []byte(*cookieSessionHash))
h, err := buildHandler(ctx)
if err != nil {
glog.Fatal(err)
}
w := io.WriteCloser(os.Stdout)
if *requestLog != "-" {
w, err = os.OpenFile(*requestLog, os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
glog.Fatalf("Cannot open request log %s: %v", *requestLog, err)
}
defer w.Close()
}
h = ghandlers.CombinedLoggingHandler(w, h)
fmt.Printf("Running on %s\n", *bindAddress)
s := &http.Server{
Addr: *bindAddress,
Handler: h,
}
if err := s.ListenAndServe(); err != nil {
glog.Fatal(err)
}
}
示例9: NewPostgresStorage
// Connect to the database.
func NewPostgresStorage() *PostgresStorage {
postgresUrlString := os.Getenv("STORAGE_URL")
if glog.V(2) {
glog.Infoln("postgresUrlString: ", postgresUrlString)
}
if postgresUrlString == "" {
glog.Fatal("STORAGE_URL cannot be empty.\nexport STORAGE_URL=postgres://user:[email protected]:port/db_name")
}
dataSource, err := pq.ParseURL(postgresUrlString)
if err != nil {
glog.Fatal("Could not read database string", err)
}
db, err := sql.Open("postgres", dataSource+" sslmode=disable fallback_application_name=bot")
if err != nil {
glog.Fatal("Could not connect to database.", err)
}
// The following 2 lines mitigate the leak of postgresql connection leak
// explicitly setting a maximum number of postgresql connections
db.SetMaxOpenConns(10)
// explicitly setting a maximum number of Idle postgresql connections
db.SetMaxIdleConns(2)
return &PostgresStorage{db}
}
示例10: main
func main() {
flag.Parse()
util.InitLogs()
defer util.FlushLogs()
if len(machineList) == 0 {
glog.Fatal("No machines specified!")
}
var cloud cloudprovider.Interface
switch *cloudProvider {
case "gce":
var err error
cloud, err = cloudprovider.NewGCECloud()
if err != nil {
glog.Fatal("Couldn't connect to GCE cloud: %#v", err)
}
default:
if len(*cloudProvider) > 0 {
glog.Infof("Unknown cloud provider: %s", *cloudProvider)
} else {
glog.Info("No cloud provider specified.")
}
}
var m *master.Master
if len(etcdServerList) > 0 {
m = master.New(etcdServerList, machineList, cloud)
} else {
m = master.NewMemoryServer(machineList, cloud)
}
glog.Fatal(m.Run(net.JoinHostPort(*address, strconv.Itoa(int(*port))), *apiPrefix))
}
示例11: run
func run(ctx *cli.Context) {
// Init API
api := New(Address)
api.Init()
log.Infof("Registering RPC Handler at %s", RPCPath)
api.Handle(RPCPath, http.HandlerFunc(handler.RPC))
log.Infof("Registering API Handler at %s", APIPath)
api.Handle(APIPath, http.HandlerFunc(restHandler))
// Initialise Server
service := micro.NewService(
micro.Name("go.micro.api"),
)
// Start API
if err := api.Start(); err != nil {
log.Fatal(err)
}
// Run server
if err := service.Run(); err != nil {
log.Fatal(err)
}
// Stop API
if err := api.Stop(); err != nil {
log.Fatal(err)
}
}
示例12: handleRequest
func handleRequest(req msgs.ClientRequest) msgs.ClientResponse {
glog.Info("Handling ", req.Request)
// check if already applied
found, res := c.Check(req)
if found {
glog.Info("Request found in cache")
return res // FAST PASS
}
// CONSENESUS ALGORITHM HERE
glog.Info("Passing request to consensus algorithm")
cons_io.IncomingRequests <- req
// wait for reply
notifyclient_mutex.Lock()
notifyclient[req] = make(chan msgs.ClientResponse)
notifyclient_mutex.Unlock()
reply := <-notifyclient[req]
// check reply
if reply.ClientID != req.ClientID {
glog.Fatal("ClientID is different")
}
if reply.RequestID != req.RequestID {
glog.Fatal("RequestID is different")
}
return reply
}
示例13: main
func main() {
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
pflag.Parse()
glog.Info("Starting HTTP server on port ", *argPort)
defer glog.Flush()
apiserverClient, err := CreateApiserverClient(*argApiserverHost, new(ClientFactoryImpl))
if err != nil {
glog.Fatal(err)
}
serverAPIVersion, err := apiserverClient.ServerAPIVersions()
if err != nil {
glog.Fatal(err)
}
// Display Apiserver version. This is just for tests.
println("Server API version: " + serverAPIVersion.GoString())
// Run a HTTP server that serves static public files from './public' and handles API calls.
// TODO(bryk): Disable directory listing.
http.Handle("/", http.FileServer(http.Dir("./public")))
http.Handle("/api/", CreateHttpApiHandler(apiserverClient))
glog.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *argPort), nil))
}
示例14: Fetch
func (s *ParallelShuffleFetcher) Fetch(shuffleId uint64, reduceId uint64, merge func(<-chan interface{})) {
glog.Infof("Fetching outputs for shuffle %d, reduce %d", shuffleId, reduceId)
serverUris := _env.mapOutputTracker.GetServerUris(shuffleId)
if serverUris == nil || len(serverUris) == 0 {
return
}
type _Part struct {
Idx int
Uri string
}
urisLen := len(serverUris)
parts := make([]_Part, urisLen)
perm := rand.Perm(urisLen) //shuffle uris
responses := make([]chan interface{}, urisLen)
for i, v := range perm {
u := serverUris[i]
parts[v] = _Part{
Idx: i,
Uri: u,
}
responses[i] = make(chan interface{})
}
go func() {
for _, v := range parts {
part, uri := v.Idx, v.Uri
req := &_FetcherRequest{
uri: uri,
shuffleId: shuffleId,
part: part,
reduceId: reduceId,
response: responses[part],
}
s.requests <- req
}
}()
wg := new(sync.WaitGroup)
for i := 0; i < urisLen; i++ {
wg.Add(1)
go func(idx int) {
defer wg.Done()
resp := <-responses[idx]
if err, ok := resp.(error); ok {
glog.Fatal(err)
} else if vals, ok := resp.(map[int]interface{}); ok {
ch := make(chan interface{})
go func() {
defer close(ch)
for _, v := range vals {
ch <- v
}
}()
merge(ch)
} else {
glog.Fatal("we do not know it.")
}
}(i)
}
wg.Wait()
}
示例15: main
func main() {
glog.Info("Web Server:Loading...")
b := flag.Bool("benchmark", false, "")
runtime.GOMAXPROCS(runtime.NumCPU())
flag.Parse()
if *b {
glog.Info("Benchmark Mode")
// Creat a file
f, err := os.Create("pprof")
if err != nil {
glog.Fatal(err)
}
if err = pprof.StartCPUProfile(f); err != nil {
glog.Fatal(err)
}
defer pprof.StopCPUProfile()
}
defer glog.Flush()
glog.Info("Read the config.")
if err := InitConf(); err != nil {
glog.Fatal(err)
}
glog.Info("[Web]: listener start.")
go start()
signal.HandleSignal(signal.InitSignal())
}