config.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. ctllog.Println("Read config: ", arg)
  34. r, err := c.LoadArg(arg)
  35. common.Must(err)
  36. c, err := serial.DecodeJSONConfig(r)
  37. if err != nil {
  38. ctllog.Fatalln(err)
  39. }
  40. conf.Override(c, arg)
  41. }
  42. pbConfig, err := conf.Build()
  43. if err != nil {
  44. return err
  45. }
  46. bytesConfig, err := proto.Marshal(pbConfig)
  47. if err != nil {
  48. return newError("failed to marshal proto config").Base(err)
  49. }
  50. if _, err := os.Stdout.Write(bytesConfig); err != nil {
  51. return newError("failed to write proto config").Base(err)
  52. }
  53. return nil
  54. }
  55. // LoadArg loads one arg, maybe an remote url, or local file path
  56. func (c *ConfigCommand) LoadArg(arg string) (out io.Reader, err error) {
  57. var data []byte
  58. if strings.HasPrefix(arg, "http://") || strings.HasPrefix(arg, "https://") {
  59. data, err = FetchHTTPContent(arg)
  60. } else if arg == "stdin:" {
  61. data, err = ioutil.ReadAll(os.Stdin)
  62. } else {
  63. data, err = ioutil.ReadFile(arg)
  64. }
  65. if err != nil {
  66. return
  67. }
  68. out = bytes.NewBuffer(data)
  69. return
  70. }
  71. func init() {
  72. common.Must(RegisterCommand(&ConfigCommand{}))
  73. }