我正在發出一個 JSON GET 請求,我現在正試圖將數據傳遞給我的模板以在 HTML 中呈現。使用 Python 我可以直接傳遞響應,但是使用 Go 我想我需要使用結構來重構 JSON?// index route http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { resp, err := http.Get("https://example.com/json") if err != nil { panic(err.Error()) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err.Error()) } log.Println(string(body)) err = tmpl.ExecuteTemplate(w, "index.html", body) if err != nil { panic("Oh no!") } })我是否需要通過 JSON 并手動構建一個結構來處理它,或者是否有一種簡單的方法來傳遞數據?
1 回答
大話西游666
TA貢獻1817條經驗 獲得超14個贊
此答案假定您希望傳遞未編組的 JSON 數據,而不是原始數據塊。
您可以簡單地將 JSON 解組為 a map[string]interface{},然后將其傳遞給模板。
它看起來像這樣:
var data map[string]interface{}
if err := json.Unmarshal([]byte(rawJSON), &data); err != nil {
// Handle error.
}
if err := tmpl.Execute(os.Stdout, data); err != nil {
// Handle error.
}
- 1 回答
- 0 關注
- 126 瀏覽
添加回答
舉報
0/150
提交
取消
