-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
cli.go
71 lines (64 loc) · 1.5 KB
/
cli.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
package cmd
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"os"
"beryju.io/gravity/api"
"beryju.io/gravity/pkg/extconfig"
"github.com/spf13/cobra"
"go.uber.org/zap"
)
var (
apiUrl string
apiToken string
)
var (
apiClient *api.APIClient
logger *zap.Logger
)
var cliCmd = &cobra.Command{
Use: "cli",
Short: "Interact with a running Gravity server",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
url, err := url.Parse(apiUrl)
if err != nil {
logger.Error("failed to parse API URL", zap.Error(err))
return
}
config := api.NewConfiguration()
config.Host = url.Host
config.Scheme = url.Scheme
if url.Scheme == "unix" {
config.Scheme = "http"
config.Host = "socket"
config.HTTPClient = &http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", url.Path)
},
},
}
}
if apiToken != "" {
config.AddDefaultHeader("Authorization", fmt.Sprintf("Bearer %s", apiToken))
}
apiClient = api.NewAPIClient(config)
},
}
func init() {
defUrl := "unix:///var/run/gravity.sock"
if extconfig.Get().Debug {
cwd, err := os.Getwd()
if err != nil {
panic(err)
}
defUrl = fmt.Sprintf("unix://%s/gravity.sock", cwd)
}
logger = extconfig.Get().Logger().Named("cli")
cliCmd.PersistentFlags().StringVarP(&apiUrl, "host", "s", defUrl, "API Host")
cliCmd.PersistentFlags().StringVarP(&apiToken, "token", "t", "", "API Token")
rootCmd.AddCommand(cliCmd)
}