gin常用操作

发布时间 2023-09-22 14:27:22作者: Jet-jing

介绍

官方介绍

​ Gin 是一个用 Go (Golang) 编写的 Web 框架。 它具有类似 martini 的 API,性能要好得多,多亏了 httprouter,速度提高了 40 倍。 如果您需要性能和良好的生产力,您一定会喜欢 Gin

中文官网

使用

简单例子

package main

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

func index(ctx *gin.Context) {
	ctx.JSON(http.StatusOK, gin.H{"首页": "Index"})
}

func main() {
	// 启动一个默认的路由
	r := gin.Default()
	// 一个get请求,相当于.net 的控制器
	r.GET("/sayHellow", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"丐帮帮主": "乔峰",
		})
	})

	r.GET("/index", index)

	// 启动webservice
	r.Run(":7000")
}

Gin模板渲染

gin框架中使用 loadHTMLGlob() 或者 LoadHTMLFiles() 方法进行html模板渲染

HTML 渲染 | Gin Web Framework (gin-gonic.com)

func index(ctx *gin.Context) {

	fmt.Println("kkkkkkkkk", ctx.Keys["key1"]) // 获取中间件的key

	ctx.HTML(http.StatusOK, "index.html", gin.H{"imgUrl": "/static/images/g.jpg"})
}

// html 模板中可以用  .imgUrl 获取到数据

路由

r.GET("/books/:nian/:yue/:ri", timeRHandler)
func timeRHandler(ctx *gin.Context) {
	ctx.JSON(http.StatusOK, gin.H{
		"nian": ctx.Param("nian"),
		"yue":  ctx.Param("yue"),
		"ri":   ctx.Param("ri"),
	})
}
r.GET("/book/:action", paramHandler)
func paramHandler(ctx *gin.Context) {
	urlParm := ctx.Param("action")

	ctx.JSON(http.StatusOK, gin.H{
		"action": urlParm,
	})

}

文件上传

r.GET("/upload", func(c *gin.Context) {
		c.HTML(http.StatusOK, "upload.html", nil)
})

r.POST("/upload", uploadHandler)

func uploadHandler(c *gin.Context) {
	// 提取用户上传的文件
	fileObj, err := c.FormFile("filename")
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"err": err,
		})
		return
	}
	// fileobj:上传的文件对象
	// fileobj.filename // 拿到上传文件的文件名
	filePath := fmt.Sprintf("./%s", fileObj.Filename)
	// 保存文件到本地的路径
	c.SaveUploadedFile(fileObj, filePath)
	c.JSON(http.StatusOK, gin.H{
		"msg": "OK",
	})
}
 <form action="/upload" method="POST" enctype="multipart/form-data">
        <input type="file" name="filename">
    <input type="submit">
 </form>

路由分组

r:=gin.Default()
book:=r.Group("/book")
{
    book.Get("/index",bookIndexHandler)
}

参数绑定

很多功能可以看官网,还有body只读一次问题处理

//curl.exe http://127.0.0.1:7000/dataBin -X POST -d "userName=jet222&pwd=3333333"
r.POST("/dataBin", DataBin)

type UserInfo struct {
	UserName string `json:"userName" form:"userName" binding:"required"`  // 验证非空 好像没起作用
	Password string `json:"pwd" form:"pwd"`
}


func DataBin(ctx *gin.Context) {
	if ctx.Request.Method == "POST" {
		var u UserInfo
		ctx.ShouldBind(&u) //  mvc 是直接传实体 默认的那种提交方式
        //ctx.ShouldBindJSON("")// json 绑定 等等很多的
		ctx.JSON(http.StatusOK, gin.H{"userName": u.UserName, "pwd": u.Password})
	}
}





func loginHandler(ctx *gin.Context) {
	if ctx.Request.Method == "POST" {
		var u UserInfo
		ctx.ShouldBind(&u)
		fmt.Println("---------------", u.UserName)
		if u.UserName == "jet" {
			// 10s 过期
			ctx.SetCookie("userName", u.UserName, 10, "/", "127.0.0.1", false, true)
			ctx.Redirect(302, "/index") // 页面跳转
		}

	} else {
		ctx.HTML(http.StatusOK, "login.html", nil)
	}
}

func cookieMiddleware(ctx *gin.Context) {
	username, err := ctx.Cookie("userName")
	if err != nil {
		ctx.Redirect(302, "/login")
		return
	}
	ctx.Set("username", username)
	ctx.Next()

}


相对来说简单点,看着文档就可以撸码