当前位置: 首页 > 工具软件 > c > 使用案例 >

c.String() c.JSON() c.JSONP() c.XML() c.HTML()

太叔天宇
2023-12-01

示例

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

type Article struct {
	Title   string // 变量名首字母需要大写,不然会返回一个空的结构体
	Desc    string `json:"desc"` // 这种格式可以使变量名输出为小写
	Content string
}

func main() {
	r := gin.Default()
	// 配置模板的文件
	r.LoadHTMLGlob("templates/*")
	r.GET("/", func(c *gin.Context) {
		c.String(200, "值:%v", "首页")
	})
	r.GET("/json1", func(c *gin.Context) {
		c.JSON(200, map[string]interface{}{
			"name":    "tom",
			"success": "true",
			"msg":     "你好",
		})
	})
	r.GET("/json2", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"name":    "krien",
			"success": "true",
			"msg":     "你好,这是第二个json",
		})
	})
	// jsonp主要用来处理跨域,在域名后加?callback=xxx
	r.GET("/jsonp", func(c *gin.Context) {
		A := &Article{
			Title:   "我是标题",
			Desc:    "描述",
			Content: "czh大帅逼",
		}
		c.JSONP(200, A)
	})
	r.GET("/xml", func(c *gin.Context) {
		c.XML(http.StatusOK, gin.H{
			"success": true,
			"msg":     "你好,我是一个xml",
		})
	})
	r.GET("/news", func(c *gin.Context) {
		c.HTML(http.StatusOK, "news.html", gin.H{
			"title": "我是后台数据",
		})
	})
	r.GET("/goods", func(c *gin.Context) {
		c.HTML(http.StatusOK, "goods.html", gin.H{
			"title":   "这是一个商品后端信息",
			"content": "这是内容页面",
		})
	})

	r.Run()
}

 类似资料:

相关阅读

相关文章

相关问答