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")
}
相关推荐
金宗汉1 天前
《宇宙递归拓扑学:基于自指性与拓扑流形的无限逼近模型》
大数据·人工智能·笔记·算法·观察者模式
张永清-老清1 天前
每周读书与学习->JMeter主要元件详细介绍(一)配置元件
学习·jmeter·性能调优·jmeter性能测试·性能分析·干货分享
狮智先生1 天前
【学习笔记】利用meshlab进行曲面的质量检查
经验分享·笔记·课程设计·几何学
鼾声鼾语1 天前
grootN1 grootN1.5 gr00t安装方法以及使用(学习)
学习·angular.js·simulink·isaacsim·isaaclab
MYX_3091 天前
第七章 完整的模型训练
pytorch·python·深度学习·学习
新子y1 天前
【小白笔记】岛屿数量
笔记·python
Larry_Yanan1 天前
QML学习笔记(四十三)QML与C++交互:上下文属性暴露
c++·笔记·qt·学习·ui·交互
励志成为美貌才华为一体的女子1 天前
pdf解析工具---Miner-u 本地部署记录
学习·pdf
FserSuN1 天前
GraphRAG 与 Neo4j 社区版:能力边界与适用场景学习总结
学习·neo4j
学不会就看1 天前
PyTorch 张量学习
人工智能·pytorch·学习