Home > Article > Backend Development > How to build web applications using golang
In recent years, the Go language (golang for short) has gradually become the darling of the web development field because of its efficiency, simplicity, and concurrency safety. Golang is easy to learn and use, and has a huge base of libraries and frameworks. This article will introduce how to use golang to build web applications, including routing settings, template processing, ORM, etc.
Go language is a compiled language, which is influenced by C language and Pascal language. It has static typing, garbage collection, concurrent programming and Asynchronous programming and other features. Golang's standard library provides a wealth of functions, including networking, encryption and decryption, input and output, and more. Moreover, Golang's concurrency model has unique advantages, making it very suitable for the field of web development.
Building a Web application using Golang requires the following components:
Next we will use the Gin framework to create a simple web application and introduce how the above components are used in it.
First, we need to install the Gin framework using the following command:
go get -u github.com/gin-gonic/gin
This command will download the Gin framework source code from Github, And install it into the $GOPATH/src/github.com/gin-gonic/gin directory.
Creating a route is an important step in a web application because it defines the mapping relationship between URLs and corresponding processing functions.
In this example, we will create two routes:
In the main.go file, we can define these two routes:
package main import ( "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "Welcome to our website!", }) }) r.GET("/hello", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "Hello there!", }) }) r.Run(":8080") }
In order to create the route, we use the Default() function of the Gin framework to create a default route processing engine, and then use the GET() function on the routing engine to define the route.
Now we have created two routes and corresponding processing functions, but the return values of these functions are data in JSON format, not pages.
In order to embed this data into HTML pages, we need to use a template engine. Golang has many different template engines to choose from, including Go's native text/template and html/template, as well as third-party libraries.
In this example, we will use the third-party library Gin Template. To do this, we need to create a templates directory and create two template files welcome.html and hello.html in it:
$ mkdir templates $ cd templates $ touch welcome.html hello.html
In these two template files, we will use the go language template engine ({{.}}
) Embed the corresponding variables into the HTML page. In welcome.html, we will add a simple welcome page:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Welcome to our website!</title> </head> <body> <h1>Welcome to our website!</h1> </body> </html>
In hello.html, we will add another simple page:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello there!</title> </head> <body> <h1>Hello there!</h1> </body> </html>
Now we are ready to use Gin Template embeds these two template files into our routing processing function.
In the main.go file, we will add the following code:
import ( "net/http" ) // ... func main() { r := gin.Default() // 模板设置 r.LoadHTMLGlob("templates/*") r.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "welcome.html", gin.H{ "title": "Welcome", }) }) r.GET("/hello", func(c *gin.Context) { c.HTML(http.StatusOK, "hello.html", gin.H{ "title": "Hello", }) }) r.Run(":8080") }
Here, we use the LoadHTMLGlob() function provided by the Gin framework to load the template file. Then, in the routing processing function, we use the c.HTML() function to merge the template file and corresponding data together to render the page.
In a web application, data needs to be stored in a persistent storage device. ORM (Object Relational Mapping) is a tool that allows developers to map tables and data in a database to objects and classes in a program.
In this example, we will use the gorm ORM library to connect to the database and perform CRUD (create, read, update, and delete) operations.
First, we need to install the gorm library using the following command:
go get -u github.com/jinzhu/gorm
Next, we can use the gorm library to perform various database operations in the program. For example, we can create a struct named User and store it in the database:
import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) type User struct { gorm.Model Name string Age int } // ... func main() { // 连接MySQL数据库 db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local") if err != nil { panic("failed to connect database") } defer db.Close() // 创建数据库表 db.AutoMigrate(&User{}) // 新增一条数据 db.Create(&User{Name: "张三", Age: 30}) }
Here, we create a struct named User and use the Gorm library's AutoMigrate() The function creates a table named users in the database. We then added a new user to the database using the db.Create() function.
In this article, we introduced how to create web applications using Golang. We used Gin as the web framework and used the template engine Gin Templae to display HTML pages. We also used the Gorm ORM library to connect to the database and perform various CRUD operations.
The lightweight, efficient and safe features of Go language make it the best choice for web development. Web development becomes easier and more efficient using Golang and corresponding frameworks and libraries.
The above is the detailed content of How to build web applications using golang. For more information, please follow other related articles on the PHP Chinese website!