config.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package control
  2. import (
  3. "bytes"
  4. "io"
  5. "io/ioutil"
  6. "os"
  7. "strings"
  8. "github.com/golang/protobuf/proto"
  9. "v2ray.com/core/common"
  10. "v2ray.com/core/infra/conf"
  11. "v2ray.com/core/infra/conf/serial"
  12. )
  13. // ConfigCommand is the json to pb convert struct
  14. type ConfigCommand struct{}
  15. // Name for cmd usage
  16. func (c *ConfigCommand) Name() string {
  17. return "config"
  18. }
  19. // Description for help usage
  20. func (c *ConfigCommand) Description() Description {
  21. return Description{
  22. Short: "merge multiple json config",
  23. Usage: []string{"v2ctl config config.json c1.json c2.json <url>.json"},
  24. }
  25. }
  26. // Execute real work here.
  27. func (c *ConfigCommand) Execute(args []string) error {
  28. if len(args) < 1 {
  29. return newError("empty config list")
  30. }
  31. conf := &conf.Config{}
  32. for _, arg := range args {
  33. newError("Reading config: ", arg).AtInfo().WriteToLog()
  34. r, err := c.LoadArg(arg)
  35. common.Must(err)
  36. c, err := serial.DecodeJSONConfig(r)
  37. common.Must(err)
  38. conf.Override(c, arg)
  39. }
  40. pbConfig, err := conf.Build()
  41. if err != nil {
  42. return err
  43. }
  44. bytesConfig, err := proto.Marshal(pbConfig)
  45. if err != nil {
  46. return newError("failed to marshal proto config").Base(err)
  47. }
  48. if _, err := os.Stdout.Write(bytesConfig); err != nil {
  49. return newError("failed to write proto config").Base(err)
  50. }
  51. return nil
  52. }
  53. // LoadArg loads one arg, maybe an remote url, or local file path
  54. func (c *ConfigCommand) LoadArg(arg string) (out io.Reader, err error) {
  55. var data []byte
  56. if strings.HasPrefix(arg, "http://") || strings.HasPrefix(arg, "https://") {
  57. data, err = FetchHTTPContent(arg)
  58. } else if arg == "stdin:" {
  59. data, err = ioutil.ReadAll(os.Stdin)
  60. } else {
  61. data, err = ioutil.ReadFile(arg)
  62. }
  63. if err != nil {
  64. return
  65. }
  66. out = bytes.NewBuffer(data)
  67. return
  68. }
  69. func init() {
  70. common.Must(RegisterCommand(&ConfigCommand{}))
  71. }