github.com/gogf/gf/v2@v2.7.4/encoding/gtoml/gtoml.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  // Package gtoml provides accessing and converting for TOML content.
     8  package gtoml
     9  
    10  import (
    11  	"bytes"
    12  
    13  	"github.com/BurntSushi/toml"
    14  
    15  	"github.com/gogf/gf/v2/errors/gerror"
    16  	"github.com/gogf/gf/v2/internal/json"
    17  )
    18  
    19  func Encode(v interface{}) ([]byte, error) {
    20  	buffer := bytes.NewBuffer(nil)
    21  	if err := toml.NewEncoder(buffer).Encode(v); err != nil {
    22  		err = gerror.Wrap(err, `toml.Encoder.Encode failed`)
    23  		return nil, err
    24  	}
    25  	return buffer.Bytes(), nil
    26  }
    27  
    28  func Decode(v []byte) (interface{}, error) {
    29  	var result interface{}
    30  	if err := toml.Unmarshal(v, &result); err != nil {
    31  		err = gerror.Wrap(err, `toml.Unmarshal failed`)
    32  		return nil, err
    33  	}
    34  	return result, nil
    35  }
    36  
    37  func DecodeTo(v []byte, result interface{}) (err error) {
    38  	err = toml.Unmarshal(v, result)
    39  	if err != nil {
    40  		err = gerror.Wrap(err, `toml.Unmarshal failed`)
    41  	}
    42  	return err
    43  }
    44  
    45  func ToJson(v []byte) ([]byte, error) {
    46  	if r, err := Decode(v); err != nil {
    47  		return nil, err
    48  	} else {
    49  		return json.Marshal(r)
    50  	}
    51  }