将字符串连接到结构片段

时间:2018-10-22 21:47:59

标签: go struct slice

我正在尝试创建一个端点Go API,供前端JavaScript图形库使用。

应该发生什么:

  1. /数据端点以获取JSON数据数组。
  2. 数据只是go结构的一部分,在此示例中仅为两个,但将超过10000。
  3. 图形库需要其他元数据。将其保存为名为AdditionalInfo的变量。
  4. 问题是,当我想对AdditionalInfo + AllAgents进行编码时,它不允许我将带有一部分结构的字符串连接起来。
  5. 在结构片的末尾还需要有]`以使其有效为JSON

问题:

  1. 如何在结构的前面和后面添加其他数据?
  2. 将结构附加到结构的切片上是否有效?
  3. 最好创建一个已知长度的切片,然后使用range附加到它上面?

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
        "net/http"
        "os"
    )
    
    func main() {
        port := os.Getenv("PORT")
        if port == "" {
            port = "443"
            log.Printf("Defaulting to port %s", port)
        }
    
        http.HandleFunc("/data", TrySnipped)
        log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
    
    }
    
    func TrySnipped(w http.ResponseWriter, r *http.Request) {
        w.Header().Add("Content-Type", "application/json")
        var AllAgents []SingleAgent
        AllAgents = append(AllAgents, FirstAgent)
        AllAgents = append(AllAgents, SecondAgent)
    
        json.NewEncoder(w).Encode(AllAgents)
    
    }
    
    var AdditionalInfo = `"meta": {
                "page": 1,
                "pages": 1,
                "perpage": -1,
                "total": 350,
                "sort": "asc",
                "field": "RecordID"
            },
            "data": [`
    
    type SingleAgent struct {
        RecordID             string `json:"RecordID"`
        OldEmployeeID        string `json:"OldEmployeeID"`
        NewEmployeeID        string `json:"NewEmployeeID"`
        AgentRank            int    `json:"AgentRank"`
        AgentName            string `json:"AgentName"`
        AgentEmail           string `json:"AgentEmail"`
        TeamManager          string `json:"TeamManager"`
        LineOfBusiness       string `json:"LineOfBusiness"`
        FitnessCampStartDate string `json:"FitnessCampStartDate"`
        FitnessCampEndDate   string `json:"FitnessCampEndDate"`
        FitnessCampStatus    int    `json:"FitnessCampStatus"`
        AgentFitnessRank     int    `json:"AgentFitnessRank"`
        LatestMetricA        int    `json:"MetricA"`
        LatestMetricB        int    `json:"MetricB"`
        LatestMetricC        int    `json:"MetricC"`
        LatestMetricD        int    `json:"MetricD"`
        LatestMetricE        int    `json:"MetricD"`
        SiteName             string `json:"SiteName"`
        SiteID               string `json:"SiteID"`
        PostCampWeek1        string `json:"PostCampWeek1"`
        PostCampWeek2        string `json:"PostCampWeek2"`
        PostCampWeek3        string `json:"PostCampWeek3"`
    }
    
    var FirstAgent = SingleAgent{
        RecordID:             "30",
        OldEmployeeID:        "785114544",
        NewEmployeeID:        "10785114544",
        AgentRank:            3,
        AgentName:            "Shandeigh Rawsen",
        AgentEmail:           "shandeigh.rawsen@gmail.com",
        TeamManager:          "Oliver Lamplugh",
        LineOfBusiness:       "BMS",
        FitnessCampStartDate: "8/13/2018",
        FitnessCampEndDate:   "10/7/2018",
        FitnessCampStatus:    1,
        AgentFitnessRank:     1,
        LatestMetricA:        77,
        LatestMetricB:        167,
        LatestMetricC:        496,
        LatestMetricD:        72,
        LatestMetricE:        80,
        SiteName:             "Montreal",
        SiteID:               "4",
        PostCampWeek1:        "10/2/2018",
        PostCampWeek2:        "10/9/2018",
        PostCampWeek3:        "10/19/2018",
    }
    var SecondAgent = SingleAgent{
        RecordID:             "29",
        OldEmployeeID:        "980433290",
        NewEmployeeID:        "10980433290",
        AgentRank:            4,
        AgentName:            "Terrijo Dewberry",
        AgentEmail:           "terrijo.deberry@gmail.com",
        TeamManager:          "Oliver Lamplugh",
        LineOfBusiness:       "BTSW",
        FitnessCampStartDate: "7/28/2018",
        FitnessCampEndDate:   "9/23/2018",
        FitnessCampStatus:    2,
        AgentFitnessRank:     2,
        LatestMetricA:        88,
        LatestMetricB:        92,
        LatestMetricC:        716,
        LatestMetricD:        78,
        LatestMetricE:        66,
        SiteName:             "Montreal",
        SiteID:               "2",
        PostCampWeek1:        "10/2/2018",
        PostCampWeek2:        "10/9/2018",
        PostCampWeek3:        "10/15/2018",
    }
    

1 个答案:

答案 0 :(得分:2)

将其他信息,座席和结束括号写到响应中:

 io.WriteString(w, "{")
 io.WriteString(w, AdditionalInfo)
 json.NewEncoder(w).Encode(AllAgents)
 io.WriteString(w, "]}")  // closing ] for data and closing } for root

请注意,这在代理周围编码了[ ]的两个级别。尚不清楚这是否是您想要的。

另一种方法是创建一个匹配输出结构的Go值并将其编码:

v := map[string]interface{}{
    "meta": map[string]interface{}{
        "page":    1,
        "pages":   1,
        "perpage": -1,
        "total":   350,
        "sort":    "asc",
        "field":   "RecordID",
    },
    "data": AllAgents,
 }
 if err := json.NewEncoder(w).Encode(v); err != nil {
    // handle error
 }

同样,目前尚不清楚您希望在代理周围进行多少嵌套。您可能需要以下变体:

v := map[string]interface{}{
    "meta": map[string]interface{}{
        "page":    1,
        "pages":   1,
        "perpage": -1,
        "total":   350,
        "sort":    "asc",
        "field":   "RecordID",
    },
    "data": []interface{}{AllAgents},
 }
 if err := json.NewEncoder(w).Encode(v); err != nil {
    // handle error
 }

re:效率创建最终尺寸的切片通常比使用append逐渐增加切片的效率更高。通过使用切片指针[]*SingleAgent代替切片结构值[]SingleAgent可能会获得一些效果。