gin常用API

发布时间 2023-11-03 14:28:11作者: 小小帅的成长之路

gin常用API

获取路由引擎

r = gin.Default() // 返回路由引擎 engine   这里命名为r

GET请求

// r.GET(路由地址, 回调函数)
r.GET("/get_request", func(c *gin.Context){
    // c.Query("请求参数") 获取GET请求参数
    name := c.Query("name") 
   // c.JSON(请求状态码, 返回参数)
    c.JSON(http.StatusOK, gin.H{
        "msg": "success",
        "code": 200,
        "data": name,
    })
})

POST请求

// r.POST(路由地址, 回调函数)
r.POST("/post_request", func(c *gin.Context){
    // 第一个参数获取请求参数,第二个默认参数,第一个参数没有时候,返回默认参数
    // name := c.DefaultPostForm("name", "默认参数");
    // 有数据掺入,b返回true,否则返回false
    name, b := c.GetPostForm("name")
    c.JSON(http.StatusOK, gin.H{
        "msg": "success",
        "code": 200,
        "data": name,
    })
})

重定向

注:c 表示 c *gin.Context

  • 301永久重定向
  • 302临时重定向

一般重定向,重定向到外部网址

c.Redirect(请求码,重定向地址)

示例:

c.Redirect(301, "https://www.baidu.com")

路由重定向,重定向到项目具体路由

c.Request.URL.Path = "跳转的路由"

r.HandleContext(c)

示例:

r.GET("/routerRedirect", func(c *gin.Context){
    c.Request.URL.Path = "/newRouter"
    r.HandleContext(c)
})
r.GET("/newRouter", func(c *gin.Context) {
    c.String(200, "重定向后的位置")
})

返回第三方数据

r.GET("/getdata", func(c *gin.Context) {
    url := "https://www.baidu.com"
    response, err := http.Get(url)
    // 如果err不为空,响应码与http.StatusOK不相等,返回错误码
    if err != nil || response.StatusCode != http.StatusOK {
        // 应答客户端
        c.Status(http.StatusServiceUnavailable)
        return
    }
    // 获取响应体
    body := response.Body
    // 获取content length
    contentLenth := response.ContentLength
    // 获取content type
    contentType := response.Header.Get("Content-Type")
    // 把读取到数据返回到客户端
    c.DataFromReader(http.StatusOK,contentLenth,contentType,body,nil)
})

多形式渲染

c.JSON()
c.XML()

// 需要先 r.LoadHTMLGlob("HTML所在文件夹/*")
c.HTML(code int, "html文件名 如:index.html", fin.H{})

c.YAML(code int, gin.H{})
c.PureJSON()

获取当前文件所在工作目录

wd, _ := os.Getwd() // 类似nodejs的 __dirname命令

数据绑定

// 将结构体数据与表单绑定(其实也就是将表单提交的数据直接映射为结构体实体)
// GET请求 ShouldBindQuery方法
// post请求 shouldbind方法

示例:

type UserRegister struct {
    UserName string `json:"username" form:"name" binding:"required"`
	Phone string `json:"phone" form:"phone" binding:"required"`
	Password string `json:"password" form:"password" binding:"required"`
}
c.GET("/user", func(c *gin.Context) {
    user := new(UserRegister)
    if err := c.ShouldBindQuery(user); err!= nil {
        c.JSON(http.StatusServiceUnavailable, gin.H{
            "msg": err.Error(),
            "code": http.StatusServiceUnavailable,
        })
    } else {
        fmt.Printf("%#v \n", user)
        c.JSON(http.StatusOK, gin.H{
            "msg":"success",
            "code":http.StatusOK,
            "data": user,
        })
    }
})

文件服务器

核心API:c.File

c.File("文件地址") 如:c.File("D:\goProject\public\images\img1.png") 将服务器图片返回到本地

r.GET("/getImg", func(c *gin.Context) {
    wd, _ := os.Getwd()
    name := c.Query("name")
    fileName := wd + "/images/"+name
    c.File(fileName)
})