json.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package json
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  7. "github.com/v2ray/v2ray-core"
  8. "github.com/v2ray/v2ray-core/common/log"
  9. )
  10. type ConnectionConfig struct {
  11. ProtocolString string `json:"protocol"`
  12. File string `json:"file"`
  13. }
  14. func (config *ConnectionConfig) Protocol() string {
  15. return config.ProtocolString
  16. }
  17. func (config *ConnectionConfig) Content() []byte {
  18. if len(config.File) == 0 {
  19. return nil
  20. }
  21. content, err := ioutil.ReadFile(config.File)
  22. if err != nil {
  23. panic(log.Error("Failed to read config file (%s): %v", config.File, err))
  24. }
  25. return content
  26. }
  27. // Config is the config for Point server.
  28. type Config struct {
  29. PortValue uint16 `json:"port"` // Port of this Point server.
  30. InboundConfigValue *ConnectionConfig `json:"inbound"`
  31. OutboundConfigValue *ConnectionConfig `json:"outbound"`
  32. }
  33. func (config *Config) Port() uint16 {
  34. return config.PortValue
  35. }
  36. func (config *Config) InboundConfig() core.ConnectionConfig {
  37. return config.InboundConfigValue
  38. }
  39. func (config *Config) OutboundConfig() core.ConnectionConfig {
  40. return config.OutboundConfigValue
  41. }
  42. func LoadConfig(file string) (*Config, error) {
  43. fixedFile := os.ExpandEnv(file)
  44. rawConfig, err := ioutil.ReadFile(fixedFile)
  45. if err != nil {
  46. log.Error("Failed to read point config file (%s): %v", file, err)
  47. return nil, err
  48. }
  49. config := &Config{}
  50. err = json.Unmarshal(rawConfig, config)
  51. if err != nil {
  52. log.Error("Failed to load point config: %v", err)
  53. return nil, err
  54. }
  55. if !filepath.IsAbs(config.InboundConfigValue.File) && len(config.InboundConfigValue.File) > 0 {
  56. config.InboundConfigValue.File = filepath.Join(filepath.Dir(fixedFile), config.InboundConfigValue.File)
  57. }
  58. if !filepath.IsAbs(config.OutboundConfigValue.File) && len(config.OutboundConfigValue.File) > 0 {
  59. config.OutboundConfigValue.File = filepath.Join(filepath.Dir(fixedFile), config.OutboundConfigValue.File)
  60. }
  61. return config, err
  62. }