1
2
3 package main
4
5 import (
6 "encoding/json"
7 "fmt"
8 "os"
9 "path/filepath"
10
11 "github.com/pkg/errors"
12 "github.com/urfave/cli"
13 )
14
15 var configCommand = cli.Command{
16 Name: "config",
17 Usage: "Information on the ncproxy config",
18 Subcommands: []cli.Command{
19 {
20 Name: "default",
21 Usage: "Print the output of the default config to stdout or to a file",
22 Flags: []cli.Flag{
23 cli.StringFlag{
24 Name: "file",
25 Usage: "Output config to a file",
26 },
27 },
28 Action: func(context *cli.Context) error {
29 file := context.String("file")
30
31 configData, err := json.MarshalIndent(defaultConfig(), "", " ")
32 if err != nil {
33 return errors.Wrap(err, "failed to marshal ncproxy config to json")
34 }
35
36 if file != "" {
37
38 if _, err := os.Stat(filepath.Dir(file)); err != nil {
39 if err := os.MkdirAll(filepath.Dir(file), 0700); err != nil {
40 return errors.Wrap(err, "failed to make path to config file")
41 }
42 }
43 if err := os.WriteFile(
44 file,
45 []byte(configData),
46 0700,
47 ); err != nil {
48 return err
49 }
50 } else {
51 fmt.Fprint(os.Stdout, string(configData))
52 }
53
54 return nil
55 },
56 },
57 },
58 }
59
60
61 func defaultConfig() *config {
62 return &config{
63 TTRPCAddr: "\\\\.\\pipe\\ncproxy-ttrpc",
64 GRPCAddr: "127.0.0.1:6669",
65 NodeNetSvcAddr: "127.0.0.1:6668",
66 Timeout: 10,
67 }
68 }
69
70 type config struct {
71 TTRPCAddr string `json:"ttrpc,omitempty"`
72 GRPCAddr string `json:"grpc,omitempty"`
73 NodeNetSvcAddr string `json:"node_net_svc_addr,omitempty"`
74
75
76
77 Timeout uint32 `json:"timeout,omitempty"`
78 }
79
80
81
82 func loadConfig(path string) (*config, error) {
83
84 if path != "" {
85 return readConfig(path)
86 }
87
88 if path, exists := configPresent(); exists {
89 return readConfig(path)
90 }
91 return nil, errors.New("no config specified and no config found in current directory. Run `ncproxy config default` to generate a default config")
92 }
93
94
95
96 func readConfig(path string) (*config, error) {
97 data, err := os.ReadFile(path)
98 if err != nil {
99 return nil, errors.Wrap(err, "failed to read config file")
100 }
101 conf := &config{}
102 if err := json.Unmarshal(data, conf); err != nil {
103 return nil, errors.New("failed to unmarshal config data")
104 }
105 return conf, nil
106 }
107
108
109 func configPresent() (string, bool) {
110 path := filepath.Join(filepath.Dir(os.Args[0]), "ncproxy.json")
111 if _, err := os.Stat(path); os.IsNotExist(err) {
112 return "", false
113 }
114 return path, true
115 }
116
View as plain text