go框架gin的使用
gin框架教程代码地址:
我们在用http的时候一般都会用一些web框架来进行开发,gin就是这样的一个框架,它有哪些特点呢
一:gin特点
1、性能优秀
2、基于官方的net/http的有限封装
3、方便 灵活的中间件
4、数据绑定很强大
5、社区比较活跃
等等
二:gin的安装
安装:
go get github.com/gin-gonic/gin
如果要更新:
go get -u github.com/gin-gonic/gin
三:gin的使用
1、入门的第一个示例
先来写出一个例子:example1.go
package main import (
"github.com/gin-gonic/gin"
) func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(, gin.H{
"message": "pong",
})
})
r.Run() //listen and serve on 0.0.0.0:8080
}
a. 然后运行 go run example1.go 之后,
b. 在浏览器上输入:http://localhost:8080/ping
输出结果:
{"message":"pong"}
2: gin的基本路由
// 创建带有默认中间件的路由:
r := gin.Default()
//创建不带中间件的路由:
//r := gin.New()
r.GET("/someGet", getting)
r.POST("/somePost", posting)
r.PUT("/somePut", putting)
r.DELETE("/someDelete", deleting)
r.PATCH("/somePatch", patching)
r.HEAD("/someHead", head)
r.OPTIONS("/someOptions", options)
3、获取路由的参数
3.1 Parameters in path
编写param1.go文件
package main import (
"github.com/gin-gonic/gin"
"net/http"
) func main() {
r := gin.Default() //这个能匹配 /user/tom , 但是不能匹配 /user/ 或 /user
r.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
}) //有一个方法可以匹配 /user/tom, 也可以匹配 /user/tom/send
//如果没有任何了路由匹配 /user/tom, 它将会跳转到 /user/tom/
r.GET("/user/:name/*action", func(c *gin.Context) {
name := c.Param("name")
action := c.Param("action")
message := name + " is " + action
c.String(http.StatusOK, message)
}) r.Run(":8080")
}
a. 然后运行 go run param1.go 之后,
b. 在浏览器上输入:http://localhost:8080/user/tom
输出结果:Hello tom
c. 在浏览器上输入:http://localhost:8080/user/tom/
输出结果:tom is /
d. 在浏览器上输入:http://localhost:8080/user/tom/pig
输出结构: tom is /pig
3.2 query param
一般匹配这种形式的url /welcome?firstname=Jane&lastname=Doe
package main //Querystring parameters import (
"github.com/gin-gonic/gin"
"net/http"
) func main() {
r := gin.Default()
r.GET("/welcome", func(c *gin.Context) {
firstname := c.DefaultQuery("firstname", "Guest") //如果没有值,还可以给一个默认值
lastname := c.Query("lastname")
c.String(http.StatusOK, "Hello %s %s ", firstname, lastname)
})
r.Run(":8080")
}
a. 然后运行 go run param2.go 之后,
b. 在浏览器上输入:http://localhost:8080/welcome?lastname=jimmy
输出结果:Hello Guest jimmy
c. 在浏览器上输入:http://localhost:8080/welcome?lastname=jimmy&firstname=tom
输出结果:Hello tom jimmy
3.3 表单参数 Form
Multipart/Urlencoded Form
package main import (
"github.com/gin-gonic/gin"
// "net/http"
) func main() {
r := gin.Default()
r.POST("/form_post", func(c *gin.Context) {
message := c.PostForm("message")
nick := c.DefaultPostForm("nick", "guest") c.JSON(, gin.H{
"status": "posted",
"message": message,
"nick": nick,
})
}) r.Run(":8080")
}
可以用postman来测试一下, 测试结果如下:
3.4 混合型的query + post form
package main import (
// "fmt"
"github.com/gin-gonic/gin"
) /*
POST /post?id=1234&page=1 HTTP/1.1
Content-Type: application/x-www-form-urlencoded name=manu&message=this_is_great
*/
func main() {
r := gin.Default()
r.POST("/post", func(c *gin.Context) {
id := c.Query("id")
page := c.DefaultQuery("page", "")
name := c.PostForm("name")
message := c.PostForm("message") // fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
c.JSON(, gin.H{
"id": id,
"page": page,
"name": name,
"message": message,
})
}) r.Run(":8080")
}
用postman测试结果如下:
4:解析数据绑定
我们可以给一个请求的数据绑定到一个类型,gin支持绑定的类型有JSON,XML和标准的表单数据(foo=bar&boo=baz)。 注意绑定时需要设置绑定类型的标签。比如绑定json数据时,
设置 json:"fieldname"
package main import (
"github.com/gin-gonic/gin"
"net/http"
) // Binding from JSON
type User struct {
Username string `form:"username" json:"username" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
Age int `form:"age" json:"age"`
} func main() {
r := gin.Default()
// Example for binding JSON ({"username": "manu", "password": "123"})
r.POST("/loginJSON", func(c *gin.Context) {
var json User if err := c.ShouldBindJSON(&json); err == nil {
if json.Username == "manu" && json.Password == "" {
c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
} else {
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized", "username": json.Username, "pass": json.Password})
}
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
})
// Example for binding a HTML form (user=manu&password=123)
r.POST("/loginForm", func(c *gin.Context) {
var form User
if err := c.ShouldBind(&form); err != nil {
if form.Username == "manu" && form.Password == "" {
c.JSON(http.StatusOK, gin.H{"status": "you are logged in 2"})
} else {
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized 2"})
}
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
})
r.Run(":8080")
}
还有一些其他的应用,可以参考:
https://github.com/gin-gonic/gin/blob/master/README.md
go框架gin的使用的更多相关文章
- Go语言web框架 gin
Go语言web框架 GIN gin是go语言环境下的一个web框架, 它类似于Martini, 官方声称它比Martini有更好的性能, 比Martini快40倍, Ohhhh….看着不错的样子, 所 ...
- GO语言web框架Gin之完全指南
GO语言web框架Gin之完全指南 作为一款企业级生产力的web框架,gin的优势是显而易见的,高性能,轻量级,易用的api,以及众多的使用者,都为这个框架注入了可靠的因素.截止目前为止,github ...
- Golang 微框架 Gin 简介
框架一直是敏捷开发中的利器,能让开发者很快的上手并做出应用,甚至有的时候,脱离了框架,一些开发者都不会写程序了.成长总不会一蹴而就,从写出程序获取成就感,再到精通框架,快速构造应用,当这些方面都得心应 ...
- httprouter框架 (Gin使用的路由框架)
之前在Gin中已经说到, Gin比Martini的效率高好多耶, 究其原因是因为使用了httprouter这个路由框架, httprouter的git地址是: httprouter源码. 今天稍微看了 ...
- Go组件学习——Web框架Gin
以前学Java的时候,和Spring全家桶打好关系就行了,从Spring.Spring MVC到SpringBoot,一脉相承. 对于一个Web项目,使用Spring MVC,就可以基于MVC的思想开 ...
- gin框架教程一: go框架gin的基本使用
我们在用http的时候一般都会用一些web框架来进行开发,gin就是这样的一个框架,它有哪些特点呢 一:gin特点 1.性能优秀2.基于官方的net/http的有限封装3.方便 灵活的中间件4.数据绑 ...
- GO语言web框架Gin之完全指南(二)
这篇主要讲解自定义日志与数据验证 参数验证 我们知道,一个请求完全依赖前端的参数验证是不够的,需要前后端一起配合,才能万无一失,下面介绍一下,在Gin框架里面,怎么做接口参数验证的呢 gin 目前是使 ...
- GO语言web框架Gin之完全指南(一)
作为一款企业级生产力的web框架,gin的优势是显而易见的,高性能,轻量级,易用的api,以及众多的使用者,都为这个框架注入了可靠的因素.截止目前为止,github上面已经有了 35,994 star ...
- go语言框架gin之集成swagger
1.安装swag 在goLand中直接使用go get -u github.com/swaggo/swag/cmd/swag命令安装会报错 翻了很多博客,都没找到太合适的办法,根据博客中所写的操作还是 ...
随机推荐
- Software License Manager
slmgr -ilc lenovo.xrm-ms slmgr -ipk lenovo-lenovo-lenovo-lenovo-lenovo
- JQuery operate xml
msg is <?xml ?> <Parameters> <WorkflowName>...</WorkflowName> </Parameter ...
- c++中结构体sort()排序
//添加函数头 #include <algorithm> //定义结构体Yoy typedef struct { double totalprice; //总价 doubl ...
- Codeforces 719A 月亮
参考自:https://www.cnblogs.com/ECJTUACM-873284962/p/6395221.html A. Vitya in the Countryside time limit ...
- POJ 3349-Snowflake Snow Snowflakes-字符串哈希
哈希后,对每片雪花对比6次. #include <cstdio> #include <cstring> #include <vector> #include < ...
- springboot使用redis
1.pom文件中引入 spring-boot-starter-redis <dependency> <groupId>org.springframework.boot</ ...
- 【XSY2719】prime 莫比乌斯反演
题目描述 设\(f(i)\)为\(i\)的不同的质因子个数,求\(\sum_{i=1}^n2^{f(i)}\) \(n\leq{10}^{12}\) 题解 考虑\(2^{f(i)}\)的意义:有\(f ...
- bzoj 1264: [AHOI2006]基因匹配Match (树状数组优化dp)
链接:https://www.lydsy.com/JudgeOnline/problem.php?id=1264 思路: n大小为20000*5,而一般的dp求最长公共子序列复杂度是 n*n的,所以我 ...
- Collect devices information
Collect devices information root@vpx-test# kenv > kenv.txt root@vpx-test# sysctl -a > sysctl_a ...
- Codeforces Round #555 (Div. 3)[1157]题解
不得不说这场div3是真的出的好,算得上是从我开始打开始最有趣的一场div3.因为自己的号全都蓝了,然后就把不经常打比赛的dreagonm的号借来打这场,然后...比赛结束rank11(帮dreago ...