This is the fourth day of my participation in Gwen Challenge

Working environment is mainly Java, I heard Go is pretty fast. A few days ago, I participated in the Dig Go theme month to learn some basic grammar, brush some questions, now I try to use Go web framework to do some basic services.

Go is not always chosen, mainly because other colleagues have written small services with Gin. Therefore, if Gin is good, maybe we can promote it among colleagues. After all, Go is very similar to C, and it is easy to learn.

Information on Gin

Source code address: github.com/gin-gonic/g… Gitee.com/github-imag… (Domestic available)

Official document address: gin-gonic.com/zh-cn/docs/…

Gin keywords: Web framework, Httprouter, fast, support middleware, Crash processing, JSON validation, routing groups, error handling, built-in rendering, extensible lines.

Get started

Gin requires Go 1.13 and above, check the version of Go:

Go Version // output: Go Version go1.16.2 Windows/AMD64Copy the code
The Go-mod method is not supported

Go mod is recommended.

Install imported Gin, NET/HTTP packages

 go get -u github.com/gin-gonic/gin
 // go: downloading xxxx.......
Copy the code

Create the.go code file and copy a template file as per the official tutorial:

curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go
// curl: The term 'curl' is not recognized as a name of a cmdlet, function, script file, or executable program.
// Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Copy the code

Windows Powershell does not support curl, and the official link seems to require Science Network, we manually copy it, main.go code as follows:

package main

import (
	"net/http"

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

var db = make(map[string]string)

func setupRouter(a) *gin.Engine {
	// Disable Console Color
	// gin.DisableConsoleColor()
	r := gin.Default()

	// Ping test
	r.GET("/ping".func(c *gin.Context) {
		c.String(http.StatusOK, "pong")})// Get user value
	r.GET("/user/:name".func(c *gin.Context) {
		user := c.Params.ByName("name")
		value, ok := db[user]
		if ok {
			c.JSON(http.StatusOK, gin.H{"user": user, "value": value})
		} else {
			c.JSON(http.StatusOK, gin.H{"user": user, "status": "no value"})}})// Authorized group (uses gin.BasicAuth() middleware)
	// Same than:
	// authorized := r.Group("/")
	// authorized.Use(gin.BasicAuth(gin.Credentials{
	// "foo": "bar",
	// "manu": "123",
	/ /}))
	authorized := r.Group("/", gin.BasicAuth(gin.Accounts{
		"foo":  "bar".// user:foo password:bar
		"manu": "123".// user:manu password:123
	}))

	/* example curl for /admin with basicauth header Zm9vOmJhcg== is base64("foo:bar") curl -X POST \ http://localhost:8080/admin \ -H 'authorization: Basic Zm9vOmJhcg==' \ -H 'content-type: application/json' \ -d '{"value":"bar"}' */
	authorized.POST("admin".func(c *gin.Context) {
		user := c.MustGet(gin.AuthUserKey).(string)

		// Parse JSON
		var json struct {
			Value string `json:"value" binding:"required"`
		}

		if c.Bind(&json) == nil {
			db[user] = json.Value
			c.JSON(http.StatusOK, gin.H{"status": "ok"})}})return r
}

func main(a) {
	r := setupRouter()
	// Listen and Server in 0.0.0.0:8080
	r.Run(": 8080")}Copy the code

Copy the software package in the corresponding directory to the $GOPATH/ SRC directory according to the code error. Again: Go-mod is more recommended.

The go-mod method is supported

After the CD is in the working directory:

CD D: lean_space\gin // Copy the file go mod init mygin. Web go mod TidyCopy the code

Up and running:

go run main.go
Copy the code

Open postman to get a browser and enter the url: http://localhost:8080/. The following information appears:

404 page not found
Copy the code

We see the following code in the code, guess the route listening path has /ping, as we expected, retrieved the string pong.

r.GET("/ping".func(c *gin.Context) {
		c.String(http.StatusOK, "pong")})Copy the code

We initiate the request as follows:

  1. GET http://localhost:8080/ping return to the pond

  2. POST to http://localhost:8080/admin {that is configured in the header authorization: “Basic Zm9vOmJhcg = =”, the content-type: “Application /json”} postman-body-raw: {“value”:”bar”}

    {
        "status": "ok"
    }
    Copy the code
  3. GET http://localhost:8080/user/foo

    {
        "user": "foo"."value": "bar"
    }
    Copy the code

Test successful!

The console output is as follows:

PS D:\lean_space\gin> go run main.go [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.setupRouter.func1 (3 handlers) [GIN-debug] GET /user/:name --> main.setupRouter.func2 (3 handlers) [GIN-debug] POST /admin --> main.setupRouter.func3 (4 handlers) [GIN-debug] Listening and serving HTTP on :8080 [GIN] 2021/06/03 - 21:35:31 |? [97;42m 200 ?[0m| 0s | ::1 |?[97;46m POST ?[0m "/admin" [GIN] 2021/06/03 - 21:35:35 |?[97;42m 200 ?[0m| 0s | ::1 |?[97;44m GET ?[0m "/ping" [GIN] 2021/06/03 - 21:35:39 |?[97;42m 200 ?[0m| 0s | ::1 |?[97;44m GET ?[0m "/user/foo"Copy the code

/hellogin = /hellogin = /hellogin = /hellogin = /hellogin

r.GET("/hellogin".func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"result": "hello, go-gin! hello go Web!"})})Copy the code

The test results are shown below:

Obviously, r.git (“/ XXX “) means that the method can serve HTTP-GET requests that access path/XXX.

C. JSON indicates that the returned data is in JSON format. Gin supports XML/JSON/YAML/ProtoBuf rendering as well as JSONP, PureJSON, SecureJson, etc.

In gin-gonic.com/zh-cn/docs/…

When you get used to the huge architecture of Java, the experience with Gin is, is this really ok? It’s okay to go into production like this