类型转换包完善

This commit is contained in:
John
2018-01-03 10:23:37 +08:00
parent 7279eb7687
commit 0092365481
3 changed files with 37 additions and 8 deletions

View File

@ -24,9 +24,9 @@ type Controller struct {
// 控制器初始化接口方法
func (c *Controller) Init(r *ghttp.Request) {
c.Server = r.Server
c.Request = r
c.Response = r.Response
c.Server = r.Server
c.View = NewView(r.Response)
c.Cookie = r.Cookie
c.Session = r.Session

View File

@ -22,13 +22,13 @@ type Request struct {
Server *Server // 请求关联的服务器对象
Cookie *Cookie // 与当前请求绑定的Cookie对象(并发安全)
Session *Session // 与当前请求绑定的Session对象(并发安全)
Response *Response // 对应请求的返回数据操作对象
Response *Response // 对应请求的返回数据操作对象
}
// 获得指定名称的get参数列表
func (r *Request) GetQuery(k string) []string {
if r.getvals == nil {
values := r.URL.Query()
values := r.URL.Query()
r.getvals = &values
}
if v, ok := (*r.getvals)[k]; ok {

View File

@ -4,7 +4,9 @@
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://gitee.com/johng/gf.
// 数据基本类型强制转换
// 数据基本类型转换
// 如果给定的interface{}参数不是指定转换的输出类型,那么会进行强制转换,效率会比较低,
// 建议已知类型的转换自行调用相关方法来单独处理。
package gconv
import (
@ -12,6 +14,17 @@ import (
"strconv"
)
func Bytes(i interface{}) []byte {
if i == nil {
return nil
}
if r, ok := i.([]byte); ok {
return r
} else {
return []byte(String(i))
}
}
func String(i interface{}) string {
if i == nil {
return ""
@ -23,6 +36,22 @@ func String(i interface{}) string {
}
}
func Strings(i interface{}) []string {
if i == nil {
return nil
}
if r, ok := i.([]string); ok {
return r
} else if r, ok := i.([]interface{}); ok {
strs := make([]string, len(r))
for k, v := range r {
strs[k] = String(v)
}
return strs
}
return []string{fmt.Sprintf("%v", i)}
}
//false: "", 0, false, off
func Bool(i interface{}) bool {
if i == nil {
@ -44,7 +73,7 @@ func Int(i interface{}) int {
if v, ok := i.(int); ok {
return v
}
v, _ := strconv.Atoi(fmt.Sprintf("%v", i))
v, _ := strconv.Atoi(String(i))
return v
}
@ -55,7 +84,7 @@ func Uint (i interface{}) uint {
if v, ok := i.(uint); ok {
return v
}
v, _ := strconv.ParseUint(fmt.Sprintf("%v", i), 10, 8)
v, _ := strconv.ParseUint(String(i), 10, 8)
return uint(v)
}
@ -66,7 +95,7 @@ func Float32 (i interface{}) float32 {
if v, ok := i.(float32); ok {
return v
}
v, _ := strconv.ParseFloat(fmt.Sprintf("%v", i), 8)
v, _ := strconv.ParseFloat(String(i), 8)
return float32(v)
}
@ -77,6 +106,6 @@ func Float64 (i interface{}) float64 {
if v, ok := i.(float64); ok {
return v
}
v, _ := strconv.ParseFloat(fmt.Sprintf("%v", i), 8)
v, _ := strconv.ParseFloat(String(i), 8)
return v
}