1
0
mirror of https://github.com/beego/bee.git synced 2024-11-15 03:20:54 +00:00
bee/parser/annotator.go

95 lines
2.2 KiB
Go
Raw Normal View History

2021-05-23 12:16:20 +00:00
package beeParser
import (
2021-06-25 15:15:46 +00:00
"fmt"
"strconv"
2021-05-23 12:16:20 +00:00
"strings"
)
type Annotator interface {
2021-05-25 02:53:12 +00:00
Annotate(string) map[string]interface{}
}
type Annotation struct {
2021-06-25 15:15:46 +00:00
Key, Description string
Default interface{}
}
2021-05-23 12:16:20 +00:00
func isWhitespace(ch byte) bool { return ch == ' ' || ch == '\t' || ch == '\r' }
func handleHeadWhitespace(s string) string {
i := 0
for i < len(s) && isWhitespace(s[i]) {
i++
}
return s[i:]
}
func handleTailWhitespace(s string) string {
i := len(s)
for i > 0 && isWhitespace(s[i-1]) {
i--
}
return s[0:i]
}
//handle value to remove head and tail space.
2021-06-25 15:15:46 +00:00
func handleWhitespaceValues(values []string) []interface{} {
res := make([]interface{}, 0)
2021-05-23 12:16:20 +00:00
for _, v := range values {
v = handleHeadWhitespace(v)
v = handleTailWhitespace(v)
2021-06-25 15:15:46 +00:00
res = append(res, transferType(v))
2021-05-23 12:16:20 +00:00
}
return res
}
2021-06-25 15:15:46 +00:00
//try to transfer string to original type
func transferType(str string) interface{} {
if res, err := strconv.Atoi(str); err == nil {
return res
}
if res, err := strconv.ParseBool(str); err == nil {
return res
}
return str
}
2021-05-23 12:16:20 +00:00
//parse annotation to generate array with key and values
//start with "@" as a key-value pair,key and values are separated by a space,wrap to distinguish values.
2021-05-25 02:53:12 +00:00
func (a *Annotation) Annotate(annotation string) map[string]interface{} {
results := make(map[string]interface{})
2021-05-23 12:16:20 +00:00
//split annotation with '@'
2021-05-25 02:53:12 +00:00
lines := strings.Split(annotation, "@")
2021-05-23 12:16:20 +00:00
//skip first line whitespace
for _, line := range lines[1:] {
kvs := strings.Split(line, " ")
key := kvs[0]
values := strings.Split(strings.TrimSpace(line[len(kvs[0]):]), "\n")
2021-06-25 15:15:46 +00:00
if len(values) == 1 {
results[key] = handleWhitespaceValues(values)[0]
} else {
results[key] = handleWhitespaceValues(values)
}
2021-05-23 12:16:20 +00:00
}
return results
}
2021-06-25 15:15:46 +00:00
//create new annotation
//parse "Key","Default","Description" by annotation
//the type of "Key" and "Description" is string, "Default" is interface{}
2021-06-25 15:15:46 +00:00
func NewAnnotation(annotation string) *Annotation {
a := &Annotation{}
kvs := a.Annotate(annotation)
if v, ok := kvs["Key"]; ok {
a.Key = fmt.Sprintf("%v", v)
}
if v, ok := kvs["Description"]; ok {
a.Description = fmt.Sprintf("%v", v)
}
if v, ok := kvs["Default"]; ok {
a.Default = v
}
return a
}