1
0
mirror of https://github.com/beego/bee.git synced 2024-11-14 22:10:55 +00:00
bee/parser/formatter.go

76 lines
1.8 KiB
Go
Raw Normal View History

2021-05-25 02:53:12 +00:00
package beeParser
2021-06-25 15:15:46 +00:00
import (
"encoding/json"
2021-05-25 02:53:12 +00:00
"github.com/talos-systems/talos/pkg/machinery/config/encoder"
2021-06-25 15:15:46 +00:00
)
type JsonFormatter struct {
}
func (f *JsonFormatter) FieldFormatFunc(field *StructField) ([]byte, error) {
annotation := NewAnnotation(field.Doc + field.Comment)
if annotation.Key == "" {
annotation.Key = field.Name
}
2021-06-25 15:15:46 +00:00
res := map[string]interface{}{}
if field.NestedType != nil {
res[annotation.Key] = field.NestedType
} else {
res[annotation.Key] = annotation.Default
}
return json.Marshal(res)
}
func (f *JsonFormatter) StructFormatFunc(node *StructNode) ([]byte, error) {
return json.Marshal(node.Fields)
}
func (f *JsonFormatter) Marshal(node *StructNode) ([]byte, error) {
return json.MarshalIndent(node, "", " ")
}
type YamlFormatter struct {
}
var result encoder.Doc
2021-06-25 15:15:46 +00:00
type Result map[string]interface{}
2021-06-25 15:15:46 +00:00
func (c Result) Doc() *encoder.Doc {
return &result
2021-06-25 15:15:46 +00:00
}
func (f *YamlFormatter) FieldFormatFunc(field *StructField) ([]byte, error) {
2021-06-25 15:15:46 +00:00
annotation := NewAnnotation(field.Doc + field.Comment)
if annotation.Key == "" {
annotation.Key = field.Name
}
res := Result{}
// add head comment for this field
res.Doc().Comments[encoder.HeadComment] = annotation.Description
2021-06-25 15:15:46 +00:00
if field.NestedType != nil {
b, _ := field.NestedType.FormatFunc(field.NestedType)
res[annotation.Key] = string(b)
2021-06-25 15:15:46 +00:00
} else {
res[annotation.Key] = annotation.Default
2021-06-25 15:15:46 +00:00
}
encoder := encoder.NewEncoder(&res, []encoder.Option{
encoder.WithComments(encoder.CommentsAll),
}...)
return encoder.Encode()
2021-05-25 02:53:12 +00:00
}
func (f *YamlFormatter) StructFormatFunc(node *StructNode) ([]byte, error) {
2021-06-25 15:15:46 +00:00
res := make([]byte, 0)
for _, f := range node.Fields {
b, _ := f.FormatFunc(f)
res = append(res, b...)
2021-05-25 02:53:12 +00:00
}
2021-06-25 15:15:46 +00:00
return res, nil
2021-05-25 02:53:12 +00:00
}
func (f *YamlFormatter) Marshal(node *StructNode) ([]byte, error) {
2021-06-25 15:15:46 +00:00
return node.FormatFunc(node)
2021-05-25 02:53:12 +00:00
}