【GoWeb框架初探————Gin篇】

1. Gin

1.1 下载相应依赖

创建go项目,在项目下建立go.mod文件(若有则跳过)

命令行运行

bash 复制代码
go get github.com/gin-gonic/gin

1.2 启动一个简单Web服务

go 复制代码
package main

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

func main() {
	// 获取一个gin默认的服务器
	ginServer := gin.Default()
	// 修改网站在浏览器的icon
	ginServer.Use(favicon.New("./icon/img.png"))
	// 访问地址,处理我们的请求		Request   Response
	ginServer.GET("/hello", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{"msg": "hello,world"})
	})
	// 返回界面
	// 服务端口
	ginServer.Run(":8083")
}

1.3 Gin中的Restful风格API

go 复制代码
	// Gin RestFul风格
	ginServer.GET("/user", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{"msg": "GET,user"})
	})
	ginServer.POST("/user", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{"msg": "POST,user"})
	})
	ginServer.PUT("/user", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{"msg": "PUT,user"})
	})
	ginServer.DELETE("/user", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{"msg": "DELETE,user"})
	})

1.4 如何返回网页

go 复制代码
func main() {
	// 创建一个服务
	ginServer := gin.Default()
	// 修改网站在浏览器的icon
	ginServer.Use(favicon.New("./icon/img.png"))
	// 加载静态页面
	ginServer.LoadHTMLGlob("templates/*")
	// 加载资源文件
	ginServer.Static("/static", "./static")
	// 响应一个页面给前端
	ginServer.GET("index", func(context *gin.Context) {
		context.HTML(http.StatusOK, "index.html", gin.H{"msg": "这是后台来的数据"})
	})
	// 服务端口
	ginServer.Run(":8083")
}

前端html界面使用参数的方法类似于vue中的操作

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>
太强啦!
获取后端数据为:{{.msg}}
</body>
</html>

1.5 如何从请求中获取参数

go 复制代码
	// url?userid=xxx&username=kuangshen
	ginServer.GET("/user/info", func(context *gin.Context) {
		userid := context.Query("userid")
		username := context.Query("username")
		context.JSON(http.StatusOK, gin.H{
			"userid":   userid,
			"username": username,
		})
	})
	// /user/info/1/kuangshen
	ginServer.GET("user/info/:userid/:username", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{
			"userid":   context.Param("userid"),
			"username": context.Param("username"),
		})
	})
	// 前端给后端传递json
	ginServer.POST("/json", func(context *gin.Context) {
		body, _ := context.GetRawData()
		var m map[string]interface{}
		// 序列化包装为json
		_ = json.Unmarshal(body, &m)
		context.JSON(http.StatusOK, m)
	})
	// 处理表单的数据
	ginServer.POST("/user/add", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{
			"userid":   context.PostForm("userid"),
			"username": context.PostForm("username"),
		})
	})

1.6 路由和重定向

go 复制代码
	// 重定向
	ginServer.GET("/test", func(context *gin.Context) {
		// 重定向
		context.Redirect(http.StatusMovedPermanently, "https://baidu.com")
	})
	// 404 NoRoute
	ginServer.NoRoute(func(context *gin.Context) {
		context.HTML(http.StatusNotFound, "404.index", nil)
	})

	// 路由组
	userGroup := ginServer.Group("/user")
	{
		userGroup.GET("/add")
		userGroup.POST("/login")
		userGroup.POST("/logout")
	}
	
	v1api := ginServer.Group("/v1")
	v1api.GET("/jack", func(context *gin.Context) {
		context.String(http.StatusOK, "版本v1的jack")
	})

1.7 中间件/拦截器

预处理、登录授权、验证、分页...耗时统计

我们查看GET等请求的参数时,发现第二个参数是...HandlerFunc,表示这是一个可变长的参数,会依次进过这些处理器进行处理。

go 复制代码
// 自定义Go中间件
func myHandler() gin.HandlerFunc {
	return func(context *gin.Context) {
		// 通过自定义的中间值,设置的值,在后续处理只要调用了这个中间件的都可以拿到这里的参数
		context.Set("usersSession", "userId-1")
		context.Next()  //放行
		context.Abort() //阻止
	}
}

//func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes
//也就是说,我们可以通过这样的方式来让请求依次通过多个handler
ginServer.POST("/user/add",myHandler() ,func(context *gin.Context) {
	context.JSON(http.StatusOK, gin.H{
		"userid":   context.PostForm("userid"),
		"username": context.PostForm("username"),
		"usersSession": context.MustGet("usersSession").(string)
	})
})
相关推荐
yagamiraito_4 小时前
757. 设置交集大小至少为2 (leetcode每日一题)
算法·leetcode·go
Code_Artist13 小时前
robfig/cron定时任务库快速入门
分布式·后端·go
川白20 小时前
用 Go 写多线程粒子动画:踩坑终端显示与跨平台编译【含 Windows Terminal 配置 + Go 交叉编译脚本】
go
zhuyasen1 天前
Go 实战:在 Gin 基础上上构建一个生产级的动态反向代理
nginx·go·gin
Tsblns2 天前
从Go http.HandleFunc()函数 引出"函数到接口"的适配思想
go
Schuyler20252 天前
年轻人的第一个 GO 桌面应用:用 Wails 做个学习搭子计时器
go
q***78372 天前
【Golang】——Gin 框架中间件详解:从基础到实战
中间件·golang·gin
狼爷3 天前
Go 重试机制终极指南:基于 go-retry 打造可靠容错系统
架构·go
不爱笑的良田3 天前
从零开始的云原生之旅(十六):金丝雀发布实战:灰度上线新版本
云原生·容器·kubernetes·go
嘿嘿4 天前
使用 Gin 框架加载 HTML 模板:`LoadHTMLGlob` 和 `LoadHTMLFiles` 的比较与优化
后端·go·gin