尧图建网站 尧图建网站 YAOTU WEB BUILD 免费咨询
ARTICLE DETAIL

资讯详情

深耕网站建设与建站编程的一线实战洞察。

01、Gin环境搭建 Gin程序的热加载 Gin路由 GET POST PUT DELETE

01、Gin环境搭建 Gin程序的热加载 Gin路由 GET POST PUT DELETE 一、Gin介绍Gin的官网https://gin-gonic.com/zh-cn/Gin Github地址https://github.com/gin-gonic/gin二、Gin安装步骤一创建并初始化项目首先为你的项目创建一个文件夹并进入该目录。然后使用go mod init命令初始化一个新的 Go 模块# 创建一个项目文件夹并进入 mkdir my-gin-app cd my-gin-app # 初始化 Go 模块这里的 my-gin-app 是你的模块名 go mod init my-gin-app执行后会在当前目录生成一个go.mod文件这是项目依赖管理的核心文件。步骤二下载并安装 Gin 包在项目根目录下执行以下命令来安装 Gingo get -u github.com/gin-gonic/gin关于命令go get用于下载并安装第三方包-u参数表示更新到该包的最新版本。安装指定版本如果需要安装特定版本可以指定版本号。例如go get github.com/gin-gonic/ginv1.9.1命令执行成功后Gin 就会被添加到go.mod文件中成为项目的依赖。三、Gin 环境搭建1、将gin引入到代码中import github.com/gin-gonic/gin2、可选如果使用诸如http.StatusOK之类的常量则需要引入net/http包import net/httpHTTP 状态码常量最常用在 Gin 中返回响应时建议直接使用这些常量避免写死数字。常量名状态码值说明分类http.StatusOK200✅ 请求成功最常用http.StatusCreated201创建资源成功POSThttp.StatusNoContent204请求成功但无返回内容DELETEhttp.StatusMovedPermanently301永久重定向http.StatusFound302临时重定向http.StatusBadRequest400❌ 客户端请求参数错误http.StatusUnauthorized401未登录或身份认证失败http.StatusForbidden403无权限访问已登录但权限不足http.StatusNotFound404请求的资源不存在http.StatusMethodNotAllowed405请求方法不被允许http.StatusTooManyRequests429请求过于频繁触发限流http.StatusInternalServerError500 服务器内部错误代码异常http.StatusBadGateway502网关或代理服务器收到无效响应http.StatusServiceUnavailable503服务器暂时无法处理停机维护3、新建Main.go配置路由package main import ( github.com/gin-gonic/gin ) func main() { // 创建一个默认的路由引擎 r : gin.Default() // 配置路由 r.GET(/, func(c *gin.Context) { c.JSON(200, gin.H{ // c.JSON返回 JSON 格式的数据 message: Hello world!}) }) // 启动 HTTP 服务默认在 0.0.0.0:8080 启动服务 r.Run() }4、运行你的项目go run main.go5、要改变默认启动的端口r.Run(:9000)四、简单的路由配置r.GET(网址, func(c *gin.Context) { c.String(200, Get) }) r.POST(网址, func(c *gin.Context) { c.String(200, POST) }) r.PUT(网址, func(c *gin.Context) { c.String(200, PUT) }) r.DELETE(网址, func(c *gin.Context) { c.String(200, DELETE) })1、路由里面获取Get传值//域名/news?aid20 r.GET(/news, func(c *gin.Context) { aid : c.Query(aid) c.String(200, aid%s, aid) })2、获取动态路由的传值//域名/user/20 r.GET(/user/:uid, func(c *gin.Context) { uid : c.Param(uid) c.String(200, userID%s, uid) })3、c.String() c.JSON() c.JSONP() c.XML() c.HTML()1、返回一个字符串 r.GET(/news, func(c *gin.Context) { aid : c.Query(aid) c.String(200, aid%s, aid) }) 2、返回一个 JSON 数据 func main() { r : gin.Default() // gin.H 是 map[string]interface{}的缩写 r.GET(/someJSON, func(c *gin.Context) { // 方式一自己拼接 JSON c.JSON(http.StatusOK, gin.H{message: Hello world!}) }) r.GET(/moreJSON, func(c *gin.Context) { // 方法二使用结构体 var msg struct { Name string json:user Message string Age int } msg.Name IT 营学院 msg.Message Hello world! msg.Age 18 c.JSON(http.StatusOK, msg) }) r.Run(:8080) } 3、JSOPN func main() { r : gin.Default() r.GET(/JSONP, func(c *gin.Context) { data : map[string]interface{}{ foo: bar, } // /JSONP?callbackx // 将输出x({\foo\:\bar\}) c.JSONP(http.StatusOK, data) }) // 监听并在 0.0.0.0:8080 上启动服务 r.Run(:8080) } 4、返回 XML 数据 func main() { r : gin.Default() // gin.H 是 map[string]interface{}的缩写 r.GET(/someXML, func(c *gin.Context) { // 方式一自己拼接 JSON c.XML(http.StatusOK, gin.H{message: Hello world!}) }) r.GET(/moreXML, func(c *gin.Context) { // 方法二使用结构体 type MessageRecord struct { Name string Message string Age int } var msg MessageRecord msg.Name IT 营学院 msg.Message Hello world! msg.Age 18 c.XML(http.StatusOK, msg) }) r.Run(:8080) } 4、渲染模板 router.GET(/, func(c *gin.Context) { c.HTML(http.StatusOK, default/index.html, map[string]interface{}{ title: 前台首页}) })3、c.HTML模板放在不同目录里面的配置方法Gin框架中如果不同目录下面有同名模板的话我们需要使用下面方法加载模板templates/admin/index.html!-- 相当于给模板定义一个名字 define end 成对出现-- {{ define admin/index.html }} !DOCTYPE html html langen head meta charsetUTF-8 meta http-equivX-UA-Compatible contentIEedge meta nameviewport contentwidthdevice-width, initial-scale1.0 titleDocument/title /head body h1后台模板/h1 h3{{.title}}/h3 /body /html {{ end }}main.gopackage main import ( net/http github.com/gin-gonic/gin ) func main() { router : gin.Default() //注意如果模板在多级目录里面的话需要这样配置 r.LoadHTMLGlob(templates/**/**/*) /** 表示目录 router.LoadHTMLGlob(templates/**/*) router.GET(/, func(c *gin.Context) { c.HTML(http.StatusOK, default/index.html, gin.H{title: 前台首页}) }) router.GET(/admin, func(c *gin.Context) { c.HTML(http.StatusOK, admin/index.html, gin.H{title: 后台首页}) }) router.Run(:8080) }
返回列表