首页 > 其他分享 >gin常用API

gin常用API

时间:2023-11-03 14:34:19浏览次数:36  
标签:常用 http name GET API StatusOK Context gin

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)
})

标签:常用,http,name,GET,API,StatusOK,Context,gin
From: https://www.cnblogs.com/huangxiaoshuai/p/17807508.html

相关文章

  • 宝塔 nginx 运行 vue项目
    宝塔安装nginxnginx根目录:/www/server/nginx/html修改nginx配置下滑到70多行,添加server对象内容,内容如下server{listen82;server_nametest2;location/{roothtml/test2;indexindex.htmlindex.htm;......
  • 在虚拟机(Linux)中Docker中部署Nginx成功,但是在宿主机无法访问Nginx站点?
    1.问题本文是基于黑马程序员Docker基础--常见命令一课中部署Nginx时遇到的问题作出解答。在虚拟机(Linux)中Docker中部署Nginx成功,但是在宿主机无法访问Nginx站点如图,Nginx服务已经启动成功但是我们在宿主机的浏览器试图访问的时候却总是报错:2.解决思路2.1查看端口号是否映......
  • mysql sql常用优化
    1 explain输出执行计划,检查orderby和where后边的字段是否建立索引2in()中的列不应过多,notin和in()数据过多都不再走索引,使用全表扫描,连续数值可以使用between1and33select后边指定字段,少用select(*)4 where子句中避免isnull/isnotnull5 应尽量避免在whe......
  • MegEngine 9-10 双月报:新版本发布,AI 生态升级,不容错过!
    ●v1.13.2新版本发布<https://github.com/MegEngine/MegEngine/releases/tag/v1.13.2>●MegCC新版本发布<https://github.com/MegEngine/MegCC/releases/tag/v0.1.6>●DataFunSummit2023:AI基础软件架构峰会《MegEngine训练性能优化与AI编译实践》主题演讲<https://w......
  • linux下安装nginx
    下载nginxwgethttps://nginx.org/download/nginx-1.25.3.tar.gzyum安装依赖包yum-yinstallgcczlibzlib-develpcre-developensslopenssl-devel解压tar-zxvfnginx-1.22.0.tar.gz配置当前nginxcdnginx-1.22.0./configure--prefix=/usr/local/nginx......
  • 前后端都用得上的 Nginx 日常使用经验
    前言nginx是一个高性能的开源反向代理服务器和web服务器,一般用来搭建静态资源服务器、负载均衡器、反向代理,本文将分享其在Windows/docker中的使用,使用nssm部署成服务的方案脚本,局域网中自定义域名解决https提示不安全的解决方案,以及一路踩过的坑。特点高性能:事件驱......
  • AtCoder Beginner Contest(abc) 314
    B-Roulette难度:⭐题目大意有一个猜数字的游戏,有n个人参加,每人都猜了若干个数;最后给出答案数字;在所有猜中数字的人中输出猜数数量最少的人的编号;(可能不止一个);解题思路数据不大,暴力即可;神秘代码#include<bits/stdc++.h>#defineintlonglong#def......
  • Ansible操作MySQL常用的几个模块
    1. mysql_user模块mysql_user模块用来添加,删除用户以及设置用户权限创建MySQL数据库的用户与口令(非root@localhost用户),直接通过playbooks中的案例来说明吧。-name:创建MySQL数据库用户--user_testmysql_user:#-----登陆数据库login_host:"localhost"......
  • 启动nginx报错nginx: [emerg] unexpected end of file, expecting "}" in /usr/local/
    启动nginx报错:“nginx:[emerg]unexpectedendoffile,expecting“}”in/usr/local/nginx/conf/nginx.conf:118”重启nginx时,报这么个错:[root@localhostconf]#/usr/local/nginx/sbin/nginx-sreloadnginx:[emerg]unexpectedendoffile,expecting“}”in/usr/lo......
  • nginx coturn socat privoxy opencv 静态编译
    文档说明:只记录关键的地方;发文时间:2023-11-02意义:linux环境,免安装下载后即可使用环境:alpine:3.18dockerclang状态:完善中体验编译结果nginx静态编译关键点nginxusePCRE2libraryonnginx1.21.5hg脚本全称是mercurialopensslzlibpcpre2等静态库......