/
command.go
70 lines (58 loc) · 1.54 KB
/
command.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
package consul2ssh
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
)
const (
c2sNodesEndpoint = "/nodes"
)
type cmd struct {
flags *flag.FlagSet
confFile string
url string
}
func (c *cmd) init() {
c.flags = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
c.flags.StringVar(&c.confFile, "config-file",
"~/.consul2ssh/config.json", "Config file that will be used.")
c.flags.StringVar(&c.url, "url",
"http://localhost:8001", "API URL for consul2ssh.")
}
func readCMDArgs(args []string) *cmd {
c := &cmd{}
c.init()
c.flags.Parse(args)
return c
}
func readConfFile(file string) []byte {
filePath := getFilePath(file)
fileContent, err := ioutil.ReadFile(filePath)
checkErrCMD(err)
return fileContent
}
// GetNodesCMD - get nodes from API in SSH conf format.
func GetNodesCMD(args []string) {
// Read command line args.
cmdConf := readCMDArgs(args)
// Read consul2ssh conf file.
jsonPayload := readConfFile(cmdConf.confFile)
// Read consul2ssh URL from cmd arg or conf file.
var confData c2sConf
confData.get(bytes.NewReader(jsonPayload))
c2sNodesURL := setStrVal(cmdConf.url, confData.API.C2SURL) + c2sNodesEndpoint
// Read nodes from consul2ssh api.
req, err := http.NewRequest("GET", c2sNodesURL, bytes.NewBuffer(jsonPayload))
checkErrCMD(err)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
checkErrCMD(err)
defer resp.Body.Close()
respBody, _ := ioutil.ReadAll(resp.Body)
// Print final output to stdout.
fmt.Fprint(os.Stdout, string(respBody))
}