我从api接收数据,对其进行解析,然后尝试从带有大猩猩的嵌套结构发送json响应。但是,当我构建响应json时,就像空字段一样:
{
"data": [
{},
{},
{},
{},
{}
]
}
当我逐个打印每个元素时,我可以看到正确的数据,所以我猜我的最终结构是正确构造的,但是我无法将其转换为可行的json。 我的代码的一部分:
type Data struct {
Response []Response `json:"data"`
}
type Response struct {
city string `json:"city"`
iradianceResponses []IradianceResponse `json:"iradianceResponses"`
}
type IradianceResponse struct {
Month string `json:"month"`
Ed float64 `json:"ed"`
Em float64 `json:"em"`
Hd float64 `json:"hd"`
Hm float64 `json:"hm"`
Sdm float64 `json:"sdm"`
}
type City struct {
name string
latitude float64
longitude float64
}
var cities []City
func initCities() {
cities = []City{}
}
func getCall(w http.ResponseWriter, r *http.Request) {
var responses []Response
ch := make(chan Response)
for _, city := range cities {
go MakeRequest(city, ch)
}
for range cities {
resp := <-ch
responses = append(responses, resp)
}
data := &Data{
Response: responses,
}
responseFinal, err := json.Marshal(data)
if err != nil {
fmt.Println(err)
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
w.Write(responseFinal)
}
func parseBody(body string, cityName string) Response {
temp := strings.Split(body, "\n")
i := 10
var iradianceResponses []IradianceResponse
for i < 22 {
#some parsing
iradianceResponses = append(iradianceResponses, IradianceResponse{
Month: month,
Ed: ed,
Em: em,
Hd: hd,
Hm: hm,
Sdm: sdm,
})
i++
}
return Response{
city: cityName,
iradianceResponses: iradianceResponses,
}
}
func MakeRequest(city City, ch chan<- Response) {
resp, _ := http.Get(fmt.Sprintf(url))
body, _ := ioutil.ReadAll(resp.Body)
response := parseBody(string(body), city.name)
ch <- response
}
func main() {
initCities()
router := mux.NewRouter()
router.HandleFunc("/call", getCall).Methods("GET")
http.ListenAndServe(":8000", router)
}