From 86b28ed21563333e949a0a9bcc443fadbe5b4851 Mon Sep 17 00:00:00 2001 From: nannanwu Date: Sun, 23 Nov 2025 17:04:51 +0800 Subject: [PATCH] =?UTF-8?q?gin=E8=B7=AF=E7=94=B1=E4=B8=AD=E7=9B=B8?= =?UTF-8?q?=E5=BA=94=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.go | 70 ++++++++++++++++++++++++++++++++++++++------ templates/goods.html | 12 ++++++++ templates/index.html | 12 ++++++++ templates/news.html | 12 ++++++++ 4 files changed, 97 insertions(+), 9 deletions(-) create mode 100644 templates/goods.html create mode 100644 templates/index.html create mode 100644 templates/news.html diff --git a/main.go b/main.go index 96f60f2..a4026d7 100644 --- a/main.go +++ b/main.go @@ -1,22 +1,74 @@ package main -import "github.com/gin-gonic/gin" +import ( + "github.com/gin-gonic/gin" +) + +type Article struct { + Title string + Desc string + Content string +} func main() { r := gin.Default() - //从服务器请求资源 + //html模板文件 + r.LoadHTMLGlob("templates/*") r.GET("/", func(c *gin.Context) { - c.String(200, "这是一个get请求,用于取出资源") + c.String(200, "首页") }) - r.POST("/add", func(c *gin.Context) { - c.String(200, "这是一个post--主要用于增加数据") + r.GET("/json", func(c *gin.Context) { + c.JSON(200, map[string]interface{}{ + "success": "true", + "msg": "你好gin", + }) }) - r.PUT("/edit", func(c *gin.Context) { - c.String(200, "这是一个put请求 主要用于编辑数据") + + r.GET("/json2", func(c *gin.Context) { + c.JSON(200, gin.H{ + "success": "true", + "msg": "你好gin", + }) }) - r.DELETE("/delete", func(c *gin.Context) { - c.String(200, "这是一个delete请求 主要用于删除数据") + + r.GET("/json3", func(c *gin.Context) { + a := Article{ + Title: "我是一个标题", + Desc: "描述", + Content: "测试内容", + } + c.JSON(200, a) }) + + //响应jsonp请求 http://0.0.0.0:8080/jsonp?callback=xxx + r.GET("/jsonp", func(c *gin.Context) { + a := Article{ + Title: "我是一个标题", + Desc: "描述", + Content: "测试内容", + } + c.JSONP(200, a) + }) + + r.GET("xml", func(c *gin.Context) { + c.XML(200, gin.H{ + "success": "true", + "msg": "你好gin,我是一个xml", + }) + }) + + r.GET("news", func(c *gin.Context) { + c.HTML(200, "news.html", gin.H{ + "title": "我是一个后台数据", + }) + }) + + r.GET("goods", func(c *gin.Context) { + c.HTML(200, "news.html", gin.H{ + "title": "我是一个商品页面", + }) + }) + err := r.Run() if err != nil { return diff --git a/templates/goods.html b/templates/goods.html new file mode 100644 index 0000000..4fabbd4 --- /dev/null +++ b/templates/goods.html @@ -0,0 +1,12 @@ + + + + + + Document + + +

{{.title}}

+ + + \ No newline at end of file diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..ea6d515 --- /dev/null +++ b/templates/index.html @@ -0,0 +1,12 @@ + + + + + + Document + + +

我是一个新闻界面

+ + + \ No newline at end of file diff --git a/templates/news.html b/templates/news.html new file mode 100644 index 0000000..4fabbd4 --- /dev/null +++ b/templates/news.html @@ -0,0 +1,12 @@ + + + + + + Document + + +

{{.title}}

+ + + \ No newline at end of file