config.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. type ConfigCommand struct{}
  14. func (c *ConfigCommand) Name() string {
  15. return "config"
  16. }
  17. func (c *ConfigCommand) Description() Description {
  18. return Description{
  19. Short: "merge multiple json config",
  20. Usage: []string{"v2ctl config config.json c1.json c2.json <url>.json"},
  21. }
  22. }
  23. func (c *ConfigCommand) Execute(args []string) error {
  24. if len(args) < 1 {
  25. return newError("empty config list")
  26. }
  27. conf := &conf.Config{}
  28. for _, arg := range args {
  29. newError("Reading config: ", arg).AtInfo().WriteToLog()
  30. r, err := c.LoadArg(arg)
  31. common.Must(err)
  32. c, err := serial.DecodeJSONConfig(r)
  33. common.Must(err)
  34. conf.Override(c, arg)
  35. }
  36. pbConfig, err := conf.Build()
  37. if err != nil {
  38. return err
  39. }
  40. bytesConfig, err := proto.Marshal(pbConfig)
  41. if err != nil {
  42. return newError("failed to marshal proto config").Base(err)
  43. }
  44. if _, err := os.Stdout.Write(bytesConfig); err != nil {
  45. return newError("failed to write proto config").Base(err)
  46. }
  47. return nil
  48. }
  49. func (c *ConfigCommand) LoadArg(arg string) (out io.Reader, err error) {
  50. var data []byte
  51. if strings.HasPrefix(arg, "http://") || strings.HasPrefix(arg, "https://") {
  52. data, err = FetchHTTPContent(arg)
  53. } else if arg == "stdin:" {
  54. data, err = ioutil.ReadAll(os.Stdin)
  55. } else {
  56. data, err = ioutil.ReadFile(arg)
  57. }
  58. if err != nil {
  59. return
  60. }
  61. out = bytes.NewBuffer(data)
  62. return
  63. }
  64. func init() {
  65. common.Must(RegisterCommand(&ConfigCommand{}))
  66. }