Home > Article > Backend Development > How to build golang project
In recent years, with the rapid development of the Internet, programming has become a decent and high-paying profession. When it comes to choosing a programming language, more and more people are choosing Golang. So, how to build an efficient and stable Golang framework in the project? This article will provide you with a comprehensive solution.
1. Environment setup
First of all, if you want to build the Golang framework, you must first install the Golang language environment. Download the latest version of Golang from the official website and install it according to the prompts.
After the installation is completed, it is recommended to add %GOPATH% to the system environment variable; then, in order to facilitate the management of the project, we also need to install a package manager-Glide. You can enter the following command in the terminal:
curl https://glide.sh/get | sh
2. Directory structure establishment
After the environment establishment is completed, we need to determine the directory structure of the project first. A clear and orderly directory structure is the soul of a project. It is recommended to use the following directory structure:
- Project - bin - pkg - src - 项目1 - main.go - 其他.go - 项目2 - main.go - 其他.go - 项目3 - main.go - 其他.go - README.md
Among them, the bin directory stores the program executable file; the pkg directory stores the compiled library files; the src directory stores the source code of the project; README.md is the description of the entire project. document.
3. Framework construction
Next, we will start to build the Golang framework. Before building the framework, you need to understand the following:
Here we recommend using the Gin framework and gorm as the main framework and ORM model of the project. The Gin framework is a lightweight Web framework, and gorm is an ORM framework of Golang that provides powerful database operation functions. Next, we will introduce in detail how to use these two frameworks to build a Golang project.
Enter the following command in the terminal to install Gin and gorm:
go get -u github.com/gin-gonic/gin go get -u github.com/jinzhu/gorm
Create a new config.yaml file in the root directory of the project. This file stores various configuration parameters of the project. For example, you can add the following content to this file:
ProjectName: "DemoProject" ListenAddr: ":8080" DebugMode: true Database: Type: "mysql" Host: "localhost" Port: 3306 User: "root" Password: "password" Name: "database_name"
Among them, ProjectName represents the project name; ListenAddr represents the listening address; DebugMode represents whether the debugging mode is turned on; Database represents database-related configuration.
Create a new main.go file in the src directory of the project and write the following code:
package main import ( "fmt" "{{.ImportPath}}/routers" ) func main() { router := routers.InitRouter() port := config.ListenAddr fmt.Printf("Server listening on %s\n", port) router.Run(port) }
Among them, . ImportPath
represents the import path of the project. The routers package is where routing configurations are stored.
Create a new routers folder in the src directory and create a new router.go file. In this file, the routing configuration information will be defined. The code is as follows:
package routers import ( "net/http" "github.com/gin-gonic/gin" "{{.ImportPath}}/controllers" ) func InitRouter() *gin.Engine { r := gin.Default() userCtl := controllers.NewUserController() r.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "Welcome to the home page!") }) r.POST("/users", userCtl.Create) return r }
Among them, the '/' route will return the string "Welcome to the home page!"; the '/users' route is a POST route used to create new users.
Create a modules folder in the src directory and create a user.go file to represent the user's data model. The code is as follows:
package modules type User struct { ID uint `gorm:"primary_key" json:"-"` Name string `gorm:"size:256;not null" json:"name"` }
Create a new controllers folder in the src directory and a new user.go file to implement user-related controllers. The code is as follows:
package controllers import ( "net/http" "github.com/gin-gonic/gin" "{{.ImportPath}}/modules" ) type UserController struct{} func NewUserController() *UserController { return &UserController{} } func (uc *UserController) Create(c *gin.Context) { var user modules.User if err := c.BindJSON(&user); err != nil { c.String(http.StatusBadRequest, "Invalid request payload") return } db.Create(&user) c.JSON(http.StatusCreated, gin.H{"status": http.StatusCreated, "message": "User created successfully", "resourceId": user.ID}) }
UserController is the user controller, and the Create function is used to add a new user model.
Finally, use glide to manage dependency packages. Run the following command:
glide install
Then, enter the main directory of the project and run the following command:
go build
to complete the compilation of the entire project.
4. Summary
This article introduces you how to build a Golang project. First, we need to set up the Golang environment and determine the directory structure of the project. We recommend using Gin and gorm as the main web framework and ORM framework. Finally, we introduced in detail how to build a Golang project from the aspects of establishing routing, writing Model and Controller, and compiling. Hope this article is helpful to you.
The above is the detailed content of How to build golang project. For more information, please follow other related articles on the PHP Chinese website!