gin框架簡介


介紹

Gin是一個golang的微框架,封裝比較優雅,API友好,源碼注釋比較明確,具有快速靈活,容錯方便等特點
對於golang而言,web框架的依賴要遠比Python,Java之類的要小。自身的net/http足夠簡單,性能也非常不錯
借助框架開發,不僅可以省去很多常用的封裝帶來的時間,也有助於團隊的編碼風格和形成規范

安裝

要安裝Gin軟件包,您需要安裝Go並首先設置Go工作區。

1.首先需要安裝Go(需要1.10+版本),然后可以使用下面的Go命令安裝Gin。

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

2.將其導入您的代碼中:

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

3.(可選)導入net/http。例如,如果使用常量,則需要這樣做http.StatusOK。

import "net/http"

Hello World

  • main.go
package main

import (
	"common_standard_library/controller"
	"github.com/gin-gonic/gin"
)

func main() {
	// 創建路由
	router := gin.Default()

	router.Use(setUserName)

	// 注冊路由
	registerRouter(router)

	router.Run()
}

func registerRouter(router *gin.Engine) {
	// 注冊hello路由
	new(controller.Hello).Register(router)
}

func setUserName(context *gin.Context) {
	context.Set("username", "馬亞南")
}
  • controller包中的hello.go
package controller

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

type Hello struct {}
func (h *Hello) Register(router *gin.Engine) {
	// 綁定路由規則執行的函數
	router.GET("/hello", h.Hello)
}
func (h *Hello) Hello(context *gin.Context) {
	// gin.Context里面封裝了request和response
	// 上下文是 gin 中最重要的部分。例如,它允許我們在中間件之間傳遞變量、管理流程、驗證請求的 JSON 並呈現 JSON 響應。
	context.JSON(http.StatusOK, gin.H{
		"name": "zhang",
		"age": 18,
		"username": context.MustGet("username"),
	})
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM