Introduction of Gin
Gin is a Web framework in go language. It is very small. As of version 1.4.0, the source code of the whole framework is only about 5K.
Gin features
- Fast: Routing does not use reflection, Radix tree based, small memory footprint
- Stability: New releases do not break your code
- Support for middleware: Incoming HTTP requests can be handled by a series of middleware and end operations
Gin also has some unreasonable aspects, such as the unreasonable implementation of context. context interface.Context non-interface cannot be extended. The registration of validators is not reasonable, different gin versions may be registered in different versions, etc. It is becoming more and more complex, but for frameworks, it is more important to have more users.
Install Go&Gin
Before installing Go, let’s take a look at the release strategy for the Go language.
The Go team kept the pace of release releases steady at two major releases per year. The Go team promised that the latest major release would be compatible with previous releases, so we didn’t have to worry about compatibility issues with new releases. In general, we can Go with the latest version, because the Go team’s code quality is consistently high with few major bugs. Some open source projects will be available soon after the latest release of Go, such as Kubernetes; Other open source projects, like Docker, are more cautious.
I choose the latest release of Go, Go 1.16.5. Go supports most major operating systems. Next, I will describe the installation and configuration of different operating systems in detail.
Install Go on Linux/Ubuntu
Download and unpack the Go Linux installation package:
C $wget - https://golang.google.cn/dl/go1.16.5.linux-amd64.tar.gzCopy the code
Decompress the downloaded Go installation package to the installation directory:
$tar -c /usr/local-xzf go1.16.5.linux-amd64.tar.gz $tar -c /usr/local-xzf go1.16.5.linux-amd64.tar.gzCopy the code
After executing the decompression command, we can see the go named directory in /usr/local, which is the official recommended installation directory of Go. To make the go command available in any path, we add the folder where the go binaries are located to the environment variable PAHT:
export PATH=$PATH:/usr/local/go/bin
Copy the code
Execute the following command for the environment variable to take effect immediately:
$ source ~/.profile
Copy the code
Verify the successful installation:
$go Version # go version go1.16.5Copy the code
Install Go on your Mac
On Mac, it can be installed via Homebrew:
I will not expand Homebrew, it is like an installation file manager, easy to install, view, uninstall your application, highly recommended.
The brew install [email protected]Copy the code
To set the environment variable, add GOPATH to ~/.bashrc:
$ vim ~/.bashrc
export GOPATH=~/go
export PATH=$PATH:$GOPATH/bin
Copy the code
Once added, execute the following command for the environment variable to take effect:
$ source ~/.bashrc
Copy the code
Verify the successful installation:
$ go version
# go version go1.16.6 darwin/amd64
Copy the code
Install Go on Windows
On Windows, you can install Go with a graphical interface boot.
Go to the Go installation package download page, find the AMD64 architecture Go 1.16.5 Windows MSI installation package and download it.
The installer will install Go under C: Program Files\Go by default, and the Go installer will automatically set the user environment variables required by Go. We can use Go command in any path, open the terminal to verify whether Go is successfully installed:
$go Version # Go Version go1.16.5 Windows/AMD64Copy the code
Due to the domestic network environment, we can configure GOPROXY to avoid the slow or failure of module pulling caused by DNS pollution and speed up your construction.
$go env -w GOPROXY=goproxy.cn,direct
Install the Gin
$ go get -v -u github.com/gin-gonic/gin
Copy the code
-v: Prints the name of the code package to be built
-u: Forces the update of the code package and dependent package if any exists
Write an HTTP server with Gin
To create a folder anywhere, first we initialize a go.mod file that manages components that Go depends on, component versions, and so on:
$ go mod init
Copy the code
Create main.go file in this folder:
$ touch main.go
$ vim main.go
Copy the code
Add the following to the main.go file:
package main
import "github.com/gin-gonic/gin"
func main(a) {
r := gin.Default()
r.GET("/".func(c *gin.Context) {
c.String(200."Hello, World")
})
r.Run("0.0.0.0:80")}Copy the code
- We use the
gin.Default()
An instance is generated - To use
r.Get("/", ...)
What happens when you declare a route and access the route, which is access/
“, will printHello, World
- Finally, r.run () is used to start the program and specify port 80. Let’s run it:
$ go run main.go
[GIN-debug] GET / --> main.main.func1 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on 0.0.0.0:80
Copy the code
Using curl to access local port 80
$ curl http://localhost:80
Hello, World
Copy the code
Install the Docker
Docker can be installed on 64-bit x86 platforms or ARM platforms. In the Ubuntu distribution, long-term Support (LTS) is supported for 5 years of upgrade and maintenance, and the version is more stable. Therefore, you are advised to use LTS in the production environment.
Install Docker on Ubuntu
Apt source uses HTTPS to ensure that the software download process will not be tampered with, so we need to add HTTPS software package and CA certificate first:
$ sudo apt-get update
$ sudo apt-get install \
apt-transport-https \
ca-certificates \
curl \
gnupg-agent \
software-properties-common
Copy the code
Due to domestic environmental problems, use domestic sources instead. To verify the validity of the downloaded package, we also need to add the key of the software source:
$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
Copy the code
Add Docker software source:
$ sudo add-apt-repository \
"deb [arch=amd64] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) \
stable"
Copy the code
Update apt software package and install docker:
$ sudo apt-get update
$ sudo apt-get install docker-ce docker-ce-cli containerd.io
Copy the code
Install Docker on other operating systems
Due to space problems, Docker installation will not be expanded, you can get the installation method from the open source book.
Making container Images
Create a Dockerfile container image in the main.go directory as follows:
# Use the official Go development image as the base image
FROM golang:1.17
Change the working directory to /demo
WORKDIR /demo
Copy the contents of the current directory to /demo
ADD . /demo
# Enable the GO MOD to install Gin dependencies required for HTTP
RUNgo env -w GO111MODULE=on &&\ go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/,direct
Allow external access to port 80 of the container
EXPOSE 80
Run the HTTP instance in this container
CMD ["go"."run"."main.go"]
Copy the code
In this file, we can see that Dockerfile uses some standard source words (capitalized words, such as FROM) to describe a Docker image. These commands are processed sequentially FROM top to bottom, and the contents of Dockerfile are mainly presented in two forms, one is the comment line. The other is the instruction line.
Next, we can tell Docker to make the image in the current directory:
docker build -t go-http-demo .
Copy the code
-t: Specifies a name for the mirror.
Docker build automatically loads the Dockerfile file in the current directory and executes the commands in the file.
After each primitive in docker build is executed, a corresponding image layer is generated. When done, you can view the results using the Docker images command:
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
go-http-demo latest ac2608f814a4 26 hours ago 941MB
Copy the code
Using this image ID, you can view the files and directories of the new layer in the overlay2 path.
Next, start the container with the docker run command:
$ docker run -p 4000:80 go-http-demo
Copy the code
We specify CMD in the Dockerfile, otherwise we need to load the process start command after:
$ docker run -p 4000:80 go-http-demo go run main.go
Copy the code
After the container is started, you can use the docker ps command to see:
$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 40a5676ed61a go-http-demo "go run main.go" 26 hours Ago Up 26 hours 0.0.0.0:4000->80/ TCP relaxed_wingCopy the code
Meanwhile, we have told Docker through -P 44:80 to map port 80 in the container to port 4000 of the host. The purpose of this is to access port 4000 of the host and see the result returned by the application in the container:
$ curl http://localhost:4000
Hello, World
Copy the code
At this point, we have completed the installation of Go, Docker, Gin HTTP server written by Go, and deployed by container.