c.JSON gin.H{()} 输出空对象

c.JSON gin.H{()} outputs empty objects

我刚开始结合 Gin 框架学习 GO(lang),我决定写一些简单的 api 来获取有关酒精饮料的数据。

我目前的问题是 api(http://localhost:8080/alcohol-drinks 上的获取方法)returns 空数据对象

我的代码:

package main

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

type alcoholDrink struct {
    name             string
    description      string
    nutritionsAmount string
    nutritions       map[string]string
}

func main() {
    r := gin.Default()
    r.GET("/alcohol-drinks", func(c *gin.Context) {

        d := []alcoholDrink{
            {
                name:             "Gin",
                description:      "DescriptionGin is a distilled alcoholic drink that derives its predominant flavour from juniper berries. Gin is one of the broadest categories of spirits, all of various origins, styles, and flavour profiles, that revolve around juniper as a common ingredient",
                nutritionsAmount: "per 100 grams",
                nutritions: map[string]string{
                    "Calories":     "263",
                    "TotalFat":     "0 g",
                    "Cholesterol":  "0 mg",
                    "Sodium":       "2 mg",
                    "Carbohydrate": "0 g",
                    "Protein":      "0 g",
                },
            },
            {
                name:             "Vodka",
                description:      "odka is a clear distilled alcoholic beverage with different varieties originating in Poland and Russia. It is composed primarily of water and ethanol, but sometimes with traces of impurities and flavorings.",
                nutritionsAmount: "per 100 grams",
                nutritions: map[string]string{
                    "Calories":     "231",
                    "TotalFat":     "0 g",
                    "Cholesterol":  "0 mg",
                    "Sodium":       "1 mg",
                    "Carbohydrate": "0 g",
                    "Protein":      "0 g",
                },
            },
        }

        c.JSON(200, gin.H{
            "status": "OK",
            "code":   200,
            "data":   d,
        })

    })
    r.Run()
}

问题是,我需要如何处理变量 d 才能在浏览器中输出数据?

小写字段被认为是私有的,不会被标准 json 序列化程序序列化。

更改 alcoholDrink 类型的字段,使它们以大写字母开头:

type alcoholDrink struct {
    Name             string
    Description      string
    NutritionsAmount string
    Nutritions       map[string]string
}

如果您想在结果 json 中看到小写的名称,您可以为每个字段添加注释:

type alcoholDrink struct {
    Name             string    `json:"name"`
    Description      string    `json:"description"`
    NutritionsAmount string    `json:"nutritionsAmount"`
    Nutritions       map[string]string   `json:"nutritions"`
}