Go Web编程(三)—— Gin框架基础 | 青训营笔记

236 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 10 天

Gin 是一个用 Go (Golang) 编写的 HTTP Web 框架。 它具有类似 Martini 的 API,但性能比 Martini 快 40 倍。

下载和安装

  1. 下载

在终端输入

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

若没有配置代理,则下载速度可能会比较慢,需要等一会

  1. 导入gin
import "github.com/gin-gonic/gin"

简单使用

使用server := gin.Default()创建服务

server.GET()设置地址,并处理请求

server.run()指定监听窗口

package main

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

func main() {
	// 创建一个服务
	ginServer := gin.Default()

	// 访问地址,处理我们的请求 Request Response
	// Gin 支持RESTful API
	ginServer.GET("/helloworld", func(ctx *gin.Context) {
		ctx.JSON(200, gin.H{"message": "Hello World"}) //返回JSON数据
	})
	ginServer.POST("/helloworld", func(ctx *gin.Context) {
		ctx.JSON(200, gin.H{"message": "post helloworld"})
	})
	// 同样有PUT 和DELETE
	ginServer.PUT("/helloworld", func(ctx *gin.Context) {})
	ginServer.DELETE("/helloworld", func(ctx *gin.Context) {})

	// 指定服务器端口,若不指定则默认为8080
	ginServer.Run(":8082")
}

写完代码后使用go run example.go运行

使用浏览器测试GET如下图

ginhelloword.png 使用postman测试POST请求如下图

post1.png

获取前端传给后端的参数

url?userid=xxx&username=xxx 传参格式

//用问号传参
ginServer.GET("/user/info", func(ctx *gin.Context) {
	userid := ctx.Query("userid")
	username := ctx.Query("username")
	ctx.JSON(http.StatusOK, gin.H{
		"userid":   userid,
		"username": username,
	})	
})

使用context.Query()获取value

效果如图

2.png

restful传参格式

ginServer.GET("/user/info/:userid/:username", func(ctx *gin.Context) {
	userid := ctx.Param("userid")
	username := ctx.Param("username")
	ctx.JSON(http.StatusOK, gin.H{
		"userid":   userid,
		"username": username,
	})
})

使用context.Param()获取value(或者context.Params()获取多个value)

由于使用了http.StatusOK,因此需要import("net/http")

效果如图

3.png

前端给后端传递JSON

ginServer.POST("/postjson", func(ctx *gin.Context) {
	jsonData, err := ctx.GetRawData()
	if err != nil {
		//处理错误
	}
	// 序列化包装为json数据
	var m map[string]interface{}
	json.Unmarshal(jsonData, &m) //写入m中需要用到指针
	ctx.JSON(http.StatusOK, m)
})

使用postman测试如图

4.png

重定向

ginServer.GET("/search", func(ctx *gin.Context) {
	// 重定向
	ctx.Redirect(http.StatusMovedPermanently, "https://cn.bing.com")
})

状态码也可以直接写302(可以查看源码)

可以从终端中查看

5.png

路由组

userGroup := ginServer.Group("/user")
{
        userGroup.GET("/add")
	userGroup.GET("/delete")
}

相当于/user/add 和 /user/delete

中间件

func myHandler() (gin.HandlerFunc){
    return func(ctx *gin.Context)  {
	ctx.Set("userSession","userid")
	ctx.Next()//放行
	ctx.Abort()// 终止
    }
}

ctx.Next()和Abort()前面都应当有条件判断,这里就不展示

同时要注册中间件ginServer.Use(myHandler())

然后稍微改一下前面的GET

ginServer.GET("/user/info", myHandler(), func(ctx *gin.Context) {
	//取出中间件的值
	userSession := ctx.MustGet("userSession").(string)
	log.Println(userSession)
	userid := ctx.Query("userid")
	username := ctx.Query("username")
	ctx.JSON(http.StatusOK, gin.H{
		"userid":   userid,
		"username": username,
	})
})

登录、校验等可以使用中间件

更多例子可以查看官网的examples pkg.go.dev/github.com/…


参考资料

gin-gonic (github.com)

文档 | Gin Web Framework (gin-gonic.com)

【狂神说】Gin框架一小时上手 | 快速转型GoWeb开发 | Go语言零基础教程