2 回答

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
一種選擇是使用Context.Data()
您提供要發(fā)送的數(shù)據(jù)(以及內(nèi)容類(lèi)型)的位置:
func GetDefault(c *gin.Context)? {
? ? jsonData := []byte(`{"msg":"this worked"}`)
? ? c.Data(http.StatusOK, "application/json", jsonData)
}
您還可以使用內(nèi)容類(lèi)型常量:
func GetDefault(c *gin.Context)? {
? ? jsonData := []byte(`{"msg":"this worked"}`)
? ? c.Data(http.StatusOK, gin.MIMEJSON, jsonData)
}
如果您的數(shù)據(jù)可用作string
值并且很大,則可以避免將其轉(zhuǎn)換為:[]byte
Context.DataFromReader()
func GetDefault(c *gin.Context) {
? ? jsonStr := `{"msg":"this worked"}`
? ? c.DataFromReader(http.StatusOK,
? ? ? ? int64(len(jsonStr)), gin.MIMEJSON, strings.NewReader(jsonStr), nil)
}
如果您的 JSON 為io.Reader
,例如 ,則此解決方案也適用os.File
。

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
gin.H
您可以在響應(yīng)中使用該結(jié)構(gòu):
c.JSON(http.StatusOK, gin.H{"msg":"this worked"})
- 2 回答
- 0 關(guān)注
- 239 瀏覽
添加回答
舉報(bào)