go-gin快速入门(1)
1.简单应用
-
安装
go get -u github.com/gin-gonic/gin -
启动服务
package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { //1.创建路由 r := gin.Default() //2.绑定路由规则,执行的函数 //gin.Context 中 封装了request 和 Response r.GET("/api", func(c *gin.Context) { //c.String(http.StatusOK, "hello world") name := c.DefaultQuery("name", "default") //获取url参数 age := c.DefaultQuery("age", "0") c.JSON(http.StatusOK, gin.H{ "name": name, "password": age, }) }) //3.监听端口,启动服务 r.Run(":8080") // listen and serve on 0.0.0.0:8080 } -
路由分组(router group)
package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { r := gin.Default() user := r.Group("/user") { user.GET("test1", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"msg": "success1"}) }) user.GET("test2", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"msg": "success2"}) }) } product := r.Group("/product") { product.POST("/add", func(c *gin.Context) { c.JSON(http.StatusCreated, gin.H{ "msg": "添加成功", "code": "0", }) }) } _ = r.Run(":8080") }测试代码(python console)
import requests req = requests.get("http://0.0.0.0:8080/user/test1") req.json() {'msg': 'success1'} res = requests.post("http://0.0.0.0:8080/product/add") res.json() {'code': '0', 'msg': '添加成功'} -
参数获取
-
API 参数获取(c.Param)
package main import ( "github.com/gin-gonic/gin" "net/http" ) //API参数获取 func test1() { r := gin.Default() r.GET("/:name/:age/*action", func(c *gin.Context) { map1 := make(map[string]interface{}) map1["name"] = c.Param("name") map1["age"] = c.Param("age") map1["action"] = c.Param("action") //想获取参数值需要手动截取 c.JSON(http.StatusOK, gin.H{ "data": map1, }) }) _ = r.Run(":8080") } func main() { test1() }测试代码:
import requests res = requests.get("http://0.0.0.0:8080/zhangsan/99/mytest") res.json() # 观察可以发现,action参数 是/mytest {'data': {'action': '/mytest', 'age': '99', 'name': 'zhangsan'}} -
URL参数获取
... map1["city"] = c.DefaultQuery("city", "北京") map1["sex"] = c.Query("sex") ...测试代码:
res = requests.get("http://0.0.0.0:8080/zhangsan/99/mytest?city=上海") {'data': {'action': '/mytest', 'age': '99', 'city': '上海', 'name': 'zhangsan', 'sex': ''}}结论:
- URL参数可以通过DefaultQuery()或Query()方法获取
- DefaultQuery()若参数不存在,返回默认值,Query()若不存在,返回空串
-
2.参数验证
Gin验证参数使用 https://github.com/go-playground/validator
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Login struct {
User string `form:"user" json:"user" xml:"user" binding:"required"`
Password string `form:"password" json:"password" xml:"password" binding:"required,omitempty"`
}
type SignUpParam struct {
Age uint8 `json:"age" binding:"gte=1,lte=130"`
Name string `json:"name" binding:"required"`
Email string `json:"email" binding:"required,email"`
Password string `json:"password" binding:"required"`
RePassword string `json:"re_password" binding:"required,eqfield=Password"`
}
func main() {
router := gin.Default()
router.POST("/login", func(c *gin.Context) {
var json Login
if err := c.ShouldBindJSON(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"Error": err.Error()})
return
}
if json.User != "admin" || json.Password != "123" {
c.JSON(http.StatusUnauthorized, gin.H{"status": "Unauthorized"})
return
}
c.JSON(http.StatusOK, gin.H{"status": "登录成功"})
})
_ = router.Run(":8080")
}
本文来自博客园,作者:CV-coding,转载请注明原文链接:https://www.cnblogs.com/CV-coding/articles/15411449.html
浙公网安备 33010602011771号