-
Notifications
You must be signed in to change notification settings - Fork 0
/
domainify.go
73 lines (63 loc) · 1.55 KB
/
domainify.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
73
package main
import (
"bufio"
"fmt"
"os"
"github.com/ProfoundNetworks/gpnutil"
"github.com/jessevdk/go-flags"
)
type Options struct {
Verbose []bool `short:"v" long:"verbose" description:"display verbose debug output"`
Stdin bool `short:"i" long:"stdin" description:"read from stdin instead of args"`
Args struct {
Hostnames []string `description:"hostnames to domainify"`
} `positional-args:"yes"`
}
func domainify(hostname string) {
domain, err := gpnutil.GetEntityDomain(hostname)
if err != nil {
fmt.Println("")
fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
} else {
fmt.Println(domain)
}
}
func runCLI(opts Options) error {
if opts.Stdin || len(opts.Args.Hostnames) == 0 {
if len(opts.Args.Hostnames) > 0 {
return fmt.Errorf("cannot specify hostnames with --stdin")
}
// Read from stdin
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
hostname := scanner.Text()
domainify(hostname)
}
} else {
// Read from opts.Args.Hostnames
for _, hostname := range opts.Args.Hostnames {
domainify(hostname)
}
}
return nil
}
func main() {
// Parse default options are HelpFlag | PrintErrors | PassDoubleDash
var opts Options
parser := flags.NewParser(&opts, flags.Default)
_, err := parser.Parse()
if err != nil {
if flags.WroteHelp(err) {
os.Exit(0)
}
// Does PrintErrors work? Is it not set?
fmt.Fprintf(os.Stderr, "Error: %s\n\n", err.Error())
parser.WriteHelp(os.Stderr)
os.Exit(2)
}
err = runCLI(opts)
if err != nil {
fmt.Fprintln(os.Stderr, "Error: "+err.Error())
os.Exit(2)
}
}