github.com/inazumav/sing-box@v0.0.0-20230926072359-ab51429a14f1/experimental/libbox/config.go (about)

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