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

68 lines
1.3 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"
"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
}
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 {
return strconv.ParseFloat(value, 32)
}
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
}