本文整理汇总了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)
}
示例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)
}
})
}
}
示例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)
}
示例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)
}
}
}
示例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")
}
示例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")
}))
}
示例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
}
示例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)
}
}
示例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)
}
}
示例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()
}
示例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)
}
示例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)
}
}
示例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)
}
示例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)
}
示例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)
}
}