1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-29 13:11:29 +00:00
Beego/param/parsers.go

95 lines
2.1 KiB
Go
Raw Normal View History

2017-04-21 12:26:41 +00:00
package param
2017-04-22 22:33:50 +00:00
import (
"encoding/json"
"reflect"
"strconv"
2017-04-23 18:37:09 +00:00
"strings"
2017-04-22 22:33:50 +00:00
"time"
)
2017-04-21 12:26:41 +00:00
type paramParser interface {
2017-04-22 22:33:50 +00:00
parse(value string, toType reflect.Type) (interface{}, error)
2017-04-21 12:26:41 +00:00
}
2017-04-23 18:37:09 +00:00
type parserFunc func(value string, toType reflect.Type) (interface{}, error)
func (f parserFunc) parse(value string, toType reflect.Type) (interface{}, error) {
return f(value, toType)
}
2017-04-21 12:26:41 +00:00
type boolParser struct {
}
2017-04-22 22:33:50 +00:00
func (p boolParser) parse(value string, toType reflect.Type) (interface{}, error) {
2017-04-21 12:26:41 +00:00
return strconv.ParseBool(value)
}
type stringParser struct {
}
2017-04-22 22:33:50 +00:00
func (p stringParser) parse(value string, toType reflect.Type) (interface{}, error) {
2017-04-21 12:26:41 +00:00
return value, nil
}
type intParser struct {
}
2017-04-22 22:33:50 +00:00
func (p intParser) parse(value string, toType reflect.Type) (interface{}, error) {
2017-04-21 12:26:41 +00:00
return strconv.Atoi(value)
}
2017-04-22 22:33:50 +00:00
type floatParser struct {
}
func (p floatParser) parse(value string, toType reflect.Type) (interface{}, error) {
if toType.Kind() == reflect.Float32 {
2017-04-23 18:37:09 +00:00
res, err := strconv.ParseFloat(value, 32)
if err != nil {
return nil, err
}
return float32(res), nil
2017-04-22 22:33:50 +00:00
}
return strconv.ParseFloat(value, 64)
}
type timeParser struct {
}
func (p timeParser) parse(value string, toType reflect.Type) (result interface{}, err error) {
result, err = time.Parse(time.RFC3339, value)
if err != nil {
result, err = time.Parse("2006-01-02", value)
}
return
}
type jsonParser struct {
}
func (p jsonParser) parse(value string, toType reflect.Type) (interface{}, error) {
pResult := reflect.New(toType)
v := pResult.Interface()
err := json.Unmarshal([]byte(value), v)
if err != nil {
return nil, err
}
return pResult.Elem().Interface(), nil
2017-04-21 12:26:41 +00:00
}
2017-04-23 18:37:09 +00:00
func sliceParser(elemParser paramParser) paramParser {
return parserFunc(func(value string, toType reflect.Type) (interface{}, error) {
values := strings.Split(value, ",")
result := reflect.MakeSlice(toType, 0, len(values))
elemType := toType.Elem()
for _, v := range values {
parsedValue, err := elemParser.parse(v, elemType)
if err != nil {
return nil, err
}
result = reflect.Append(result, reflect.ValueOf(parsedValue))
}
return result.Interface(), nil
})
}