forked from golang/example
-
Notifications
You must be signed in to change notification settings - Fork 1
/
hello.go
72 lines (63 loc) · 1.39 KB
/
hello.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Hello is a hello, world program, demonstrating
// how to write a simple command-line program.
//
// Usage:
//
// hello [options] [name]
//
// The options are:
//
// -g greeting
// Greet with the given greeting, instead of "Hello".
//
// -r
// Greet in reverse.
//
// By default, hello greets the world.
// If a name is specified, hello greets that name instead.
package main
import (
"flag"
"fmt"
"log"
"os"
"golang.org/x/example/hello/reverse"
)
func usage() {
fmt.Fprintf(os.Stderr, "usage: hello [options] [name]\n")
flag.PrintDefaults()
os.Exit(2)
}
var (
greeting = flag.String("g", "Hello", "Greet with `greeting`")
reverseFlag = flag.Bool("r", false, "Greet in reverse")
)
func main() {
// Configure logging for a command-line program.
log.SetFlags(0)
log.SetPrefix("hello: ")
// Parse flags.
flag.Usage = usage
flag.Parse()
// Parse and validate arguments.
name := "world"
args := flag.Args()
if len(args) >= 2 {
usage()
}
if len(args) >= 1 {
name = args[0]
}
if name == "" { // hello '' is an error
log.Fatalf("invalid name %q", name)
}
// Run actual logic.
if *reverseFlag {
fmt.Printf("%s, %s!\n", reverse.String(*greeting), reverse.String(name))
return
}
fmt.Printf("%s, %s!\n", *greeting, name)
}