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

示例

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值