go 语言 Gin框架 接收请求后,返回各种格式的数据

以下内容转载自 https://blog.csdn.net/guofeng93/article/details/92798948

package main

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

func main() {
  //1. 注册一个路由器
  router := gin.Default()

  //2. 注册路由处理

  //默认请求  http://localhost:8080/
  router.GET("/", func(c *gin.Context) {
     c.String(http.StatusOK, fmt.Sprintln(gin.H{"data":"默认请求"}))
  })
  
  //post 请求  string 格式话   http://localhost:8080/string
  router.GET("/string", func(c *gin.Context) {
     c.String(http.StatusOK, fmt.Sprintln("post 请求  string 格式话"))
  })

  //post 请求  json 格式话    http://localhost:8080/json
  router.POST("/json",func (c *gin.Context)  {
    c.JSON(http.StatusOK,gin.H{"name":"post 请求  json 格式话","age":18})
  })

  //delete 请求 xml 格式化   http://localhost:8080/xml
  router.DELETE("/xml",func (c *gin.Context)  {
    c.XML(http.StatusOK,gin.H{"name":"delete 请求 xml 格式化","age":18})
  })

  //patch 请求  yaml 格式化   http://localhost:8080/yaml
  router.PATCH("/yaml",func (c *gin.Context)  {
    c.YAML(http.StatusOK,gin.H{"name":"patch 请求 yaml 格式化","age":18})
  })

  //get请求 html界面显示   http://localhost:8080/html
  router.GET("/html",func (c *gin.Context)  {
    router.LoadHTMLGlob("../view/tem/index/*")  //这是前台的index
    // router.LoadHTMLGlob("../view/tem/admin/*")  //这是后台的index
    // router.LoadHTMLFiles("../view/tem/index.html")  //指定加载某些文件
    c.HTML(http.StatusOK,"index.html",nil)
  })

  //3. 运行(默认是8080端口)
  router.Run()
}

 

 

更详细的 参考 https://blog.csdn.net/csdniter/article/details/103870034

html渲染

func main() {
	r := gin.Default()
	r.LoadHTMLGlob("templates/**/*")
	//r.LoadHTMLFiles("templates/posts/index.html", "templates/users/index.html")
	r.GET("/posts/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "posts/index.html", gin.H{
			"title": "posts/index",
		})
	})

	r.GET("users/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "users/index.html", gin.H{
			"title": "users/index",
		})
	})

	r.Run(":8080")
}

JSON渲染

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

	// gin.H 是map[string]interface{}的缩写
	r.GET("/someJSON", func(c *gin.Context) {
		// 方式一:自己拼接JSON
		c.JSON(http.StatusOK, gin.H{"message": "Hello world!"})
	})
	r.GET("/moreJSON", func(c *gin.Context) {
		// 方法二:使用结构体
		var msg struct {
			Name    string `json:"user"`
			Message string
			Age     int
		}
		msg.Name = "小王子"
		msg.Message = "Hello world!"
		msg.Age = 18
		c.JSON(http.StatusOK, msg)
	})
	r.Run(":8080")
}

XML渲染

func main() {
	r := gin.Default()
	// gin.H 是map[string]interface{}的缩写
	r.GET("/someXML", func(c *gin.Context) {
		// 方式一:自己拼接JSON
		c.XML(http.StatusOK, gin.H{"message": "Hello world!"})
	})
	r.GET("/moreXML", func(c *gin.Context) {
		// 方法二:使用结构体
		type MessageRecord struct {
			Name    string
			Message string
			Age     int
		}
		var msg MessageRecord
		msg.Name = "小王子"
		msg.Message = "Hello world!"
		msg.Age = 18
		c.XML(http.StatusOK, msg)
	})
	r.Run(":8080")
}

YMAL渲染

r.GET("/someYAML", func(c *gin.Context) {
	c.YAML(http.StatusOK, gin.H{"message": "ok", "status": http.StatusOK})
})
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在gin框架接收POST请求并在请求到达处理程序之前进行中间件处理,可以使用gin的中间件功能。以下是一个示例中间件,它可以将POST请求请求体中的JSON解析为一个结构体,并将其绑定到请求的上下文中: ```go func JsonMiddleware() gin.HandlerFunc { return func(c *gin.Context) { if c.Request.Method == "POST" { var data interface{} err := c.BindJSON(&data) if err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } c.Set("json_data", data) } c.Next() } } ``` 在这个中间件中,我们首先检查请求的HTTP方法是否为POST。如果是,我们尝试将请求体中的JSON解析为一个结构体。如果解析失败,我们返回一个HTTP 400错误响应,并终止请求。否则,我们将解析后的数据绑定到请求上下文的“json_data”键中,并继续处理请求。 要在gin应用程序中使用这个中间件,我们只需要在路由注册之前将其添加到应用程序的中间件链中: ```go router := gin.Default() router.Use(JsonMiddleware()) router.POST("/my-endpoint", func(c *gin.Context) { data := c.MustGet("json_data") // 处理请求数据 }) ``` 在这个示例中,我们使用gin.Default()创建一个新的路由器实例,并使用JsonMiddleware()函数添加一个中间件到路由器的中间件链中。然后,我们注册一个POST处理程序,该处理程序使用c.MustGet("json_data")从请求上下文中获取JSON解析后的数据,并对数据进行处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值