config.go 1.5 KB

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