An error occurred in the middle of the booking tutorial.
https://github.com/revel/examples/tree/master/booking
ERROR 18:33:28 watcher.go:270:Build detected an error="Go Compilation Error (in app/controllers/gorm.go:31): undefined:sql"
I got in trouble when I tried to define getUser in controllers/app.go.
First of all, I was told that Txn was not defined, so (hereafter)
ERROR 18:18:26 watcher.go:270:Build detected an error="Go Compilation Error (in app/controllers/app.go:26):c.Txn undefined (type Application has no field or method Txn)"
controllers/gorm.go
to
typeTransactional structure{
*revel.Controller
Txn*sql.Tx
}
(I don't know if it's correct...)
Now, if you think you have defined Txn,
The error at the top came out.
I was told that I couldn't find sql.
Txn*sql.Tx This is the part.
Do I need a definition statement for sql somewhere or do I need to import a package?
Or is there another reason?
package controllers
import(
_"github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"github.com/revel/revel"
"booking/app/models"
"log"
)
typeTransactional structure {
*revel.Controller
Txn*gorm.Tx
}
varDB*gorm.DB
//db Configuration
funcInitDB(){
dbInfo,_:=revel.Config.String("db.info")
db,err: =gorm.Open("mysql", dbInfo)
if err!=nil{
log.Panicf("Failed gorm.Open:%v\n",err)
}
db.DB()
db.AutoMigrate(&models.Booking{})
db.AutoMigrate(&models.Hotel{})
db.AutoMigrate(&models.User{})
DB = db
}
package controllers
import(
"github.com/revel/revel"
"booking/app/models"
"booking/app/routes"
)
type Application structure {
*revel.Controller
}
func(c Application)Index()level.Result{
if c.connected()!=nil{
return c.Redirect (routes.Hotels.Index())
}
c.Flash.Error("Please log in first")
return c. Render()
}
func(cApplication)connected()*models.User{
if c.ViewArgs["user"]!=nil{
return c.ViewArgs ["user"]. (*models.User)
}
if username, ok: = c. Session ["user" ]; ok{
return c.getUser(username.(string))
}
return nil
}
func(c Application)getUser(username string)(user*models.User){
user=&models.User{}
_,err: =c.Session.GetInto("fulluser", user, false)
if user.Username==username{
return user
}
err=c.Txn.SelectOne(user,c.Db.SqlStatementBuilder.Select("*").From("User").Where("Username=?", username))
if err!=nil{
iferr!=sql.ErrNoRows{
// c.Txn.Select(user, c.Db.SqlStatementBuilder.Select("*").From("User").Limit(1))
count,_:=c.Txn.SelectInt(c.Db.SqlStatementBuilder.Select("count(*)").From("User"))
c.Log.Error("Failed to find user", "user", username, "error", error, "count", count)
}
return nil
}
c. Session ["fulluser"] = user
return
}
func(c Application)Register()level.Result{
return c. Render()
}
If you need the entire code, I'll list it.
I think this Txn method is disturbing.
This is a gorp method, so I think it cannot be used in gorm.
Then, how does gorm work?
I think it is necessary to import the sql package.
https://golang.org/pkg/database/sql/
import "database/sql"
Then, won't it be solved?
© 2024 OneMinuteCode. All rights reserved.