You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Go Fiber应用中通过循环外部数据填充结构体列表的方法

解决方案实现步骤
  1. 修正Report结构体的字段可见性与序列化标签
    要让结构体字段能被JSON序列化、且同包内函数可访问,字段首字母必须大写;建议添加json标签指定返回的JSON字段名(符合接口规范)。

  2. 构建Report结构体列表
    在getReportData中初始化Report类型切片,循环遍历handler1返回的数据集,把需要的字段值赋值到新的Report实例,再加入切片。

  3. 转换为JSON并返回接口响应
    在Fiber的handler函数中,调用getReportData获取整理好的列表,用Fiber上下文的c.JSON()方法直接返回JSON响应,该方法会自动处理序列化和响应头设置。


完整代码示例

handler2.go 代码

package handlers

import (
    "github.com/gofiber/fiber/v2"
)

// 修正后的Report结构体,字段首字母大写并添加JSON标签
type Report struct {
    Contact  string `json:"contact"`
    Date     string `json:"date"`
    Resource string `json:"resource"`
}

// 获取并整理报告数据,返回Report切片
func getReportData() []Report {
    // 调用handler1中的GetReport函数,假设返回[]*SourceData类型(handler1定义的数据源结构体)
    sourceData := GetReport()
    // 初始化Report切片,预分配容量提升性能
    reportList := make([]Report, 0, len(sourceData))
    
    for _, item := range sourceData {
        // 从源数据提取指定字段,填充Report实例
        report := Report{
            Contact:  item.Contact,  // 对应handler1返回结构体的Contact字段
            Date:     item.Date,     // 对应handler1返回结构体的Date字段
            Resource: item.Resource, // 对应handler1返回结构体的Resource字段
        }
        reportList = append(reportList, report)
    }
    return reportList
}

// Fiber接口handler,返回JSON格式的报告数据
func ReportHandler(c *fiber.Ctx) error {
    reports := getReportData()
    // 返回标准格式的接口响应
    return c.JSON(fiber.Map{
        "code": 200,
        "data": reports,
        "msg":  "报告数据获取成功",
    })
}

handler1.go 中GetReport函数示例(同包)

package handlers

// handler1定义的数据源结构体,字段首字母大写确保同包可访问
type SourceData struct {
    Contact  string
    Date     string
    Resource string
    // 其他从外部API获取的字段
}

// 从外部API获取数据并返回SourceData切片
func GetReport() []SourceData {
    // 此处实现调用外部API、解析数据为SourceData切片的逻辑
    // 以下为模拟返回数据
    return []SourceData{
        {Contact: "user1@example.com", Date: "2024-05-20", Resource: "server-01"},
        {Contact: "user2@example.com", Date: "2024-05-21", Resource: "server-02"},
    }
}

关键注意事项

  • 字段可见性:Go语言仅首字母大写的标识符可跨函数访问,所以源结构体和自定义Report结构体的目标字段必须大写。
  • JSON序列化:若需自定义JSON字段名,通过json:"xxx"标签指定;不指定则默认使用结构体字段名(大写)。
  • Fiber响应优化:使用c.JSON()无需手动调用encoding/json的Marshal方法,会自动设置Content-Type: application/json响应头。

内容的提问来源于stack exchange,提问作者Robert Campbell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 08:05:23