Go 言語 GIN フレームワークのインストールと開始

Go 言語 GIN フレームワークのインストールと開始


前に 1 週​​間 GO 言語を勉強し、GO 言語の基礎を学んだので、現在は GO 言語の最も人気のあるフレームワークである GIN を使用して、いくつかの簡単なインターフェイスを作成しようとしています。Station B の GIN 紹介ビデオを見て、インターフェイスの書き方を基本的に理解したので、以下に基本的な手順を記録します。

1. 構成環境を作成する

最初の新しい開発環境の作成には Goland を使用しますが、Windows に Go 言語がインストールされていれば、Goroot が自動的に認識します。
ここに画像の説明を挿入します
新しいプロジェクトには、プロジェクトで使用されるサードパーティ ライブラリを示すために使用される go.mod ファイルが 1 つだけあります。
ここに画像の説明を挿入します

2. 環境を構成する

サードパーティのライブラリを使用する場合、github からダウンロードする必要がありますが、github は接続に失敗することが多いため、最初にサードパーティのプロキシ アドレスを設定する必要があります。[設定] -> [移動] -> [Go モジュール] -> [環境] にプロキシ アドレスを追加します。

GOPROXY=https://goproxy.cn,direct

ここに画像の説明を挿入します

3.最新バージョンのGinをダウンロードします。

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. まとめ

以上がジンを始めるための内容となりますので、参考になった方はぜひ「いいね」や「収集」をお願いいたします。

おすすめ

転載: blog.csdn.net/HELLOWORLD2424/article/details/132333923