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:"-"
标签排除了 JSON 编码和解码的字段。定义一个与 Person 具有相同字段的新类型,并改为对该类型的一个 slice 进行编码(为简洁起见,省略了一些字段):
package main
import (
"encoding/json"
"fmt"
"log"
)
type Profile struct {
ID int `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
}
type ProfileSummary struct {
ID int `json:"-"`
Username string `json:"username"`
Email string `json:"-"`
}
func main() {
var profiles []Profile
profiles = append(profiles, Profile{Username: "john", Email: "john.doe@example.com"})
profiles = append(profiles, Profile{Username: "jane", Email: "jane.doe@example.com"})
summaries := make([]ProfileSummary, len(profiles))
for i, p := range profiles {
summaries[i] = ProfileSummary(p)
}
b, err := json.MarshalIndent(summaries, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(b))
}
在 Playground 上试试:https://play.golang.org/p/y3gP5IZDWzl
关于arrays - 使用结构变量数组访问结构变量golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49432716/