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")
}
相关推荐
潇-xiao21 分钟前
进程状态 + 进程优先级切换调度-进程概念(5)
linux·笔记
骁的小小站31 分钟前
HDLBits刷题笔记和一些拓展知识(十一)
开发语言·经验分享·笔记·其他·fpga开发
北风toto1 小时前
python学习DataFrame数据结构
数据结构·python·学习
njsgcs2 小时前
ParaCAD 笔记 png 图纸标注数据集
笔记
Andy杨2 小时前
20250710-2-Kubernetes 集群部署、配置和验证-网络组件存在的意义?_笔记
网络·笔记·kubernetes
qq_386322693 小时前
华为网路设备学习-26(BGP协议 一)
学习
DKPT3 小时前
Java设计模式之行为型模式(责任链模式)介绍与说明
java·笔记·学习·观察者模式·设计模式
L_autinue_Star3 小时前
手写vector容器:C++模板实战指南(从0到1掌握泛型编程)
java·c语言·开发语言·c++·学习·stl
崔高杰4 小时前
微调性能赶不上提示工程怎么办?Can Gradient Descent Simulate Prompting?——论文阅读笔记
论文阅读·人工智能·笔记·语言模型
KhalilRuan4 小时前
Unity Demo——3D平台跳跃游戏笔记
笔记·游戏·unity·游戏引擎