The previous article briefly covered the technology stack selection and how to initialize a Web project, project directory, etc. This article will cover the configuration of routing and how to connect to a database and use XORM.

The routing configuration

The previous chapter described using GIN to create an initial Web project. For now, we will use the routing mechanism provided by GIN for configuration. Add in main.go:

The main. Go:

package main import ( "io" "os" "github.com/gin-gonic/gin" "github.com/zachrey/blog/routers" ) func main() { r := Gin.New() // Set log file f, _ := os.create ("gin. Log ") gin. Os.stdout) // Use the logging middleware r.US (gin.Logger()) // set the static folder r.static ("/static", "./static") // LoadRouters.LoadRouters(r).Copy the code

LoadRouters, we put these functions under the routers/ packages to allow all routers to be managed at the same time.

Routers/router. Go:

package routers import ( "log" "net/http" "github.com/gin-gonic/gin" // ctrs "github.com/zachrey/blog/controllers" ) // Router func LoadRouters(Router *gin.Engine) {LoadRouters(router)} Func LoadRouters(Router *gin.Engine) {// Here the test root route /* The controller function receives a pointer of type 'gin.Context', which contains HTTP request and response information and operation methods. */ router.GET("/", func(c *gin.Context) { post := models.GetPostByID(1) log.Println("@@ post", C. Json (http.statusok, gin.H{"Status": 0, "data": Ctrs.getposts ("/ GetPosts ", ctrs.getposts) //...... Lots and lots of routes... }Copy the code

Ctrs. GetPosts is the controller function, and then we’ll demonstrate it with the database. Now start the project go Run main.go and go to localhost:8888/ in your browser to see what the root route returns.

Connecting to a Database

Since personal blogging is not very complex, a lightweight database like SQLite is used directly here. GO does not have a built-in database driver, but GO defines the database driver package interface database/ SQL /driver, so even for different databases, you can develop your own driver package based on these interfaces. So, to connect to the SQLite database, we need to look for the SQLite data driver package.

github.com/mattn/go-sqlite3
Copy the code

The above is the address of the driver package that needs to be used, just import the initialization in the project.

List of other driver packages: github.com/golang/go/w…

Initialize (import) the database driver in the project entry file main.go:

The main. Go:

Package main import (" IO "" OS" "github.com/gin-gonic/gin" _ "github.com/mattn/go-sqlite3") Func main() {r := gin.New()... r.Run(":8888") }Copy the code

After initializing the database, in the Database directory, create a database configuration file and use XORM to connect to the database.

The database/sqlite3. Go:

Package database import ("log" "github.com/xormplus/xorm" // remember to go get ") // ORM xorm engine instance, for other modules can be used directly, note ** first letter **, Because of the 'Go' speech hiding and disclosure rules, upper case for public, lower case for hidden. Var ORM * xorm.engine func init() {var ORM * xorm.engine func init() { Var err Error ORM, err = xorm.NewEngine("sqlite3", "./database/test.db") if err! = nil {log.fatalln (err) return} err = orm.ping () if err! = nil {log.fatalln (err) return} ORM.ShowSQL(true)Copy the code

The above xORM operation, it is recommended to see the official documentation. I have a ready-made test database file on Github, that is, the database file of this blog system, you can download it and connect to try. Let’s see if there’s an error, if the ping can work. /database/test.db, the relative path, because I put the test.db file in the same directory as the sqlite3.go configuration file, if you create an engine like this./test.db, Instead of pointing to the /database/test.db file, it points to /test.db in the project root directory, creating a new empty /text.db file. Because the Go language manages projects in packages, the./ represents the sibling directory of the package, not the sibling directory of the files in the package.

Create an ORM template

All templates are placed under models. Each model corresponds to a table in the database. We can use sqLite database connection tool to see which tables and specific fields are in test.db.

Models/post. Go:

Package models import (" log "db" github.com/zachrey/blog/database "/ / import the previously created database engine as an example, Type MPost struct {Id int64 'xorm:"pk autoincr"' Title 'string xorm:"' Title '"' FileName string `xorm:"file_name"` TextAmount int64 `xorm:"text_amount"` CreateTime int64 `xorm:"created 'create_time'"` } // Func GetPostByID(ID int64) *MPost {var post MPost; err := db.ORM.Table("posts").Id(Id).Get(&post) if err ! = nil { log.Println("ERROR:", Err) return nil} if has == false {return nil} return &post} // GetPosts get all posts func GetPosts() *[]MPost {var post []MPost err := db.ORM.Table("posts").Find(&post) if err ! = nil { log.Println("ERROR:", err) return nil } return &post }Copy the code

Structs are used to correspond to tables in the database, types of fields in the table, constraints, etc. Note that structure attributes start with uppercase letters, depending on the case. If the structure needs to be accessed, it is best to miswrite all uppercase letters. For the type mapping, you can see the “Go and Field Type mapping table” directory on the official website, which will provide detailed instructions. Xorm :” PK autoincr” is called a Tag. For details about the Tag rules, see the “Column attribute Definition” directory on the website.

Use the methods on the template in the controller

All the controllers are placed under controllers.

/ controllers/posts. Go:

package controllers import ( "log" "net/http" "github.com/gin-gonic/gin" "github.com/zachrey/blog/models" ) //GetPosts Func GetPosts(c *gin.Context) {labels := models.getposts () // use the method written in the template. gin.H{ "status": 0, "data": labels, }) }Copy the code

Use controllers in routing

Routers/router. Go:

package routers import ( "log" "net/http" "github.com/gin-gonic/gin" ctrs "github.com/zachrey/blog/controllers" ) // Router func LoadRouters(Router *gin.Engine) {LoadRouters(router)} Func LoadRouters(Router *gin.Engine) {// Here the test root route /* The controller function receives a pointer of type 'gin.Context', which contains HTTP request and response information and operation methods. */ router.GET("/", func(c *gin.Context) { post := models.GetPostByID(1) log.Println("@@ post", C. Json (http.statusok, gin.H{"Status": 0, "data": Ctrs.getposts ("/ GetPosts ", ctrs.getposts) //...... Lots and lots of routes... }Copy the code

Now let’s go to localhost:8888/get-posts and see the json array returned.

The last

The example project has been written and posted on Github. This second article covers configuring routing and using XORM to manipulate the database. Feel free to discuss or leave a comment, or just run through the clone project on github. Continue to update the problems encountered and some solutions.