Gin 学习笔记01-数据返回

1、返回 string 和 json

  • c.String()
  • c.JSON()
package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func getJSON(c *gin.Context) {

	//c.String(http.StatusOK, "小明")

	//c.JSON(http.StatusOK, gin.H{"name": "小明", "age": 18})

	//type User struct {
	//	Name string
	//	Age  int
	//}

	// 自定义返回的字段名成
	//type User struct {
	//	Name string `json:"name"`
	//	Age  int    `json:"age"`
	//}

	// 如果不想让某个字段返回可以使用 “-”
	type User struct {
		Name     string `json:"name"`
		Age      int    `json:"age"`
		Password string `json:"-"`
	}

	user := User{"小明", 18, "123123"}

	c.JSON(http.StatusOK, user)
}

func main() {
	router := gin.Default()

	router.GET("/getJSON", getJSON)

	router.Run(":9000")
}

2、返回 xml 和 ymal

  • c.XML()
  • c.YAML()
package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func getXML(c *gin.Context) {
	c.XML(http.StatusOK, gin.H{"name": "小明", "age": 18})
}

func getYAML(c *gin.Context) {
	c.YAML(http.StatusOK, gin.H{"name": "小明", "age": 18})
}

func main() {
	router := gin.Default()

	router.GET("/getXML", getXML)

	router.GET("/getYAML", getYAML)

	router.Run(":9000")
}

3、返回html

  • router.LoadHTMLGlob()
  • router.StaticFS()
  • router.StaticFs()
package main

import (
   "github.com/gin-gonic/gin"
   "net/http"
)

func getHtml(c *gin.Context) {
   c.HTML(http.StatusOK, "index.html", gin.H{"name": "小明"})
}

func main() {
   router := gin.Default()

   // 全局加载
   router.LoadHTMLGlob("template/*")
   // 加载目录
   router.StaticFS("/static", http.Dir("static/static"))
   // 加载静态文件
   router.StaticFile("/login.jpg", "static/login.jpg")

   router.GET("/getHtml", getHtml)

   router.Run(":9000")
}

4、重定向

  • c.Redirect()
package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func direct(c *gin.Context) {
	c.Redirect(http.StatusMovedPermanently, "http://www.baidu.com")
}

func main() {
	router := gin.Default()

	router.GET("/redirect", direct)

	router.Run(":9000")
}

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值