github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/codec/jsoni.go (about)

     1  package codec
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  
     9  	"github.com/bingoohuang/gg/pkg/jsoni"
    10  )
    11  
    12  func Json(v interface{}) []byte {
    13  	vv, _ := jsoni.Marshal(v)
    14  	return vv
    15  }
    16  
    17  func Jsonify(v interface{}) ([]byte, error) {
    18  	return jsoni.Marshal(v)
    19  }
    20  
    21  func ParseJson(data []byte, v interface{}) error {
    22  	return jsoni.Unmarshal(data, v)
    23  }
    24  
    25  func EncodeJson(w io.Writer, v interface{}) error {
    26  	return jsoni.NewEncoder(w).Encode(context.Background(), v)
    27  }
    28  
    29  func DecodeJson(r io.Reader, obj interface{}) error {
    30  	return jsoni.NewDecoder(r).Decode(context.Background(), obj)
    31  }
    32  
    33  func ReadJsonFile(obj interface{}, file string) error {
    34  	// 读取配置文件
    35  	configFile, err := os.ReadFile(file)
    36  	if err != nil {
    37  		return fmt.Errorf("read config file %s failed: %w", file, err)
    38  	}
    39  
    40  	// 反序列化到结构体中
    41  	if err := jsoni.Unmarshal(configFile, obj); err != nil {
    42  		return fmt.Errorf("unmarshal file data failed: %w", err)
    43  	}
    44  
    45  	return nil
    46  }
    47  
    48  func WriteJsonFile(obj interface{}, indent, file string) error {
    49  	data, err := jsoni.MarshalIndent(obj, "", indent)
    50  	if err != nil {
    51  		return fmt.Errorf("MarshalIndent failed: %w", err)
    52  	}
    53  
    54  	if err := os.WriteFile(file, data, os.ModePerm); err != nil {
    55  		return fmt.Errorf("writing config file %s failed: %w", file, err)
    56  	}
    57  
    58  	return nil
    59  }