“This is the 13th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

directory

  • preface
  • The body of the
  • At the end

preface

Gin is an HTTP Web framework implemented using the pure Golang language. Gin is now widely used for its simple interface design and high performance. Our Web back-end services are basically developed based on Gin.

The body of the

The installation

To use the Gin framework for the first time, you need to install the Gin framework as follows:

go get -u github.com/gin-gonic/gin

The following error message may appear:

# cd .; git clone -- https://github.com/gin-contrib/sse /Users/lz/go/src/github.com/gin-contrib/sse
Cloning into '/Users/lz/go/src/github.com/gin-contrib/sse'.fatal: unable to access 'https://github.com/gin-contrib/sse/': LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443
package github.com/gin-contrib/sse: exit status 128
Copy the code

It is usually a network problem. You can try again.

use

Before using Gin’s library, import the dependency library as follows:

import "github.com/gin-gonic/gin"
Copy the code

Specific use is as follows:

r := gin.Default()
Copy the code

Examples demonstrate

Write a sample code:

package main

import "github.com/gin-gonic/gin"

func main(a) {
	r := gin.Default()
	r.GET("/ping".func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.Run()
}
Copy the code

As you can see from the code, we have defined a service interface whose API is /ping.

Then we compile the code with the command:

go build

After the compilation is successful, the executable program gin-Demo is generated and the executable program is run as follows:

liuzhen-3:gin-demo lz$ ./gin-demo
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:	export GIN_MODE=release
 - using code:	gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /ping                     --> main.main.func1 (3 handlers)
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080
Copy the code

From the log, we can see that the service started port 8080 by default.

Next, let’s test the service by typing the following address into your browser:

http://localhost:8080/ping

The running results are as follows:

The results show that the service is normal.

At the end

To sum up, the Gin framework is very simple to use and easy to get started. If you are interested, try it yourself! We will continue our in-depth analysis of the source code of the Gin framework. Stay tuned!

About the author: Hello, everyone, I am Liuzhen007, an audio and video technology fan, CSDN blog expert, Huawei Cloud community cloud sharing expert, signed the author, welcome to follow me to share more dry products!