Go 언어 GIN 프레임워크 설치 및 시작하기

Go 언어 GIN 프레임워크 설치 및 시작하기


일주일 전에 GO 언어를 공부하고 GO 언어의 기초를 배웠고, 이제는 GO 언어의 가장 인기 있는 프레임워크인 GIN을 사용하여 간단한 인터페이스를 작성하려고 합니다. Station B의 GIN 소개 영상을 보고 기본적으로 인터페이스 작성 방법을 이해하게 되었으며, 기본적인 단계를 아래에 기록해 놓겠습니다.

1. 구성 환경 만들기

우리는 Goland를 사용하여 최초의 새로운 개발 환경을 만들고, Windows에 Go 언어가 설치되어 있으면 Goroot가 자동으로 이를 인식합니다.
여기에 이미지 설명을 삽입하세요.
새 프로젝트에는 프로젝트에 사용되는 타사 라이브러리를 나타내는 데 사용되는 go.mod 파일이 하나만 있습니다.
여기에 이미지 설명을 삽입하세요.

2. 환경 구성

타사 라이브러리를 사용하려면 github에서 다운로드해야 하는데 github에서 연결이 안되는 경우가 많기 때문에 먼저 타사 프록시 주소를 구성해야 합니다. 설정->Go->Go 모듈->환경 아래에 프록시 주소를 추가합니다.

GOPROXY=https://goproxy.cn,direct

여기에 이미지 설명을 삽입하세요.

3. 최신 버전의 진을 다운로드하세요

IDE의 터미널 아래에 Gin 프레임워크를 설치하고, 다음 명령을 사용하여 Gin을 설치하면 설치가 완료된 후 go.mod 아래의 require 아래에 종속 항목이 자동으로 추가됩니다.

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

여기에 이미지 설명을 삽입하세요.

4. 첫 번째 인터페이스 작성

main.go 파일을 생성한 후 /hello 경로를 정의하는 다음 코드를 작성합니다.

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")

}

컴파일하고 실행하고 브라우저를 통해 접근하여 JSON을 출력합니다.

여기에 이미지 설명을 삽입하세요.

5. 정적 페이지 및 리소스 파일 로딩

다음 코드를 사용하여 프로젝트 아래에 정적 페이지(HTML 파일) 및 동적 리소스(JS)를 추가합니다.

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

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

해당 프로젝트의 리소스 파일 목록이며,
여기에 이미지 설명을 삽입하세요.
index.html 파일은 다음과 같습니다 .

<!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>

그런 다음 프런트 엔드에서 페이지에 응답할 수 있습니다.

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

여기에 이미지 설명을 삽입하세요.

6. 다양한 파라미터 전송 방식

6.1 URL 매개변수 전달

백엔드에서 URL로 전달된 매개변수를 가져옵니다.

	// 传参方式
	//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,
		})
	})

위에 추가된 중간 키는 인터페이스 코드가 실행되기 전에 실행되는 코드이며, myHandler의 정의는 다음과 같습니다.

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

6.2 라우팅 형식으로 매개변수 전달하기

	// 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 프런트엔드는 JSON 형식을 백엔드에 전달합니다.

	// 前端给后端传递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 양식에 매개변수 전달하기

	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. 라우팅 및 라우팅 그룹

	// 路由
	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. 프로젝트 코드 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. 요약

이상이 Gin을 시작하기 위한 모든 컨텐츠입니다. 도움이 되셨다면 좋아요와 좋아요 부탁드립니다.

추천

출처blog.csdn.net/HELLOWORLD2424/article/details/132333923