GF 框架封装了一些常用的数据类型以及对象获取方法,通过 g.* 方法获取。
g 是一个强耦合的模块,目的是为开发者在对频繁使用的类型/对象调用时提供便利。
使用方式:
import "github.com/gogf/gf/frame/g"
数据类型
常用数据类型别名。
// 泛型
type Var = gvar.Var
// 常用Map类型
type Map = map[string]interface{}
type MapAnyAny = map[interface{}]interface{}
type MapAnyStr = map[interface{}]string
type MapAnyInt = map[interface{}]int
type MapStrAny = map[string]interface{}
type MapStrStr = map[string]string
type MapStrInt = map[string]int
type MapIntAny = map[int]interface{}
type MapIntStr = map[int]string
type MapIntInt = map[int]int
// 常用Slice Map类型
type List = []Map
type ListAnyStr = []map[interface{}]string
type ListAnyInt = []map[interface{}]int
type ListStrAny = []map[string]interface{}
type ListStrStr = []map[string]string
type ListStrInt = []map[string]int
type ListIntAny = []map[int]interface{}
type ListIntStr = []map[int]string
type ListIntInt = []map[int]int
// 常用Slice类型
type Slice = []interface{}
type SliceAny = []interface{}
type SliceStr = []string
type SliceInt = []int
// 常用Slice类型(别名)
type Array = []interface{}
type ArrayAny = []interface{}
type ArrayStr = []string
type ArrayInt = []int
常用对象
常用对象往往通过 单例模式 进行管理,可以根据不同的单例名称获取对应的对象实例,并在对象初始化时会自动检索获取配置文件中的对应配置项,具体配置项请查看对应对象的章节介绍。
注意事项:在运行时阶段,每一次通过 g 模块获取单例对象时都会有内部全局锁机制来保证操作和数据的并发安全性,原理性上来讲在并发量大的场景下会存在锁竞争的情况,但绝大部分的业务场景下开发者均不需要太在意锁竞争带来的性能损耗。此外,开发者也可以通过将获取到的单例对象保存到特定的模块下的内部变量重复使用,以此避免运行时锁竞争情况。
HTTP 客户端对象
func Client() *ghttp.Client
创建一个新的 HTTP 客户端对象。
Validator 校验对象
func Validator() *gvalid.Validator
创建一个新的数据校验对象。
(单例) 配置管理对象
func Cfg(name ...string) *gcfg.Config
该单例对象将会自动读取默认配置文件 config.toml 并缓存,配置文件在外部被修改时将会自动刷新缓存。从 GF v1.12 版本开始,为方便多文件场景下的配置文件调用,简便使用并提高开发效率,因此当给定的单例名称对应的 toml 配置文件在配置目录中存在时,将自动设置该单例对象的默认配置文件为该文件。
例如: g.Cfg("redis") 获取到的单例对象将会默认去检索会自动检索 redis.toml、 redis.yaml、 redis.json、 redis.ini、 redis.xml,如果检索成功那么将该文件加载到内存缓存中,下一次将会直接从内存中读取;当该文件不存在时,则使用默认的配置文件( config.toml)。
(单例) 日志管理对象
func Log(name ...string) *glog.Logger
该单例对象将会自动读取默认配置文件中的 logger 配置项,并只会初始化一次日志对象。
(单例) 模板引擎对象
func View(name ...string) *gview.View
该单例对象将会自动读取默认配置文件中的 viewer 配置项,并只会初始化一次模板引擎对象。内部采用了 懒初始化 设计,获取模板引擎对象时只是创建了一个轻量的模板管理对象,只有当解析模板文件时才会真正初始化。
(单例) WEB Server
func Server(name ...interface{}) *ghttp.Server
该单例对象将会自动读取默认配置文件中的 server 配置项,并只会初始化一次 Server 对象。
(单例) TCP Server
func TcpServer(name ...interface{}) *gtcp.Server
(单例) UDP Server
func UdpServer(name ...interface{}) *gudp.Server
(单例) 数据库 ORM 对象
func DB(name ...string) *gdb.Db
该单例对象将会自动读取默认配置文件中的 database 配置项,并只会初始化一次 DB 对象。
此外,可以通过以下方法在默认数据库上创建一个 Model 对象:
func Model(tables string, db ...string) *gdb.Model
(单例) Redis 客户端对象
func Redis(name ...string) *gredis.Redis
该单例对象将会自动读取默认配置文件中的 redis 配置项,并只会初始化一次 Redis 对象。
(单例) 资源管理对象
func Res(name ...string) *gres.Resource
(单例) 国际化管理对象
func I18n(name ...string) *gi18n.Manager