GoFrame g.* 方法和数据类型
GoFrame 框架通过 g.*
方法提供了一系列常用的数据类型和对象获取方法。这个模块采用强耦合设计,目的是为开发者提供便捷的类型和对象调用方式。
使用方式
import "github.com/gogf/gf/v2/frame/g"
数据类型
基础类型别名
type (
Var = gvar.Var // 通用变量接口,类似泛型
Ctx = context.Context // context.Context 的别名
)
Map 类型别名
type (
Map = map[string]interface{} // 常用的 string-interface{} 映射
MapAnyAny = map[interface{}]interface{} // 任意类型键值对映射
MapAnyStr = map[interface{}]string // interface{}-string 映射
MapAnyInt = map[interface{}]int // interface{}-int 映射
MapStrAny = map[string]interface{} // string-interface{} 映射
MapStrStr = map[string]string // string-string 映射
MapStrInt = map[string]int // string-int 映射
MapIntAny = map[int]interface{} // int-interface{} 映射
MapIntStr = map[int]string // int-string 映射
MapIntInt = map[int]int // int-int 映射
MapAnyBool = map[interface{}]bool // interface{}-bool 映射
MapStrBool = map[string]bool // string-bool 映射
MapIntBool = map[int]bool // int-bool 映射
)
List 类型别名
type (
List = []Map // Map 切片
ListAnyAny = []MapAnyAny // MapAnyAny 切片
ListAnyStr = []MapAnyStr // MapAnyStr 切片
ListAnyInt = []MapAnyInt // MapAnyInt 切片
ListStrAny = []MapStrAny // MapStrAny 切片
ListStrStr = []MapStrStr // MapStrStr 切片
ListStrInt = []MapStrInt // MapStrInt 切片
ListIntAny = []MapIntAny // MapIntAny 切片
ListIntStr = []MapIntStr // MapIntStr 切片
ListIntInt = []MapIntInt // MapIntInt 切片
ListAnyBool = []MapAnyBool // MapAnyBool 切片
ListStrBool = []MapStrBool // MapStrBool 切片
ListIntBool = []MapIntBool // MapIntBool 切片
)
Slice/Array 类型别名
type (
Slice = []interface{} // interface{} 切片
SliceAny = []interface{} // interface{} 切片
SliceStr = []string // string 切片
SliceInt = []int // int 切片
Array = []interface{} // interface{} 数组
ArrayAny = []interface{} // interface{} 数组
ArrayStr = []string // string 数组
ArrayInt = []int // int 数组
)
常用对象获取方法
所有对象都采用单例模式管理,可以通过不同的单例名称获取对应的对象实例。对象初始化时会自动检索配置文件中的对应配置项。
注意:运行时每次通过
g
模块获取单例对象时都有内部全局锁机制保证并发安全。在高并发场景下可能存在锁竞争,建议将获取的单例对象保存到模块内部变量重复使用。
HTTP 相关
func Client() *ghttp.Client // 创建 HTTP 客户端对象
func Server(name ...interface{}) *ghttp.Server // 获取 Web Server 单例对象
数据校验
func Validator() *gvalid.Validator // 创建数据校验对象
配置管理
func Cfg(name ...string) *gcfg.Config // 获取配置管理对象
支持自动检索的配置文件格式:
- config.toml
- config.yaml/yml
- config.json
- config.ini
- config.xml
- config.properties
数据库和缓存
func DB(name ...string) *gdb.Db // 获取数据库 ORM 对象
func Model(tables string, db ...string) *gdb.Model // 创建数据库 Model 对象
func Redis(name ...string) *gredis.Redis // 获取 Redis 客户端对象
其他功能
func Log(name ...string) *glog.Logger // 获取日志管理对象
func View(name ...string) *gview.View // 获取模板引擎对象
func TcpServer(name ...interface{}) *gtcp.Server // 获取 TCP Server 对象
func UdpServer(name ...interface{}) *gudp.Server // 获取 UDP Server 对象
func Res(name ...string) *gres.Resource // 获取资源管理对象
func I18n(name ...string) *gi18n.Manager // 获取国际化管理对象