减少内存消耗
比如说下面这段程序
for i, tl := 0, len(t); i < tl; i++{
if t[i].method != httpMethod{
continue
}
}
初始化的时候就赋值了tl, tl 等于 t 的长度,这样避免了每次循环动态的计算长度,减少了内存消耗。
比下面这样写好
for i := 0; i< len(t); i++{
}
type IRouter interface {
IRoutes
Group(string, ...HandlerFunc) *RouterGroup
}
type Engine struct {
RouterGroup
RedirectTrailingSlash bool
RedirectFixedPath bool
HandleMethodNotAllowed bool
ForwardedByClientIP bool
RemoteIPHeaders []string
TrustedProxies []string
AppEngine bool
UseRawPath bool
UnescapePathValues bool
MaxMultipartMemory int64
RemoveExtraSlash bool
delims render.Delims
secureJSONPrefix string
HTMLRender render.HTMLRender
FuncMap template.FuncMap
allNoRoute HandlersChain
allNoMethod HandlersChain
noRoute HandlersChain
noMethod HandlersChain
pool sync.Pool
trees methodTrees
maxParams uint16
trustedCIDRs []*net.IPNet
}
var _ IRouter = &Engine{}
这样写是为了确保结构体实现了一个接口,为了把问题暴露在编译阶段,如果engine没有实现接口的话,就会报错
键值对判断和全局变量
var (
driversMu sync.RWMutex
drivers = make(map[string]driver.Driver)
)
if _, dup := drivers[name]; dup {
panic("sql: Register called twice for driver " + name)
}
两点:
– 声明一些全局变量
– 用这种方式判断键值是否存在
类型断言
if driverCtx, ok := driveri.(driver.DriverContext); ok {
connector, err := driverCtx.OpenConnector(dataSourceName)
if err != nil {
return nil, err
}
return OpenDB(connector), nil
}