Golang web (5)- Send Json

Jane
May 1, 2021

--

除了send value外gin.context還支援其他泛型

例如底下的json

router.GET("/json", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{
"result": "ok",
"data": "Hello, json data.",
"developer": "jane",
})
})

利用context.json回傳json型態資料

完整code如下

package main 
import ( "github.com/gin-gonic/gin")
// return json data
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/*.html")
router.GET("/", func(ctx *gin.Context) {
ctx.HTML(200, "index.html", gin.H{}) })
router.GET("/data", func(ctx *gin.Context) {
ctx.HTML(200, "data.html", gin.H{"data": "Hello, template data."}) })
router.GET("/json", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{
"result": "ok",
"data": "Hello, json data.",
"developer": "jane",
})
})
router.Run(":8000")}
// $ curl -X GET localhost:8000/json

--

--

Jane
Jane

Written by Jane

Life’s a Struggle But You Can Win

No responses yet