- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
问题:存在关联键的表列表。有必要为每个表实现 CRUD + 一些关于表细节的功能(分页等)。麻烦:在每个表的每个功能实现中重复了大约 50% 的代码。问题:关于语言细节、优化/重构/使用类似代码模式的方法是什么?
示例代码部分
//------------------------------------------------------------------
// user
//----------------------------------------------------------------------
func (d *Database) UserCreate(email, password, username string, role int) *Answer {
//variables
answer := d.initCall("UserCreate")
user := new(User)
//check exist user
if userExist := d.DB.Find(&User{}, &User{Email:email}).Error; userExist == nil {
answer.AnswerJSON.ErrorAnswer.Message = "[usercreate] user already exist"
answer.AnswerJSON.Result = nil
answer.AnswerJSON.Status = false
} else {
userinfo := UserInfo{Data:time.Now()}
session := Session{Data:time.Now()}
cook := Cook{}
//make support tables object
//userinfo object
userinfo.Password = password
userinfo.Username = username
//cook object
cook.SessionID = session.ID
cook.Cookie = d.cookgeneratenew("somesaltforcooksgenerate")
cook.Status = true
cook.Lastconnect = time.Now()
cook.CountConnect += 1
//user object
user.Email = email
user.Session = session
user.UserInfo = userinfo
user.Cook = cook
user.Role = int64(role)
//make request + //serizlizations to json answer
if err := d.DB.Create(user).Error; err != nil {
answer.AnswerJSON.ErrorAnswer.Message = err.Error()
answer.AnswerJSON.Status = false
} else {
answer.AnswerJSON.Result = user
answer.AnswerJSON.Status = true
}
}
d.serilize(answer)
return answer
}
func (d *Database) UserDelete(userid int64) *Answer {
answer := d.initCall("UserDelete")
user := new(User)
//check exists
if userExists := d.DB.Find(user, "ID = ?", userid).Error; userExists == nil {
if userDelete := d.DB.Delete(user).Error; userDelete != nil {
answer.AnswerJSON.ErrorAnswer.Message = userExists.Error()
answer.AnswerJSON.Status = false
} else {
answer.AnswerJSON.Status = true
answer.AnswerJSON.ErrorAnswer = nil
}
} else {
answer.AnswerJSON.ErrorAnswer.Message = userExists.Error()
answer.AnswerJSON.Status = false
}
d.serilize(answer)
return answer
}
func (d *Database) UserRead(userid int64) *Answer {
answer := d.initCall("UserRead")
user := new(User)
if userExists := d.DB.Find(user, "ID = ?", userid).Error; userExists != nil {
answer.AnswerJSON.ErrorAnswer.Message = userExists.Error()
answer.AnswerJSON.Status = false
} else {
if rel := d.DB.Model(user).Related(&user.Session).Error; rel != nil {
answer.AnswerJSON.Result = nil
answer.AnswerJSON.ErrorAnswer.Message = rel.Error()
answer.AnswerJSON.Status = false
} else if rel = d.DB.Model(user).Related(&user.UserInfo).Error; rel != nil {
answer.AnswerJSON.Result = nil
answer.AnswerJSON.ErrorAnswer.Message = rel.Error()
answer.AnswerJSON.Status = false
} else if rel = d.DB.Model(user).Related(&user.Cook).Error; rel != nil {
answer.AnswerJSON.Result = nil
answer.AnswerJSON.ErrorAnswer.Message = rel.Error()
answer.AnswerJSON.Status = false
} else {
answer.AnswerJSON.Result = user
answer.AnswerJSON.ErrorAnswer = nil
answer.AnswerJSON.Status = true
}
}
d.serilize(answer)
return answer
}
func (d *Database) UserReadAll() *Answer {
answer := d.initCall("UserReadAll")
users := []User{}
if usersGet := d.DB.Find(&users).Error; usersGet != nil {
answer.AnswerJSON.ErrorAnswer.Message = usersGet.Error()
answer.AnswerJSON.Status = false
} else {
for _, user := range users {
d.DB.Model(user).Related(&user.Session)
d.DB.Model(user).Related(&user.UserInfo)
d.DB.Model(user).Related(&user.Cook)
}
answer.AnswerJSON.Result = users
answer.AnswerJSON.ErrorAnswer = nil
answer.AnswerJSON.Status = true
}
d.serilize(answer)
return answer
}
func (d *Database) UserUpdate(userid int64, uu *UserUpdateStruct) *Answer {
answer := d.initCall("UserUpdate")
user := new(User)
if userExists := d.DB.Find(user, "ID = ?", userid).Error; userExists != nil {
answer.AnswerJSON.ErrorAnswer.Message = userExists.Error()
answer.AnswerJSON.Status = false
} else {
//get relevating struct info
d.DB.Model(user).Related(&user.Session)
d.DB.Model(user).Related(&user.UserInfo)
d.DB.Model(user).Related(&user.Cook)
//update columns
if uu.Email != "" {
user.Email = uu.Email
}
if uu.Avatar > 0 {
user.UserInfo.Avatar = uu.Avatar
}
if uu.Birthday != "" {
user.UserInfo.Birthday = uu.Birthday
}
if uu.Location != "" {
user.UserInfo.Location = uu.Location
}
if uu.Male != "" {
user.UserInfo.Male = uu.Male
}
if uu.Password != "" {
user.UserInfo.Password = uu.Password
}
if uu.Role > 0 {
if roleErr := d.DB.Find(&Role{}).Error; roleErr != nil {
//role not found
fmt.Printf("[userupdate] role not found `%d`\n", uu.Role)
} else {
user.Role = uu.Role
}
}
//update
if errUpdate := d.DB.Save(user).Error; errUpdate != nil {
answer.AnswerJSON.ErrorAnswer.Message = errUpdate.Error()
answer.AnswerJSON.Status = false
} else {
answer.AnswerJSON.Result = user
answer.AnswerJSON.ErrorAnswer = nil
answer.AnswerJSON.Status = true
}
}
d.serilize(answer)
return answer
}
func (d *Database) UserPaginate(page, countPage int) *Answer {
answer := d.initCall("UserPaginate")
result := []*User{}
if errPag := d.DB.Limit(countPage).Offset((page * countPage) - countPage).Find(&result).Error; errPag != nil {
answer.AnswerJSON.ErrorAnswer.Message = errPag.Error()
answer.AnswerJSON.Status = false
} else {
for _, user := range result {
d.DB.Model(&user).Related(&user.Session)
d.DB.Model(&user).Related(&user.UserInfo)
d.DB.Model(&user).Related(&user.Cook)
}
answer.AnswerJSON.Result = result
answer.AnswerJSON.ErrorAnswer = nil
answer.AnswerJSON.Status = true
}
d.serilize(answer)
return answer
}
//-------------------------------------------------------------------
// category
//--------------------------------------------------------------------
func (d *Database) CategoryCreate(name string) *Answer {
//variables
answer := d.initCall("CategoryCreate")
cat := new(Category)
//check exist user
if catExist := d.DB.Find(&Category{}, &Category{Name:name}).Error; catExist == nil {
answer.AnswerJSON.ErrorAnswer.Message = "[categorycreate] category already exist"
answer.AnswerJSON.Result = nil
answer.AnswerJSON.Status = false
} else {
cat.Name = name
//make request + //serizlizations to json answer
if err := d.DB.Create(cat).Error; err != nil {
answer.AnswerJSON.ErrorAnswer.Message = err.Error()
answer.AnswerJSON.Status = false
} else {
answer.AnswerJSON.Result = cat
answer.AnswerJSON.Status = true
}
}
d.serilize(answer)
return answer
}
func (d *Database) CategoryDelete(catid int64) *Answer {
answer := d.initCall("CategoryDelete")
cat := new(Category)
//check exists
if catExists := d.DB.Find(cat, "ID = ?", catid).Error; catExists == nil {
if catDelete := d.DB.Delete(cat).Error; catDelete != nil {
answer.AnswerJSON.ErrorAnswer.Message = catExists.Error()
answer.AnswerJSON.Status = false
} else {
answer.AnswerJSON.Status = true
answer.AnswerJSON.ErrorAnswer = nil
}
} else {
answer.AnswerJSON.ErrorAnswer.Message = catExists.Error()
answer.AnswerJSON.Status = false
}
d.serilize(answer)
return answer
}
func (d *Database) CategoryRead(catid int64) *Answer {
answer := d.initCall("CategoryRead")
cat := new(Category)
if catExists := d.DB.Find(cat, "ID = ?", catid).Error; catExists != nil {
answer.AnswerJSON.ErrorAnswer.Message = catExists.Error()
answer.AnswerJSON.Status = false
} else {
if rel := d.DB.Model(cat).Related(&cat.Post).Error; rel != nil {
answer.AnswerJSON.Result = nil
answer.AnswerJSON.ErrorAnswer.Message = rel.Error()
answer.AnswerJSON.Status = false
} else {
for x, p := range cat.Post {
d.DB.Model(&p).Related(&p.Comment)
d.DB.Model(&p).Related(&p.PostSeo)
cat.Post[x] = p
}
answer.AnswerJSON.Result = cat
answer.AnswerJSON.ErrorAnswer = nil
answer.AnswerJSON.Status = true
}
}
d.serilize(answer)
return answer
}
func (d *Database) CategoryReadAll() *Answer {
answer := d.initCall("CategoryReadAll")
cats := []Category{}
if catsGet := d.DB.Find(&cats).Error; catsGet != nil {
answer.AnswerJSON.ErrorAnswer.Message = catsGet.Error()
answer.AnswerJSON.Status = false
} else {
//categorys
for _, cat := range cats {
d.DB.Model(cat).Related(&cat.Post)
//get relete POST
for x, p := range cat.Post {
d.DB.Model(&p).Related(&p.Comment)
d.DB.Model(&p).Related(&p.PostSeo)
cat.Post[x] = p
}
}
answer.AnswerJSON.Result = cats
answer.AnswerJSON.ErrorAnswer = nil
answer.AnswerJSON.Status = true
}
d.serilize(answer)
return answer
}
func (d *Database) CategoryUpdate(catid int64, name string) *Answer {
answer := d.initCall("CategoryUpdate")
cat := new(Category)
if catExists := d.DB.Find(cat, "ID = ?", catid).Error; catExists != nil {
answer.AnswerJSON.ErrorAnswer.Message = catExists.Error()
answer.AnswerJSON.Status = false
} else {
//get relevating struct info
d.DB.Model(cat).Related(&cat.Post)
//update columns
if name != "" {
cat.Name = name
}
//update
if errUpdate := d.DB.Save(cat).Error; errUpdate != nil {
answer.AnswerJSON.ErrorAnswer.Message = errUpdate.Error()
answer.AnswerJSON.Status = false
} else {
answer.AnswerJSON.Result = cat
answer.AnswerJSON.ErrorAnswer = nil
answer.AnswerJSON.Status = true
}
}
d.serilize(answer)
return answer
}
func (d *Database) CategoryPaginate(page, countPage int) *Answer {
answer := d.initCall("CategoryPaginate")
result := []*Category{}
if errPag := d.DB.Limit(countPage).Offset((page * countPage) - countPage).Find(&result).Error; errPag != nil {
answer.AnswerJSON.ErrorAnswer.Message = errPag.Error()
answer.AnswerJSON.Status = false
} else {
for _, cat := range result {
d.DB.Model(&cat).Related(&cat.Post)
//get relete POST
for x, p := range cat.Post {
d.DB.Model(&p).Related(&p.Comment)
d.DB.Model(&p).Related(&p.PostSeo)
cat.Post[x] = p
}
}
answer.AnswerJSON.Result = result
answer.AnswerJSON.ErrorAnswer = nil
answer.AnswerJSON.Status = true
}
d.serilize(answer)
return answer
}
最佳答案
我可以看到您的代码中有很多冗余。几个月前我遇到了同样的问题并且得到了很好的答案。看这里:How to return dynamic type struct in Golang? .
基本上你会像这样拥有相同的三个功能(添加/编辑/删除/计数)(我不知道你用的是什么数据库我用的是NoSql Rethinkdb,但原理是一样的):
func (c Main) Get(modelname string) interface{} {
//your query here for getting stuff from model name and return interface
rows, err := rethink.Table(modelname).OrderBy(rethink.Asc("sortNo")).Run(c.DB)
if err != nil {
log.Println(err)
return nil
}
if (modelType == "brand") {
var brands []*models.Brand
rows.All(&brands)
return brands
}
//rest of your models here or use some switch
})
我通常将所有与数据库相关的功能都放在一些助手中(这主要是因为测试)。
我认为这是一个很好的方向,因为这样您的代码很容易维护,您将只更改辅助函数,而不是去为每个模型执行添加/删除/更新的数百万个小说。
关于戈朗。重构 ||图案 ||任何解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38079036/
我想知道将任何数据发送到模板(html/template 包)的真正方法是什么?我的代码如下: var templates = template.Must(template.ParseFiles(
我有密码 if config.Process.TraceLog != "" { f, err := os.OpenFile(config.Process.TraceLog, os.O_RDWR
大家好。我是 GO 的新手,需要一些帮助。我有一个具有这种结构的项目 但让我们假设我的逻辑包 中有 100500 个项目。如果我只需要为特定包导入一个或两个文件怎么办?我可以这样做还是只能导入完整包?
package main import ( "fmt" ) func main() { var square int box := [4]int{1, -2, 3, 4}
我想在每个范围循环后递增一个变量。但是,似乎无法使用标准(for init; condition; post {})语法,因此我想知道为什么。这是我正在尝试做的事情 for item := r
这个问题在这里已经有了答案: Creating a Constant Type and Restricting the Type's Values (2 个答案) 关闭 6 年前。 什么是只允许一组
我试过编译我的简单程序: func main(){fmt.Printf("Hello")} 根据文档在我的 PC 上使用 64 位 Debian Linux 到 MIPS 架构 https://gol
为什么不在 channel 上发送并阻止执行?我怎样才能使这个星座工作,以便我可以向 MoneyDive() 发送信号并继续执行? package main import ( "fmt" )
这是来自 Golang.org http://golang.org/pkg/sort/ // By is the type of a "less" function that defines the
class type User { name string } 是否可以在运行时添加字段age? 最佳答案 不,这是不可能的。 即使使用 Java 或 C++ 语法代替有效的 Go 也不行。
当我编译下面的程序时 func myPrint(v ...interface{}) { fmt.Println("Hello", v...) } func main() { m
有一个问题,这里发生了什么? forever := make(chan bool) log.Printf(" [*] Waiting for messages. To exit press CTRL+
当我运行我的 GoLang 程序时,它抛出了这个异常: packages/go-lang/1.3/pkg/tool/linux_amd64/6l: readsym 不同步 它是否来 self 的 am
我时常会遇到诸如零垃圾或有效使用内存等概念。例如在知名包的特性部分 httprouter您可以看到以下内容: Zero Garbage: The matching and dispatching pr
最近读了golang规范,遇到了一些有趣的操作符: & bitwise AND integers | bitwise OR integers
有这个包https://github.com/open-telemetry/opentelemetry-proto其中仅包含 protobuf 定义。要生成 golang 代码,必须输入: make
有这个包https://github.com/open-telemetry/opentelemetry-proto其中仅包含 protobuf 定义。要生成 golang 代码,必须输入: make
我正在使用下面的代码连接到 grpc 服务器,clientConn 对象用于所有后续的 rpc 调用。 maxDelay 设置为 5 秒。现在由于服务器出现问题,它没有响应 grpc 调用。所以我的客
初始数据: rawdata := []int{17, 23, 100500} 结果: result := convert(rawdata) expected := "1723100500" 我应该用
我想用我的智能手机操作我的窗帘。现在每次我改变手机的位置时都有一个方法 func main() { OnUpdate(func(tPos int) { wc(tPos,cPos)
我是一名优秀的程序员,十分优秀!