Optimize maligned structs

This commit is contained in:
Nitin Mohan 2021-03-08 12:44:14 +05:30
parent 7909fb5ff3
commit f554a1c543
12 changed files with 91 additions and 88 deletions

View File

@ -24,6 +24,7 @@
- Add some testing scripts [4461](https://github.com/beego/beego/pull/4461) - Add some testing scripts [4461](https://github.com/beego/beego/pull/4461)
- Refactor httplib: Move debug code to a filter [4440](https://github.com/beego/beego/issues/4440) - Refactor httplib: Move debug code to a filter [4440](https://github.com/beego/beego/issues/4440)
- fix: code quality issues [4513](https://github.com/beego/beego/pull/4513) - fix: code quality issues [4513](https://github.com/beego/beego/pull/4513)
- Optimize maligned structs to reduce memory foot-print [4525](https://github.com/beego/beego/pull/4525)
## Fix Sonar ## Fix Sonar

View File

@ -101,29 +101,30 @@ func newFields() *fields {
// single field info // single field info
type fieldInfo struct { type fieldInfo struct {
mi *modelInfo
fieldIndex []int
fieldType int
dbcol bool // table column fk and onetoone dbcol bool // table column fk and onetoone
inModel bool inModel bool
name string
fullName string
column string
addrValue reflect.Value
sf reflect.StructField
auto bool auto bool
pk bool pk bool
null bool null bool
index bool index bool
unique bool unique bool
colDefault bool // whether has default tag colDefault bool // whether has default tag
initial StrTo // store the default value
size int
toText bool toText bool
autoNow bool autoNow bool
autoNowAdd bool autoNowAdd bool
rel bool // if type equal to RelForeignKey, RelOneToOne, RelManyToMany then true rel bool // if type equal to RelForeignKey, RelOneToOne, RelManyToMany then true
reverse bool reverse bool
isFielder bool // implement Fielder interface
mi *modelInfo
fieldIndex []int
fieldType int
name string
fullName string
column string
addrValue reflect.Value
sf reflect.StructField
initial StrTo // store the default value
size int
reverseField string reverseField string
reverseFieldInfo *fieldInfo reverseFieldInfo *fieldInfo
reverseFieldInfoTwo *fieldInfo reverseFieldInfoTwo *fieldInfo
@ -134,7 +135,6 @@ type fieldInfo struct {
relModelInfo *modelInfo relModelInfo *modelInfo
digits int digits int
decimals int decimals int
isFielder bool // implement Fielder interface
onDelete string onDelete string
description string description string
timePrecision *int timePrecision *int

View File

@ -22,16 +22,16 @@ import (
// single model info // single model info
type modelInfo struct { type modelInfo struct {
manual bool
isThrough bool
pkg string pkg string
name string name string
fullName string fullName string
table string table string
model interface{} model interface{}
fields *fields fields *fields
manual bool
addrField reflect.Value // store the original struct value addrField reflect.Value // store the original struct value
uniques []string uniques []string
isThrough bool
} }
// new model info // new model info

View File

@ -118,6 +118,10 @@ var _ Fielder = new(JSONFieldTest)
type Data struct { type Data struct {
ID int `orm:"column(id)"` ID int `orm:"column(id)"`
Boolean bool Boolean bool
Byte byte
Int8 int8
Uint8 uint8
Rune rune
Char string `orm:"size(50)"` Char string `orm:"size(50)"`
Text string `orm:"type(text)"` Text string `orm:"type(text)"`
JSON string `orm:"type(json);default({\"name\":\"json\"})"` JSON string `orm:"type(json);default({\"name\":\"json\"})"`
@ -125,26 +129,21 @@ type Data struct {
Time time.Time `orm:"type(time)"` Time time.Time `orm:"type(time)"`
Date time.Time `orm:"type(date)"` Date time.Time `orm:"type(date)"`
DateTime time.Time `orm:"column(datetime)"` DateTime time.Time `orm:"column(datetime)"`
Byte byte
Rune rune
Int int Int int
Int8 int8 Uint uint
Int16 int16 Int16 int16
Uint16 uint16
Int32 int32 Int32 int32
Int64 int64 Int64 int64
Uint uint
Uint8 uint8
Uint16 uint16
Uint32 uint32 Uint32 uint32
Uint64 uint64
Float32 float32 Float32 float32
Uint64 uint64
Float64 float64 Float64 float64
Decimal float64 `orm:"digits(8);decimals(4)"` Decimal float64 `orm:"digits(8);decimals(4)"`
} }
type DataNull struct { type DataNull struct {
ID int `orm:"column(id)"` ID int `orm:"column(id)"`
Boolean bool `orm:"null"`
Char string `orm:"null;size(50)"` Char string `orm:"null;size(50)"`
Text string `orm:"null;type(text)"` Text string `orm:"null;type(text)"`
JSON string `orm:"type(json);null"` JSON string `orm:"type(json);null"`
@ -153,19 +152,20 @@ type DataNull struct {
Date time.Time `orm:"null;type(date)"` Date time.Time `orm:"null;type(date)"`
DateTime time.Time `orm:"null;column(datetime)"` DateTime time.Time `orm:"null;column(datetime)"`
DateTimePrecision time.Time `orm:"null;type(datetime);precision(4)"` DateTimePrecision time.Time `orm:"null;type(datetime);precision(4)"`
Boolean bool `orm:"null"`
Byte byte `orm:"null"` Byte byte `orm:"null"`
Int8 int8 `orm:"null"`
Uint8 uint8 `orm:"null"`
Rune rune `orm:"null"` Rune rune `orm:"null"`
Int int `orm:"null"` Int int `orm:"null"`
Int8 int8 `orm:"null"` Uint uint `orm:"null"`
Int16 int16 `orm:"null"` Int16 int16 `orm:"null"`
Uint16 uint16 `orm:"null"`
Int32 int32 `orm:"null"` Int32 int32 `orm:"null"`
Int64 int64 `orm:"null"` Int64 int64 `orm:"null"`
Uint uint `orm:"null"`
Uint8 uint8 `orm:"null"`
Uint16 uint16 `orm:"null"`
Uint32 uint32 `orm:"null"` Uint32 uint32 `orm:"null"`
Uint64 uint64 `orm:"null"`
Float32 float32 `orm:"null"` Float32 float32 `orm:"null"`
Uint64 uint64 `orm:"null"`
Float64 float64 `orm:"null"` Float64 float64 `orm:"null"`
Decimal float64 `orm:"digits(8);decimals(4);null"` Decimal float64 `orm:"digits(8);decimals(4);null"`
NullString sql.NullString `orm:"null"` NullString sql.NullString `orm:"null"`
@ -215,21 +215,21 @@ type Float64 float64
type DataCustom struct { type DataCustom struct {
ID int `orm:"column(id)"` ID int `orm:"column(id)"`
Boolean Boolean Boolean Boolean
Byte Byte
Int8 Int8
Uint8 Uint8
Rune Rune
Char string `orm:"size(50)"` Char string `orm:"size(50)"`
Text string `orm:"type(text)"` Text string `orm:"type(text)"`
Byte Byte
Rune Rune
Int Int Int Int
Int8 Int8 Uint Uint
Int16 Int16 Int16 Int16
Uint16 Uint16
Int32 Int32 Int32 Int32
Int64 Int64 Int64 Int64
Uint Uint
Uint8 Uint8
Uint16 Uint16
Uint32 Uint32 Uint32 Uint32
Uint64 Uint64
Float32 Float32 Float32 Float32
Uint64 Uint64
Float64 Float64 Float64 Float64
Decimal Float64 `orm:"digits(8);decimals(4)"` Decimal Float64 `orm:"digits(8);decimals(4)"`
} }
@ -278,7 +278,9 @@ type User struct {
Password string `orm:"size(100)"` Password string `orm:"size(100)"`
Status int16 `orm:"column(Status)"` Status int16 `orm:"column(Status)"`
IsStaff bool IsStaff bool
IsActive bool `orm:"default(true)"` IsActive bool `orm:"default(true)"`
unexport bool `orm:"-"`
unexportBool bool
Created time.Time `orm:"auto_now_add;type(date)"` Created time.Time `orm:"auto_now_add;type(date)"`
Updated time.Time `orm:"auto_now"` Updated time.Time `orm:"auto_now"`
Profile *Profile `orm:"null;rel(one);on_delete(set_null)"` Profile *Profile `orm:"null;rel(one);on_delete(set_null)"`
@ -287,8 +289,6 @@ type User struct {
Nums int Nums int
Langs SliceStringField `orm:"size(100)"` Langs SliceStringField `orm:"size(100)"`
Extra JSONFieldTest `orm:"type(text)"` Extra JSONFieldTest `orm:"type(text)"`
unexport bool `orm:"-"`
unexportBool bool
} }
func (u *User) TableIndex() [][]string { func (u *User) TableIndex() [][]string {

View File

@ -51,24 +51,25 @@ func TestTagAutoWireBeanFactory_AutoWire(t *testing.T) {
} }
type ComplicateStruct struct { type ComplicateStruct struct {
IntValue int `default:"12"` BoolValue bool `default:"true"`
StrValue string `default:"hello, strValue"` Int8Value int8 `default:"8"`
Int8Value int8 `default:"8"` Uint8Value uint8 `default:"88"`
Int16Value int16 `default:"16"`
Int32Value int32 `default:"32"`
Int64Value int64 `default:"64"`
UintValue uint `default:"13"` Int16Value int16 `default:"16"`
Uint8Value uint8 `default:"88"`
Uint16Value uint16 `default:"1616"` Uint16Value uint16 `default:"1616"`
Int32Value int32 `default:"32"`
Uint32Value uint32 `default:"3232"` Uint32Value uint32 `default:"3232"`
IntValue int `default:"12"`
UintValue uint `default:"13"`
Int64Value int64 `default:"64"`
Uint64Value uint64 `default:"6464"` Uint64Value uint64 `default:"6464"`
StrValue string `default:"hello, strValue"`
Float32Value float32 `default:"32.32"` Float32Value float32 `default:"32.32"`
Float64Value float64 `default:"64.64"` Float64Value float64 `default:"64.64"`
BoolValue bool `default:"true"`
ignoreInt int `default:"11"` ignoreInt int `default:"11"`
TimeValue time.Time `default:"2018-02-03 12:13:14.000"` TimeValue time.Time `default:"2018-02-03 12:13:14.000"`

View File

@ -33,6 +33,11 @@ import (
// Writes messages by lines limit, file size limit, or time frequency. // Writes messages by lines limit, file size limit, or time frequency.
type fileLogWriter struct { type fileLogWriter struct {
sync.RWMutex // write log order by order and atomic incr maxLinesCurLines and maxSizeCurSize sync.RWMutex // write log order by order and atomic incr maxLinesCurLines and maxSizeCurSize
Rotate bool `json:"rotate"`
Daily bool `json:"daily"`
Hourly bool `json:"hourly"`
// The opened file // The opened file
Filename string `json:"filename"` Filename string `json:"filename"`
fileWriter *os.File fileWriter *os.File
@ -49,19 +54,15 @@ type fileLogWriter struct {
maxSizeCurSize int maxSizeCurSize int
// Rotate daily // Rotate daily
Daily bool `json:"daily"`
MaxDays int64 `json:"maxdays"` MaxDays int64 `json:"maxdays"`
dailyOpenDate int dailyOpenDate int
dailyOpenTime time.Time dailyOpenTime time.Time
// Rotate hourly // Rotate hourly
Hourly bool `json:"hourly"`
MaxHours int64 `json:"maxhours"` MaxHours int64 `json:"maxhours"`
hourlyOpenDate int hourlyOpenDate int
hourlyOpenTime time.Time hourlyOpenTime time.Time
Rotate bool `json:"rotate"`
Level int `json:"level"` Level int `json:"level"`
Perm string `json:"perm"` Perm string `json:"perm"`

View File

@ -112,17 +112,17 @@ func Register(name string, log newLoggerFunc) {
// Can contain several providers and log message into all providers. // Can contain several providers and log message into all providers.
type BeeLogger struct { type BeeLogger struct {
lock sync.Mutex lock sync.Mutex
level int
init bool init bool
enableFuncCallDepth bool enableFuncCallDepth bool
loggerFuncCallDepth int
enableFullFilePath bool enableFullFilePath bool
asynchronous bool asynchronous bool
wg sync.WaitGroup
level int
loggerFuncCallDepth int
prefix string prefix string
msgChanLen int64 msgChanLen int64
msgChan chan *LogMsg msgChan chan *LogMsg
signalChan chan string signalChan chan string
wg sync.WaitGroup
outputs []*nameLogger outputs []*nameLogger
globalFormatter string globalFormatter string
} }

View File

@ -39,46 +39,46 @@ type Config struct {
AppName string // Application name AppName string // Application name
RunMode string // Running Mode: dev | prod RunMode string // Running Mode: dev | prod
RouterCaseSensitive bool RouterCaseSensitive bool
ServerName string
RecoverPanic bool RecoverPanic bool
RecoverFunc func(*context.Context, *Config)
CopyRequestBody bool CopyRequestBody bool
EnableGzip bool EnableGzip bool
EnableErrorsShow bool
EnableErrorsRender bool
ServerName string
RecoverFunc func(*context.Context, *Config)
// MaxMemory and MaxUploadSize are used to limit the request body // MaxMemory and MaxUploadSize are used to limit the request body
// if the request is not uploading file, MaxMemory is the max size of request body // if the request is not uploading file, MaxMemory is the max size of request body
// if the request is uploading file, MaxUploadSize is the max size of request body // if the request is uploading file, MaxUploadSize is the max size of request body
MaxMemory int64 MaxMemory int64
MaxUploadSize int64 MaxUploadSize int64
EnableErrorsShow bool Listen Listen
EnableErrorsRender bool WebConfig WebConfig
Listen Listen Log LogConfig
WebConfig WebConfig
Log LogConfig
} }
// Listen holds for http and https related config // Listen holds for http and https related config
type Listen struct { type Listen struct {
Graceful bool // Graceful means use graceful module to start the server Graceful bool // Graceful means use graceful module to start the server
ServerTimeOut int64
ListenTCP4 bool ListenTCP4 bool
EnableHTTP bool EnableHTTP bool
HTTPAddr string
HTTPPort int
AutoTLS bool AutoTLS bool
Domains []string
TLSCacheDir string
EnableHTTPS bool EnableHTTPS bool
EnableMutualHTTPS bool EnableMutualHTTPS bool
EnableAdmin bool
EnableFcgi bool
EnableStdIo bool // EnableStdIo works with EnableFcgi Use FCGI via standard I/O
ServerTimeOut int64
HTTPAddr string
HTTPPort int
Domains []string
TLSCacheDir string
HTTPSAddr string HTTPSAddr string
HTTPSPort int HTTPSPort int
HTTPSCertFile string HTTPSCertFile string
HTTPSKeyFile string HTTPSKeyFile string
TrustCaFile string TrustCaFile string
EnableAdmin bool
AdminAddr string AdminAddr string
AdminPort int AdminPort int
EnableFcgi bool
EnableStdIo bool // EnableStdIo works with EnableFcgi Use FCGI via standard I/O
ClientAuth int ClientAuth int
} }
@ -86,9 +86,10 @@ type Listen struct {
type WebConfig struct { type WebConfig struct {
AutoRender bool AutoRender bool
EnableDocs bool EnableDocs bool
EnableXSRF bool
DirectoryIndex bool
FlashName string FlashName string
FlashSeparator string FlashSeparator string
DirectoryIndex bool
StaticDir map[string]string StaticDir map[string]string
StaticExtensionsToGzip []string StaticExtensionsToGzip []string
StaticCacheFileSize int StaticCacheFileSize int
@ -97,7 +98,6 @@ type WebConfig struct {
TemplateRight string TemplateRight string
ViewsPath string ViewsPath string
CommentRouterPath string CommentRouterPath string
EnableXSRF bool
XSRFKey string XSRFKey string
XSRFExpire int XSRFExpire int
Session SessionConfig Session SessionConfig
@ -106,26 +106,26 @@ type WebConfig struct {
// SessionConfig holds session related config // SessionConfig holds session related config
type SessionConfig struct { type SessionConfig struct {
SessionOn bool SessionOn bool
SessionAutoSetCookie bool
SessionDisableHTTPOnly bool // used to allow for cross domain cookies/javascript cookies.
SessionEnableSidInHTTPHeader bool // enable store/get the sessionId into/from http headers
SessionEnableSidInURLQuery bool // enable get the sessionId from Url Query params
SessionProvider string SessionProvider string
SessionName string SessionName string
SessionGCMaxLifetime int64 SessionGCMaxLifetime int64
SessionProviderConfig string SessionProviderConfig string
SessionCookieLifeTime int SessionCookieLifeTime int
SessionAutoSetCookie bool
SessionDomain string SessionDomain string
SessionDisableHTTPOnly bool // used to allow for cross domain cookies/javascript cookies.
SessionEnableSidInHTTPHeader bool // enable store/get the sessionId into/from http headers
SessionNameInHTTPHeader string SessionNameInHTTPHeader string
SessionEnableSidInURLQuery bool // enable get the sessionId from Url Query params
SessionCookieSameSite http.SameSite SessionCookieSameSite http.SameSite
} }
// LogConfig holds Log related config // LogConfig holds Log related config
type LogConfig struct { type LogConfig struct {
AccessLogs bool AccessLogs bool
EnableStaticLogs bool // log static files requests default: false EnableStaticLogs bool // log static files requests default: false
AccessLogsFormat string // access log format: JSON_FORMAT, APACHE_FORMAT or empty string
FileLineNum bool FileLineNum bool
AccessLogsFormat string // access log format: JSON_FORMAT, APACHE_FORMAT or empty string
Outputs map[string]string // Store Adaptor : config Outputs map[string]string // Store Adaptor : config
} }

View File

@ -108,9 +108,9 @@ type Controller struct {
EnableRender bool EnableRender bool
// xsrf data // xsrf data
EnableXSRF bool
_xsrfToken string _xsrfToken string
XSRFExpire int XSRFExpire int
EnableXSRF bool
// session // session
CruSession session.Store CruSession session.Store

View File

@ -69,10 +69,10 @@ var (
type Options struct { type Options struct {
// If set, all origins are allowed. // If set, all origins are allowed.
AllowAllOrigins bool AllowAllOrigins bool
// A list of allowed origins. Wild cards and FQDNs are supported.
AllowOrigins []string
// If set, allows to share auth credentials such as cookies. // If set, allows to share auth credentials such as cookies.
AllowCredentials bool AllowCredentials bool
// A list of allowed origins. Wild cards and FQDNs are supported.
AllowOrigins []string
// A list of allowed HTTP methods. // A list of allowed HTTP methods.
AllowMethods []string AllowMethods []string
// A list of allowed HTTP headers. // A list of allowed HTTP headers.

View File

@ -150,8 +150,8 @@ type filterChainConfig struct {
type ControllerRegister struct { type ControllerRegister struct {
routers map[string]*Tree routers map[string]*Tree
enablePolicy bool enablePolicy bool
policies map[string]*Tree
enableFilter bool enableFilter bool
policies map[string]*Tree
filters [FinishRouter + 1][]*FilterRouter filters [FinishRouter + 1][]*FilterRouter
pool sync.Pool pool sync.Pool

View File

@ -4,19 +4,19 @@ import "net/http"
// ManagerConfig define the session config // ManagerConfig define the session config
type ManagerConfig struct { type ManagerConfig struct {
CookieName string `json:"cookieName"`
EnableSetCookie bool `json:"enableSetCookie,omitempty"` EnableSetCookie bool `json:"enableSetCookie,omitempty"`
Gclifetime int64 `json:"gclifetime"`
Maxlifetime int64 `json:"maxLifetime"`
DisableHTTPOnly bool `json:"disableHTTPOnly"` DisableHTTPOnly bool `json:"disableHTTPOnly"`
Secure bool `json:"secure"` Secure bool `json:"secure"`
EnableSidInHTTPHeader bool `json:"EnableSidInHTTPHeader"`
EnableSidInURLQuery bool `json:"EnableSidInURLQuery"`
CookieName string `json:"cookieName"`
Gclifetime int64 `json:"gclifetime"`
Maxlifetime int64 `json:"maxLifetime"`
CookieLifeTime int `json:"cookieLifeTime"` CookieLifeTime int `json:"cookieLifeTime"`
ProviderConfig string `json:"providerConfig"` ProviderConfig string `json:"providerConfig"`
Domain string `json:"domain"` Domain string `json:"domain"`
SessionIDLength int64 `json:"sessionIDLength"` SessionIDLength int64 `json:"sessionIDLength"`
EnableSidInHTTPHeader bool `json:"EnableSidInHTTPHeader"`
SessionNameInHTTPHeader string `json:"SessionNameInHTTPHeader"` SessionNameInHTTPHeader string `json:"SessionNameInHTTPHeader"`
EnableSidInURLQuery bool `json:"EnableSidInURLQuery"`
SessionIDPrefix string `json:"sessionIDPrefix"` SessionIDPrefix string `json:"sessionIDPrefix"`
CookieSameSite http.SameSite `json:"cookieSameSite"` CookieSameSite http.SameSite `json:"cookieSameSite"`
} }