add buildin function yamli for package gview

This commit is contained in:
John Guo
2022-01-17 17:10:44 +08:00
parent c72a9f2e1e
commit 56f88f759a
6 changed files with 62 additions and 2 deletions

View File

@ -120,6 +120,12 @@ func (j *Json) ToYaml() ([]byte, error) {
return gyaml.Encode(*(j.p))
}
func (j *Json) ToYamlIndent(indent string) ([]byte, error) {
j.mu.RLock()
defer j.mu.RUnlock()
return gyaml.EncodeIndent(*(j.p), indent)
}
func (j *Json) ToYamlString() (string, error) {
b, e := j.ToYaml()
return string(b), e
@ -170,8 +176,6 @@ func (j *Json) MustToTomlString() string {
// ToIni json to ini
func (j *Json) ToIni() ([]byte, error) {
j.mu.RLock()
defer j.mu.RUnlock()
return gini.Encode(j.Map())
}

View File

@ -8,6 +8,9 @@
package gyaml
import (
"bytes"
"strings"
"gopkg.in/yaml.v3"
"github.com/gogf/gf/v2/errors/gerror"
@ -22,6 +25,26 @@ func Encode(value interface{}) (out []byte, err error) {
return
}
func EncodeIndent(value interface{}, indent string) (out []byte, err error) {
out, err = Encode(value)
if err != nil {
return
}
if indent != "" {
var (
buffer = bytes.NewBuffer(nil)
array = strings.Split(strings.TrimSpace(string(out)), "\n")
)
for _, v := range array {
buffer.WriteString(indent)
buffer.WriteString(v)
buffer.WriteString("\n")
}
out = buffer.Bytes()
}
return
}
func Decode(value []byte) (interface{}, error) {
var (
result map[string]interface{}

View File

@ -59,6 +59,18 @@ func Test_Encode(t *testing.T) {
})
}
func Test_EncodeIndent(t *testing.T) {
// Array.
gtest.C(t, func(t *gtest.T) {
b, err := gyaml.EncodeIndent([]string{"a", "b", "c"}, "####")
t.AssertNil(err)
t.Assert(string(b), `####- a
####- b
####- c
`)
})
}
func Test_Decode(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
result, err := gyaml.Decode([]byte(yamlStr))