【发布时间】:2018-09-01 03:07:39
【问题描述】:
func GetprofilesApi(c *gin.Context) {
var p Profile
profiles, err, count := p.GetProfiles()
if err != nil {
log.Fatalln(err)
}
c.JSON(http.StatusOK, gin.H{
"Number of Results": count,
"profiles": profiles,
}) }
//Getprofiles() function
func (p *Profile) GetProfiles() (profiles []Profile, err error, count int) {
profiles = make([]Profile, 0)
rows, err := db.Query("SELECT id, firstname, lastname, email, username, phone, function FROM profile")
defer rows.Close()
if err != nil {
return
}
//counting rows
for rows.Next() {
var profile Profile
rows.Scan(&profile.ID, &profile.FirstName, &profile.LastName, &profile.Email, &profile.Username, &profile.Phone, &profile.Function)
profiles = append(profiles, profile)
count = count + 1
}
if err = rows.Err(); err != nil {
return
}
return}
我在获取每个对象的用户名配置文件时遇到了问题
您可能会看到 Getprofiles() 返回所有字段,因此在 GetprofilesApi() 中我只想返回 json 结果中的用户名字段
感谢您的任何建议!
配置文件结构是:
type Profile struct {
ID int `json:"id"`
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
Username string `json:"username"`
Email string `json:"email"`
Phone string `json:"phone"`
Function string `json:"function"`}
【问题讨论】:
-
我不明白这个问题。请粘贴您要返回的示例 JSON 文档。
-
@Peter 感谢您的合作,这里是我的结果的截图(通常它会给我所有的配置文件字段,但我只想拥有每个对象的用户名字段
-
这个问题不清楚。请提供有关您的期望、您尝试过的内容以及您正在尝试做的事情的更多信息。
-
@JakeHeidt 我编辑添加了附加信息,希望问题能被理解
-
@dev_medo 您可以仅从配置文件中要公开的那些字段创建
map[string]interface{},并编组该映射而不是结构。
标签: arrays json go struct interface