Go language GIN framework installation and getting started

Go language GIN framework installation and getting started


I studied GO language for a week before and learned the basics of GO language. Now I am trying to use GIN, the most popular framework of GO language, to write some simple interfaces. After watching the GIN introductory video from Station B, I basically understand how to write an interface. I will record the basic steps below.

1. Create a configuration environment

We use Goland to create the first new development environment. As long as the Go language is installed under windows, Goroot will automatically recognize it.
Insert image description here
The new project only has one go.mod file, which is used to indicate the third-party libraries used in the project.
Insert image description here

2. Configure the environment

When we use third-party libraries, we need to download them from github, but github often fails to connect, so we need to configure the third-party proxy address first. We add the proxy address under Settings->Go->Go Modules->Environment.

GOPROXY=https://goproxy.cn,direct

Insert image description here

3. Download the latest version of Gin

Install the Gin framework under the Terminal in the IDE, and use the following command to install Gin. After the installation is complete, dependencies will be added automatically under require under go.mod.

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

Insert image description here

4. Write the first interface

Create the main.go file, and then write the following code, which defines a /hello route.

package main

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

func main() {
    
    

	ginServer := gin.Default()
	ginServer.GET("/hello", func(context *gin.Context) {
    
    
		context.JSON(200, gin.H{
    
    "msg": "hello world"})
	})

	ginServer.Run(":8888")

}

Compile and run and access it through a browser to output JSON.

Insert image description here

5. Static page and resource file loading

Use the following code to add the static pages (HTML files) and dynamic resources (JS) under the project.

	// 加载静态页面
	ginSever.LoadHTMLGlob("templates/*")

	// 加载资源文件
	ginSever.Static("/static", "./static")

This is the resource file list of the project.
Insert image description here
The index.html file is as follows

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>我的第一个GO web页面</title>
    <link rel="stylesheet" href="/static/css/style.css">
    <script src="/static/js/common.js"></script>
</head>
<body>

<h1>谢谢大家支持</h1>

获取后端的数据为:
{
   
   {.msg}}

<form action="/user/add" method="post">
        <p>username: <input type="text" name="username"></p>
        <p>password: <input type="text" name="password"></p>
        <button type="submit"> 提 交 </button>
</form>


</body>
</html>

Then you can respond to a page to the front end.

	// 响应一个页面给前端
	ginSever.GET("/index", func(context *gin.Context) {
    
    
		context.HTML(http.StatusOK, "index.html", gin.H{
    
    
			"msg": "这是go后台传递来的数据",
		})
	})

Insert image description here

6. Various parameter transmission methods

6.1 URL parameter passing

Get the parameters passed by the URL on the backend.

	// 传参方式
	//http://localhost:8082/user/info?userid=123&username=dfa
	ginSever.GET("/user/info", myHandler(), func(context *gin.Context) {
    
    
		// 取出中间件中的值
		usersession := context.MustGet("usersession").(string)
		log.Println("==========>", usersession)

		userid := context.Query("userid")
		username := context.Query("username")
		context.JSON(http.StatusOK, gin.H{
    
    
			"userid":   userid,
			"username": username,
		})
	})

An additional intermediate key is added above, which is the code executed before the interface code is run. The definition of myHandler is as follows:

// go自定义中间件
func myHandler() gin.HandlerFunc {
    
    
	return func(context *gin.Context) {
    
    
		// 设置值,后续可以拿到
		context.Set("usersession", "userid-1")
		context.Next() // 放行
	}
}

6.2 Passing parameters in routing form

	// http://localhost:8082/user/info/123/dfa
	ginSever.GET("/user/info/:userid/:username", func(context *gin.Context) {
    
    
		userid := context.Param("userid")
		username := context.Param("username")
		context.JSON(http.StatusOK, gin.H{
    
    
			"userid":   userid,
			"username": username,
		})
	})

6.3 The front end passes JSON format to the back end

	// 前端给后端传递json
	ginSever.POST("/json", func(context *gin.Context) {
    
    
		// request.body
		data, _ := context.GetRawData()
		var m map[string]interface{
    
    }
		_ = json.Unmarshal(data, &m)
		context.JSON(http.StatusOK, m)

	})

6.4 Passing parameters in form

	ginSever.POST("/user/add", func(context *gin.Context) {
    
    
		username := context.PostForm("username")
		password := context.PostForm("password")
		context.JSON(http.StatusOK, gin.H{
    
    
			"msg":      "ok",
			"username": username,
			"password": password,
		})
	})

7. Routing and routing groups

	// 路由
	ginSever.GET("/test", func(context *gin.Context) {
    
    
		context.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
	})

	// 404
	ginSever.NoRoute(func(context *gin.Context) {
    
    
		context.HTML(http.StatusNotFound, "404.html", nil)
	})

	// 路由组
	userGroup := ginSever.Group("/user")
	{
    
    
		userGroup.GET("/add")
		userGroup.POST("/login")
		userGroup.POST("/logout")
	}

	orderGroup := ginSever.Group("/order")
	{
    
    
		orderGroup.GET("/add")
		orderGroup.DELETE("delete")
	}

8. Project code main.go

package main

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

// go自定义中间件
func myHandler() gin.HandlerFunc {
    
    
	return func(context *gin.Context) {
    
    
		// 设置值,后续可以拿到
		context.Set("usersession", "userid-1")
		context.Next() // 放行
	}
}

func main() {
    
    
	// 创建一个服务
	ginSever := gin.Default()
	//ginSever.Use(favicon.New("./icon.png"))

	// 加载静态页面
	ginSever.LoadHTMLGlob("templates/*")

	// 加载资源文件
	ginSever.Static("/static", "./static")

	//ginSever.GET("/hello", func(context *gin.Context) {
    
    
	//	context.JSON(200, gin.H{"msg": "hello world"})
	//})
	//ginSever.POST("/user", func(c *gin.Context) {
    
    
	//	c.JSON(200, gin.H{"msg": "post,user"})
	//})
	//ginSever.PUT("/user")
	//ginSever.DELETE("/user")

	// 响应一个页面给前端
	ginSever.GET("/index", func(context *gin.Context) {
    
    
		context.HTML(http.StatusOK, "index.html", gin.H{
    
    
			"msg": "这是go后台传递来的数据",
		})
	})

	// 传参方式
	//http://localhost:8082/user/info?userid=123&username=dfa
	ginSever.GET("/user/info", myHandler(), func(context *gin.Context) {
    
    
		// 取出中间件中的值
		usersession := context.MustGet("usersession").(string)
		log.Println("==========>", usersession)

		userid := context.Query("userid")
		username := context.Query("username")
		context.JSON(http.StatusOK, gin.H{
    
    
			"userid":   userid,
			"username": username,
		})
	})

	// http://localhost:8082/user/info/123/dfa
	ginSever.GET("/user/info/:userid/:username", func(context *gin.Context) {
    
    
		userid := context.Param("userid")
		username := context.Param("username")
		context.JSON(http.StatusOK, gin.H{
    
    
			"userid":   userid,
			"username": username,
		})
	})

	// 前端给后端传递json
	ginSever.POST("/json", func(context *gin.Context) {
    
    
		// request.body
		data, _ := context.GetRawData()
		var m map[string]interface{
    
    }
		_ = json.Unmarshal(data, &m)
		context.JSON(http.StatusOK, m)

	})

	// 表单
	ginSever.POST("/user/add", func(context *gin.Context) {
    
    
		username := context.PostForm("username")
		password := context.PostForm("password")
		context.JSON(http.StatusOK, gin.H{
    
    
			"msg":      "ok",
			"username": username,
			"password": password,
		})
	})

	// 路由
	ginSever.GET("/test", func(context *gin.Context) {
    
    
		context.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
	})

	// 404
	ginSever.NoRoute(func(context *gin.Context) {
    
    
		context.HTML(http.StatusNotFound, "404.html", nil)
	})

	// 路由组
	userGroup := ginSever.Group("/user")
	{
    
    
		userGroup.GET("/add")
		userGroup.POST("/login")
		userGroup.POST("/logout")
	}

	orderGroup := ginSever.Group("/order")
	{
    
    
		orderGroup.GET("/add")
		orderGroup.DELETE("delete")
	}

	// 端口
	ginSever.Run(":8888")

}

9. Summary

The above is all the content for getting started with Gin. If you find it helpful, please like and collect it.

Guess you like

Origin blog.csdn.net/HELLOWORLD2424/article/details/132333923