config.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package libbox
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "github.com/sagernet/sing-box"
  7. "github.com/sagernet/sing-box/option"
  8. E "github.com/sagernet/sing/common/exceptions"
  9. )
  10. func parseConfig(configContent string) (option.Options, error) {
  11. var options option.Options
  12. err := options.UnmarshalJSON([]byte(configContent))
  13. if err != nil {
  14. return option.Options{}, E.Cause(err, "decode config")
  15. }
  16. return options, nil
  17. }
  18. func CheckConfig(configContent string) error {
  19. options, err := parseConfig(configContent)
  20. if err != nil {
  21. return err
  22. }
  23. ctx, cancel := context.WithCancel(context.Background())
  24. defer cancel()
  25. instance, err := box.New(box.Options{
  26. Context: ctx,
  27. Options: options,
  28. })
  29. if err == nil {
  30. instance.Close()
  31. }
  32. return err
  33. }
  34. func FormatConfig(configContent string) (string, error) {
  35. options, err := parseConfig(configContent)
  36. if err != nil {
  37. return "", err
  38. }
  39. var buffer bytes.Buffer
  40. json.NewEncoder(&buffer)
  41. encoder := json.NewEncoder(&buffer)
  42. encoder.SetIndent("", " ")
  43. err = encoder.Encode(options)
  44. if err != nil {
  45. return "", err
  46. }
  47. return buffer.String(), nil
  48. }