當(dāng)前位置:首頁(yè) > IT技術(shù) > Web編程 > 正文

Gin框架JSON渲染
2021-11-30 22:47:57

Gin框架JSON渲染

一、map渲染JSON

package main

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

func main() {
	r := gin.Default()
	r.GET("/jsonMap", func(c *gin.Context) {
		// 方法1: 使用map
		data := map[string]interface{}{
			"name":     "randysun",
			"age":      18,
			"messages": "jsonMap",
		}

		c.JSON(http.StatusOK, data)

	})

}

image-20211116215600103

二、struct渲染JOSN

package main

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

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

	r.GET("/jsonStruct", func(c *gin.Context) {
		// 方法2:通過(guò)結(jié)構(gòu)體方式
		type userInfo struct {
			Name     string `json:"name"`
			Age      int
			Messages string
			low      string
		}
		user := userInfo{
			"randySun",
			18,
			"json struct",
			"小寫(xiě)訪問(wèn)不到",
		}
		c.JSON(http.StatusOK, user)
	})
	r.Run(":9999")
}

image-20211116215545179

本文摘自 :https://www.cnblogs.com/

開(kāi)通會(huì)員,享受整站包年服務(wù)立即開(kāi)通 >