mirror of
https://github.com/astaxie/beego.git
synced 2024-11-22 14:40:57 +00:00
Added ToString method which converts values of any type to string
This commit is contained in:
parent
24015e9ace
commit
5bc3e30653
@ -43,6 +43,8 @@ package config
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
"reflect"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Configer defines how to get and set value from configuration raw data.
|
// Configer defines how to get and set value from configuration raw data.
|
||||||
@ -204,3 +206,37 @@ func ParseBool(val interface{}) (value bool, err error) {
|
|||||||
}
|
}
|
||||||
return false, fmt.Errorf("parsing <nil>: invalid syntax")
|
return false, fmt.Errorf("parsing <nil>: invalid syntax")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ToString converts values of any type to string.
|
||||||
|
func ToString(x interface{}) string {
|
||||||
|
switch y := x.(type) {
|
||||||
|
|
||||||
|
// Handle dates with special logic
|
||||||
|
// This needs to come above the fmt.Stringer
|
||||||
|
// test since time.Time's have a .String()
|
||||||
|
// method
|
||||||
|
case time.Time:
|
||||||
|
return y.Format("A Monday")
|
||||||
|
|
||||||
|
// Handle type string
|
||||||
|
case string:
|
||||||
|
return y
|
||||||
|
|
||||||
|
// Handle type with .String() method
|
||||||
|
case fmt.Stringer:
|
||||||
|
return y.String()
|
||||||
|
|
||||||
|
// Handle type with .Error() method
|
||||||
|
case error:
|
||||||
|
return y.Error()
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle named string type
|
||||||
|
if v := reflect.ValueOf(x); v.Kind() == reflect.String {
|
||||||
|
return v.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback to fmt package for anything else like numeric types
|
||||||
|
return fmt.Sprint(x)
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user