当前位置: 首页>>代码示例>>Golang>>正文


Golang log.Fatalf函数代码示例

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


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

示例1: sshCreate

func sshCreate(ctx *cli.Context) {
	if len(ctx.Args()) != 2 {
		log.Fatal("Must provide name and public key file.")
	}

	tokenSource := &TokenSource{
		AccessToken: APIKey,
	}
	oauthClient := oauth2.NewClient(oauth2.NoContext, tokenSource)
	client := godo.NewClient(oauthClient)

	file, err := os.Open(ctx.Args()[1])
	if err != nil {
		log.Fatalf("Error opening key file: %s.", err)
	}

	keyData, err := ioutil.ReadAll(file)
	if err != nil {
		log.Fatalf("Error reading key file: %s.", err)
	}

	createRequest := &godo.KeyCreateRequest{
		Name:      ctx.Args().First(),
		PublicKey: string(keyData),
	}
	key, _, err := client.Keys.Create(createRequest)
	if err != nil {
		log.Fatal(err)
	}

	WriteOutput(key)
}
开发者ID:phillbaker,项目名称:doctl,代码行数:32,代码来源:sshkey.go

示例2: startProfile

func startProfile() {
	if cpuprofile != "" {
		f, err := os.Create(cpuprofile)
		if err != nil {
			log.Fatalf("%v", err)
		}
		if err := pprof.StartCPUProfile(f); err != nil {
			log.Fatalf("%v", err)
		}
		AtExit(pprof.StopCPUProfile)
	}
	if memprofile != "" {
		if memprofilerate != 0 {
			runtime.MemProfileRate = int(memprofilerate)
		}
		f, err := os.Create(memprofile)
		if err != nil {
			log.Fatalf("%v", err)
		}
		AtExit(func() {
			runtime.GC() // profile all outstanding allocations
			if err := pprof.WriteHeapProfile(f); err != nil {
				log.Fatalf("%v", err)
			}
		})
	}
}
开发者ID:sreis,项目名称:go,代码行数:27,代码来源:util.go

示例3: urlShortenerMain

func urlShortenerMain(client *http.Client, argv []string) {
	if len(argv) != 1 {
		fmt.Fprintf(os.Stderr, "Usage: urlshortener http://goo.gl/xxxxx     (to look up details)\n")
		fmt.Fprintf(os.Stderr, "       urlshortener http://example.com/long (to shorten)\n")
		return
	}

	svc, _ := urlshortener.New(client)
	urlstr := argv[0]

	// short -> long
	if strings.HasPrefix(urlstr, "http://goo.gl/") || strings.HasPrefix(urlstr, "https://goo.gl/") {
		url, err := svc.Url.Get(urlstr).Do()
		if err != nil {
			log.Fatalf("URL Get: %v", err)
		}
		fmt.Printf("Lookup of %s: %s\n", urlstr, url.LongUrl)
		return
	}

	// long -> short
	url, err := svc.Url.Insert(&urlshortener.Url{
		Kind:    "urlshortener#url", // Not really needed
		LongUrl: urlstr,
	}).Do()
	if err != nil {
		log.Fatalf("URL Insert: %v", err)
	}
	fmt.Printf("Shortened %s => %s\n", urlstr, url.Id)
}
开发者ID:GamerockSA,项目名称:dex,代码行数:30,代码来源:urlshortener.go

示例4: Example_buildBinaryDeb

func Example_buildBinaryDeb() {

	pkg := deb.NewControlDefault("testpkg", "me", "[email protected]", "Dummy package for doing nothing", "testpkg is package ", true)
	exesMap := map[string][]string{
		"amd64": []string{filepath.Join(deb.TempDirDefault, "/a.amd64")},
		"i386":  []string{filepath.Join(deb.TempDirDefault, "/a.i386")},
		"armhf": []string{filepath.Join(deb.TempDirDefault, "/a.armhf")}}
	err := createExes(exesMap)
	if err != nil {
		log.Fatalf("%v", err)
	}
	artifacts, err := deb.NewWriters(pkg)
	if err != nil {
		log.Fatalf("Error building binary: %v", err)
	}
	artifacts[deb.ArchAmd64].MappedFiles = map[string]string{"/usr/bin/a": filepath.Join(deb.TempDirDefault, "/a.amd64")}
	artifacts[deb.ArchI386].MappedFiles = map[string]string{"/usr/bin/a": filepath.Join(deb.TempDirDefault, "/a.i386")}
	artifacts[deb.ArchArmhf].MappedFiles = map[string]string{"/usr/bin/a": filepath.Join(deb.TempDirDefault, "/a.armhf")}
	buildDeb := func(art *deb.Writer) error {
		//generate artifact here ...
		return nil
	}
	for arch, artifact := range artifacts {
		//build binary deb here ...
		err = buildDeb(artifact)
		if err != nil {
			log.Fatalf("Error building for '%s': %v", arch, err)
		}
	}
}
开发者ID:himanshugpt,项目名称:evergreen,代码行数:30,代码来源:deb_writer_test.go

示例5: translate

func translate(typedJson interface{}) interface{} {
	switch v := typedJson.(type) {
	case map[string]interface{}:
		if len(v) == 2 && in("type", v) && in("value", v) {
			return untag(v)
		}
		m := make(map[string]interface{}, len(v))
		for k, v2 := range v {
			m[k] = translate(v2)
		}
		return m
	case []interface{}:
		tabArray := make([]map[string]interface{}, len(v))
		for i := range v {
			if m, ok := translate(v[i]).(map[string]interface{}); ok {
				tabArray[i] = m
			} else {
				log.Fatalf("JSON arrays may only contain objects. This " +
					"corresponds to only tables being allowed in " +
					"TOML table arrays.")
			}
		}
		return tabArray
	}
	log.Fatalf("Unrecognized JSON format '%T'.", typedJson)
	panic("unreachable")
}
开发者ID:hellrider42,项目名称:ShortLinkRestApi,代码行数:27,代码来源:main.go

示例6: ExampleClient_Listen

func ExampleClient_Listen() {
	config := &ClientConfig{
		User: "username",
		Auth: []AuthMethod{
			Password("password"),
		},
	}
	// Dial your ssh server.
	conn, err := Dial("tcp", "localhost:22", config)
	if err != nil {
		log.Fatalf("unable to connect: %s", err)
	}
	defer conn.Close()

	// Request the remote side to open port 8080 on all interfaces.
	l, err := conn.Listen("tcp", "0.0.0.0:8080")
	if err != nil {
		log.Fatalf("unable to register tcp forward: %v", err)
	}
	defer l.Close()

	// Serve HTTP with your SSH server acting as a reverse proxy.
	http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(resp, "Hello world!\n")
	}))
}
开发者ID:BillTheBest,项目名称:fleet,代码行数:26,代码来源:example_test.go

示例7: Load

func Load() Config {
	file, err := os.Open(Path())

	var wConfig Config

	if err != nil {
		log.Printf("Config file not found. Creating new...")
		err = CreateNewConfigFile()

		if err != nil {
			log.Fatalf("Unable to create new config file. Error: %v", err)
			os.Exit(1)
		}

		file, err = os.Open(Path())
		if err != nil {
			log.Fatalf("Unable to read new config file. Error: %v", err)
			os.Exit(1)
		}
	}

	defer file.Close()

	toml.DecodeReader(file, &wConfig)

	return wConfig
}
开发者ID:sparkymat,项目名称:wain,代码行数:27,代码来源:config.go

示例8: changeUser

// Takes care of dropping privileges to the desired user
func changeUser(u string) {
	if u == "" {
		return
	}
	userent, err := utils.UserLookup(u)
	if err != nil {
		log.Fatalf("Unable to find user %v: %v", u, err)
	}

	uid, err := strconv.Atoi(userent.Uid)
	if err != nil {
		log.Fatalf("Invalid uid: %v", userent.Uid)
	}
	gid, err := strconv.Atoi(userent.Gid)
	if err != nil {
		log.Fatalf("Invalid gid: %v", userent.Gid)
	}

	if err := syscall.Setgid(gid); err != nil {
		log.Fatalf("setgid failed: %v", err)
	}
	if err := syscall.Setuid(uid); err != nil {
		log.Fatalf("setuid failed: %v", err)
	}
}
开发者ID:JeremyGrosser,项目名称:docker,代码行数:26,代码来源:sysinit.go

示例9: main

func main() {
	var statsdHost = flag.String("statsd_host", "127.0.0.1", "Statsd host")
	var statsdPort = flag.Int("statsd_port", 8125, "Statsd host")
	var nodename = flag.String("nodename", "riak", "Riak node name")
	var riakHost = flag.String("riak_host", "127.0.0.1", "Riak host")
	var riakHttpPort = flag.Int("riak_http_port", 8098, "Riak HTTP port")
	flag.Parse()

	// First ping to node to make sure it works
	err := pingRiak(*riakHost, *riakHttpPort)
	if err != nil {
		log.Fatalf("Error: %v", err)
		os.Exit(1)
	}
	statsd := fmt.Sprintf("%s:%d", *statsdHost, *statsdPort)
	addr, err := net.ResolveUDPAddr("udp", statsd)
	if err != nil {
		log.Fatalf("Couldn't resolve UDP addr: %v", err)
		os.Exit(1)
	}
	conn, err := net.DialUDP("udp", nil, addr)
	if err != nil {
		log.Fatalf("Couldn't connect to statsd at %s", statsd)
		os.Exit(1)
	}

	// every 60s run hit the stats endpoint and then send to statsd
	interval := time.NewTicker(time.Second * 60)
	for _ = range interval.C {
		go getAndSendRiakMetrics(conn, *nodename, *riakHost, *riakHttpPort)
	}
}
开发者ID:jjmalina,项目名称:riak-statsd,代码行数:32,代码来源:main.go

示例10: main

func main() {
	flag.Parse()

	if *flagVersion {
		fmt.Fprintf(os.Stderr, "hello version: %s\nGo version: %s (%s/%s)\n",
			buildinfo.Version(), runtime.Version(), runtime.GOOS, runtime.GOARCH)
		return
	}

	log.Printf("Starting hello version %s; Go %s (%s/%s)", buildinfo.Version(), runtime.Version(),
		runtime.GOOS, runtime.GOARCH)

	listenAddr, err := app.ListenAddress()
	if err != nil {
		log.Fatalf("Listen address: %v", err)
	}
	conf := appConfig()
	ws := webserver.New()
	ws.Handle("/", &helloHandler{who: conf.Word})
	// TODO(mpl): handle status requests too. Camlistore will send an auth
	// token in the extra config that should be used as the "password" for
	// subsequent status requests.
	if err := ws.Listen(listenAddr); err != nil {
		log.Fatalf("Listen: %v", err)
	}

	ws.Serve()
}
开发者ID:pombredanne,项目名称:camlistore,代码行数:28,代码来源:main.go

示例11: Authorize

// Authorize is for remote authorization of headless machines.
//
// It expects 1 or 3 arguments
//
//   rclone authorize "fs name"
//   rclone authorize "fs name" "client id" "client secret"
func Authorize(args []string) {
	switch len(args) {
	case 1, 3:
	default:
		log.Fatalf("Invalid number of arguments: %d", len(args))
	}
	newType := args[0]
	fs, err := Find(newType)
	if err != nil {
		log.Fatalf("Failed to find fs: %v", err)
	}

	if fs.Config == nil {
		log.Fatalf("Can't authorize fs %q", newType)
	}
	// Name used for temporary fs
	name := "**temp-fs**"

	// Make sure we delete it
	defer DeleteRemote(name)

	// Indicate that we want fully automatic configuration.
	ConfigFile.SetValue(name, ConfigAutomatic, "yes")
	if len(args) == 3 {
		ConfigFile.SetValue(name, ConfigClientID, args[1])
		ConfigFile.SetValue(name, ConfigClientSecret, args[2])
	}
	fs.Config(name)
}
开发者ID:stengaard,项目名称:rclone,代码行数:35,代码来源:config.go

示例12: contactOthers

// Find all sibling pods in the service and post to their /write handler.
func contactOthers(state *State) {
	const waitTimeout = 2 * time.Minute
	defer state.doneContactingPeers()
	client, err := client.NewInCluster()
	if err != nil {
		log.Fatalf("Unable to create client; error: %v\n", err)
	}
	// Double check that that worked by getting the server version.
	if v, err := client.Discovery().ServerVersion(); err != nil {
		log.Fatalf("Unable to get server version: %v\n", err)
	} else {
		log.Printf("Server version: %#v\n", v)
	}

	for start := time.Now(); time.Since(start) < waitTimeout; time.Sleep(5 * time.Second) {
		eps := getWebserverEndpoints(client)
		if eps.Len() >= *peerCount {
			break
		}
		state.Logf("%v/%v has %v endpoints, which is less than %v as expected. Waiting for all endpoints to come up.", *namespace, *service, len(eps), *peerCount)
	}

	// Do this repeatedly, in case there's some propagation delay with getting
	// newly started pods into the endpoints list.
	for i := 0; i < 15; i++ {
		eps := getWebserverEndpoints(client)
		for ep := range eps {
			state.Logf("Attempting to contact %s", ep)
			contactSingle(ep, state)
		}
		time.Sleep(5 * time.Second)
	}
}
开发者ID:leecalcote,项目名称:kubernetes,代码行数:34,代码来源:webserver.go

示例13: main

func main() {
	db, err := sql.Open("sqlite3", ":memory:")
	if err != nil {
		log.Fatalf("cannot open an SQLite memory database: %v", err)
	}
	defer db.Close()

	// sqlite> select strftime('%J', '2015-04-13T19:22:19.773Z'), strftime('%J', '2015-04-13T19:22:19');
	_, err = db.Exec("CREATE TABLE unix_time (time datetime)")
	if err != nil {
		log.Fatalf("cannot create schema: %v", err)
	}

	_, err = db.Exec("INSERT INTO unix_time (time) VALUES (strftime('%Y-%m-%dT%H:%MZ','now'))")
	if err != nil {
		log.Fatalf("cannot insert: %v", err)
	}

	row := db.QueryRow("SELECT time FROM unix_time")
	fmt.Printf("Rec: %v\nScan: ", *row)

	var t time.Time
	err = row.Scan(TimeStamp{&t})
	if err != nil {
		log.Fatalf("cannot scan time: %v", err)
	}
	fmt.Println(t)
}
开发者ID:suntong,项目名称:lang,代码行数:28,代码来源:go-sqlite3-memory.go

示例14: main

func main() {
	flag.Parse()

	rpc.Register(new(Worker))
	l, e := net.Listen("tcp", ":"+strconv.Itoa(*port))
	if e != nil {
		log.Fatal("listen error:", e)
	}
	log.Print("listening for connections on ", l.Addr())

	if *connect != "" {
		log.Printf("calling %s\n", *connect)
		conn, err := net.Dial("tcp", *connect)
		if err != nil {
			log.Fatalf("failed to connect to %s: %s", *connect, err)
		}
		addr, _, err := net.SplitHostPort(conn.LocalAddr().String())
		if err != nil {
			log.Fatalf("failed to get the local address: %s", err)
		}
		laddr := net.JoinHostPort(addr, strconv.Itoa(*port))
		client := rpc.NewClient(conn)
		var res struct{}
		client.Call("WorkerList.Add", laddr, &res)
		client.Close()
	}

	rpc.Accept(l)
}
开发者ID:velour,项目名称:distribute,代码行数:29,代码来源:main.go

示例15: main

func main() {

	var x int32
	var y int32
	flag.Parse()
	conn, err := openTLSClient("127.0.0.1:8000")
	sum := addservice.NewAddServiceClient(conn)
	if err != nil {
		log.Fatalf("dial: %s", err)
	}

	for {
		fmt.Printf("Enter 2 numbers> ")
		fmt.Scan(&x)
		fmt.Scan(&y)
		fmt.Printf("Sending %d and %d\n", x, y)
		in := &addservice.AddMessage{X: &x, Y: &y}
		out := &addservice.SumMessage{}
		if err := sum.Add(in, out); err != nil {
			log.Fatalf("Add failed with: %s", err)
		}
		if out.Z == nil {
			log.Fatalf("Sum failed with no message returned")
		}
		fmt.Printf("Received %d\n\n", *out.Z)
	}
}
开发者ID:kylelemons,项目名称:go-rpcgen,代码行数:27,代码来源:client.go


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