如何从MySQL中选择数据,然后将其附加到新结构中并将其转换为字节

I want to read data from a MySQL database using Go Language. The script is like this

func GetAllCountry() []*Country{

    dbConnection := db.ConnectMySQL()

    rows, err := dbConnection.Query("SELECT id, country_code, country_name, phone_code, icon FROM country;")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    country := new(Country)
    var countries []*Country
    for rows.Next() {
        err := rows.Scan(&country.id, &country.country_code, &country.country_name, &country.phone_code, &country.icon)
        if err != nil {
            log.Fatal(err)
        }
        countries = append(countries, country)
        fmt.Println(country)
    }
    return countries
}

Data that returned will save into object Struct. The struct is like this

type Country struct {
    id              int `json:"Country.id"`
    country_code    string `json:"Country.country_code"`
    country_name    string `json:"Country.country_name"`
    phone_code      string `json:"Country.phone_code"`
    icon            string `json:"Country.icon"`
}

In the oher files, I am creating a function to get all data. I call that function, then convert it into []byte because it used to send it into MessageBroker.

Here is the function to convert it into []byte

func GetCountry(msg string) []byte {

    // country := new(countryModel.Country)
    var countries []*countryModel.Country

    countries = countryModel.GetAllCountry()
    log.Println("Show result: ", countries)

    jsResult, err := json.Marshal(countries)

    if err != nil {
        logger.Error(err, "Failed on GetCountry")
    }


    log.Println("Show result JSON: ", jsResult)

    return jsResult
}

But the returned result at GetCountry function is not what I want. In that function, I get

[
  {},
  {}
]

I show the data on my console.

&{1 ID Indonesia +62 no-data}
&{2 MY Malaysia +60 no-data}
2017/03/20 17:55:27 Show result:  [0xc8200ba410 0xc8200ba410]
2017/03/20 17:55:27 Show result JSON:  [91 123 125 44 123 125 93]

Please help.

As mentioned by @M-AbdelRahman in the comment, your Country struct fields need to be exported (those that start with an uppercase letter) because json.Marshal skips over fields that are unexported (those that start with a lowercase letter) and that's why you're getting back {}.

type Country struct {
    Id             int `json:"Country.id"`
    CountryCode    string `json:"Country.country_code"`
    CountryName    string `json:"Country.country_name"`
    PhoneCode      string `json:"Country.phone_code"`
    Icon           string `json:"Country.icon"`
}

Your scan will have to change accordingly.

err := rows.Scan(&country.Id, &country.CountryCode, &country.CountryName, &country.PhoneCode, &country.Icon)