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

98 lines
2.4 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"
"encoding/xml"
2021-05-25 02:53:12 +00:00
2021-06-25 15:15:46 +00:00
"gopkg.in/yaml.v2"
)
type JsonFormatter struct {
}
func (f *JsonFormatter) FieldFormatFunc(field *StructField) ([]byte, error) {
annotation := NewAnnotation(field.Doc + field.Comment)
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 {
}
func (f *YamlFormatter) FieldFormatFunc(field *StructField) ([]byte, error) {
annotation := NewAnnotation(field.Doc + field.Comment)
res := map[string]interface{}{}
if field.NestedType != nil {
res[annotation.Key] = field.NestedType
} else {
res[annotation.Key] = annotation.Default
}
return yaml.Marshal(res)
}
func (f *YamlFormatter) StructFormatFunc(node *StructNode) ([]byte, error) {
return yaml.Marshal(node.Fields)
}
func (f *YamlFormatter) Marshal(node *StructNode) ([]byte, error) {
return yaml.Marshal(node)
}
type XmlFormatter struct {
}
func (f *XmlFormatter) FieldFormatFunc(field *StructField) ([]byte, error) {
annotation := NewAnnotation(field.Doc + field.Comment)
if field.NestedType != nil {
type xmlStruct struct {
XMLName xml.Name
Default interface{} `xml:",innerxml"`
Description string `xml:",comment"`
}
b, _ := field.NestedType.FormatFunc(field.NestedType)
return xml.Marshal(&xmlStruct{
XMLName: xml.Name{Local: annotation.Key},
Description: annotation.Description,
Default: b,
})
} else {
type xmlStruct struct {
XMLName xml.Name
Default interface{} `xml:",chardata"`
Description string `xml:",comment"`
}
return xml.Marshal(&xmlStruct{
XMLName: xml.Name{Local: annotation.Key},
Description: annotation.Description,
Default: annotation.Default,
})
}
2021-05-25 02:53:12 +00:00
}
2021-06-25 15:15:46 +00:00
func (f *XmlFormatter) StructFormatFunc(node *StructNode) ([]byte, error) {
res := make([]byte, 0)
for _, f := range node.Fields {
b, _ := f.FormatFunc(f)
res = append(res, b...)
res = append(res, '\n')
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
}
2021-06-25 15:15:46 +00:00
func (f *XmlFormatter) Marshal(node *StructNode) ([]byte, error) {
return node.FormatFunc(node)
2021-05-25 02:53:12 +00:00
}