Golang Beego use models in your controllers
This post is meant to guide you on how to use models inside your controllers, not using the ORM way. Meaning you can implement your own reusable functions, another way of handeling your queries and even better, choose another database besides MySQL, Sqlite, PostgreSQL which ORM only supports.
Assuming you have everything setup and ready to Go.
Create a model
Simply create a file under your BeegoProject/models/ folder, let's say user.go
package models
func GetUserNameById(UserID int) string {
// Put database logic here
// Return value is just a stub
return "DatabaseResult"
}
The package should be 'models'.
Create or edit your controller.
Now to use the model you should import it into your controller file.
import (
"BeegoProject/models"
//The other imports
...
)
And now you can access your model inside the controllers by simply calling upon:
UserID := models.GetUserNameById(123456789)
Creating a single connection to your database
Now you are probably meaning to use a database, so you'll need to create a connection. However you don't want that your application creates a new connection every time a page request/controller is called upon. So you'll want a single connection that is maintained over the duration of your running application.
In order to do so we'll need a variable in your model file that contains the connection or collection to your desired database, and a 'init()' function that establishes the connection upon starting your application.
For example for Cassandra using the gocql package we'll add the following lines in your model:
var CassandraSession *gocql.Session
func init(){
//Open cassandra connection
cluster := gocql.NewCluster("localhost")
cluster.Keyspace = "mykeyspace"
cluster.Consistency = gocql.One
cluster.ProtoVersion = 4
CassandraSession, _ = cluster.CreateSession()
}
The init function gets called automatically whenever your Beego starts running, before the main function. Note that you can only have one init function per package and only one main function per program.
Now you can use the CassandraSession variable to do queries on inside your functions of the models package.