Gin 学习笔记01-数据返回

Gin 数据返回

  • [1、返回 string 和 json](#1、返回 string 和 json)
  • [2、返回 xml 和 ymal](#2、返回 xml 和 ymal)
  • 3、返回html
  • 4、重定向

1、返回 string 和 json

  • c.String()
  • c.JSON()
go 复制代码
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()
go 复制代码
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()
go 复制代码
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()
go 复制代码
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")
}
相关推荐
星幻元宇VR26 分钟前
VR科普大空间:沉浸式公共教育新模式
科技·学习·安全·vr·虚拟现实
@蓝莓果粒茶1 小时前
【Unity笔记】保姆级AssetBundle详解(含代码+避坑指南)
笔记·游戏·unity
kobesdu2 小时前
【ROS2实战笔记-20】ROS2 bag 录播与时间模拟:从基础操作到高级调试技巧
笔记·机器人·ros·ros2
笨鸟先飞的橘猫2 小时前
MMO游戏中的“跨服团队副本”匹配与状态同步系统
分布式·学习·游戏·lua·skynet
kobesdu3 小时前
【ROS2实战笔记-18】ROS2 通信的隐秘控制:DDS 配置参数如何决定系统性能
网络·人工智能·笔记·机器人·开源·ros·人形机器人
雨落在了我的手上4 小时前
如何学习java?
java·开发语言·学习
吃好睡好便好5 小时前
汽车基本组成
学习·汽车
nnsix5 小时前
Unity 动画 Avatar 笔记
笔记·unity·游戏引擎
拾忆丶夜5 小时前
unity 热力图学习
学习·unity·游戏引擎
red_redemption6 小时前
自由学习记录(183)
学习·ue项目改名字的学问