Go Gin框架

Gin框架入门与实战

一、Gin介绍
Gin是一个用Go编写的HTTPweb框架。它是一个类似于martini但拥有更好性能的API框架, 优于httprouter,速度提高了近 40 倍。点击此处访问Gin官方中文文档。

二、安装
1、安装Gin

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


2、代码中引入

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


代码

package main

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

func main() {
	//go get -u github.com/gin-gonic/gin  执行get拉取包
	ginServer := gin.Default() //创建服务
	ginServer.GET("/hello", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": "hello go"})
	})
	ginServer.POST("/user", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": "创建成功"})
	})
	ginServer.PUT("/user", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": "修改成功"})
	})
	ginServer.DELETE("/user", func(context *gin.Context) {
		context.JSON(200, gin.H{"msg": "删除成功"})
	})


    	//usl?userid=xxx&username=xxx
	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/zhangsan
	ginServer.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传递给后端
	ginServer.POST("/json", func(context *gin.Context) {
		data, _ := context.GetRawData()
		var m map[string]interface{}
		_ = json.Unmarshal(data, &m)
		context.JSON(http.StatusOK, m)

	})

	//表单提交
	ginServer.POST("/user/add", func(context *gin.Context) {
		username := context.PostForm("username")
		context.JSON(http.StatusOK, gin.H{
			"username": username,
		})

	})

    //404
	ginServer.NoRoute(func(context *gin.Context) {
		context.HTML(http.StatusNotFound, "404.html", nil)

	})

	//路由组
	orderGroup := ginServer.Group("/order")
	{
		orderGroup.GET("/list", func(context *gin.Context) {

		})
		orderGroup.POST("/add", func(context *gin.Context) {

		})
	}

	//调用中间件
	//	ginServer.Use(myHandler())定义全局中间件
	//  /user/info/1/zhangsan
	ginServer.GET("/zjj", myHandler(), func(context *gin.Context) {
		usersession := context.MustGet("usersesion").(string)

		context.JSON(http.StatusOK, gin.H{
			"usersession": usersession,
		})
	})

	ginServer.Run(":8082")
}

// 中间件  拦截器
func myHandler() gin.HandlerFunc {
	return func(context *gin.Context) {
		//通过中间件设置值,后续只要调用中间件都可以拿到这个参数
		context.Set("usersesion", "userid1")

		context.Next() //往下执行
		//context.Abort()//阻止执行
	}
}

结果:

### Golang Gin 框架使用教程 #### 安装环境准备 为了能够顺利安装和使用Gin框架,需先确保已正确安装Golang。对于Golang的版本建议不低于1.15[^3]。 #### 安装Gin框架 通过`go get`命令来获取Gin库文件,这会自动将所需的依赖项一同下载下来: ```bash $ go get -u github.com/gin-gonic/gin ``` 如果遇到网络问题无法正常拉取资源,则可以通过配置GOPROXY指向国内镜像源解决此问题: ```bash $ go env -w GO111MODULE=on $ go env -w GOPROXY=https://goproxy.cn,direct ``` 以上操作完成后即完成了Gin框架的基础安装过程[^2]。 #### 创建第一个HTTP服务器实例 下面给出一段简单的代码用来创建基于Gin框架的Web服务端程序: ```go package main import ( "net/http" "github.com/gin-gonic/gin" ) func helloWorld(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "message": "Hello world!", }) } func main() { r := gin.Default() r.GET("/hello", helloWorld) r.Run(":8080") // 默认监听地址为localhost:8080 } ``` 这段代码定义了一个GET类型的API接口/hello,在接收到客户端请求时返回JSON格式的消息"Hello world!"给调用方[^1]。 #### 集成Swagger自动生成API文档 为了让开发者更加方便地维护RESTful API的设计说明以及测试在线调试功能,可以考虑集成Swagger工具来自动生成交互式的API文档。具体做法是在项目里加入必要的模块支持,并按照官方指南完成相应设置即可实现这一目标[^5]。
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值