table of Contents
Outline
I would like to achieve a wheel out of the box ready to use the API framework, based on this wheel is developed on the basis of Gin.
Why is it out of the box, what features it will integrate?
More function points are commonly used, the latter may also increase.
Ado, let's get started.
Create a project, we must first consider a dependent package management tool.
There are common package management, dep, go vendor, glide, go modules and so on.
Initially, used dep, was then diss a friend recommended I use go modules.
Now it is about go modules, this is with the release of Go 1.11 and we met, this is a new package management official advocated.
He said an environment variable: GO111MODULE, the default is auto.
When the project has go.mod, go modules use management, and vice versa using the old GOPATH and vendor mechanisms.
If you want to use go modules, you can be GO111MODULE set to on.
Direct it to get started.
initialization
We place outside GOPATH, and create a new empty folder go-gin-api
.
cd go-gin-api && go mod init go-gin-api
Output:
go: creating new go.mod: module go-gin-api
Then one more go.mod file directory, as follows:
module go-gin-api
go 1.12
With this, go mod initialization is complete, then add dependencies - gin.
Add dependencies
Create a directory in main.go
a file, put the following code:
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}
This code is nothing special, is the official entry of Demo.
Next, start downloading dependencies.
go mod tidy
After execution, look at the go.mod
file:
module go-gin-api
go 1.12
require github.com/gin-gonic/gin v1.4.0
At this time, a gin v1.4.0 see the new package.
Go.sum also generates a file, this file can hold that thought.
Then found two problems.
1, the directory not found gin package, where the package download?
Downloaded to GOPATH / pkg / mod directory.
2, GoLand editor on the reference Gin turned red?
Here the editor need to set up, as shown:
Click Apply and OK to.
If this does not work, you can perform:
go mod vendor
This command is the project dependent packages, vendor directory into the project, it is certainly it.
go mod command
go mod tidy
Pulling the missing module, remove unused modules.
I used this command.
go mod vendor
Will depend copied to the vendor.
I used this command.
go mod download
Download dependencies.
go mod verify
Inspection dependence.
go mod graph
Printing module dependency diagram.
Other commands can be executed go mod
, you can view.
summary
This article, shared use of go modules.
- Use go modules to build a project from scratch.
- GoLand Editor go modules.
Today, on this, and began to build the next article API project, and write parameter validation.