1 回答
TA贡献1785条经验 获得超4个赞
如果您可以直接从 API 向您的用户发送响应,请使用io.Copy。您可以在将 api 请求转发给用户之前检查它是否成功,如果没有,则发送错误。
某些 API 在标头中发送信息,例如您如何处理速率限制。因此,您也可以在中继之前检查标题。
func handler(w http.ResponseWriter, r *http.Request) {
resp, err := http.Get("http://jsonplaceholder.typicode.com/posts") // your request to the api
w.Header().Set("Content-Type", "application/javascript")
if err == nil && resp.StatusCode == http.StatusOK {
io.Copy(w, resp.Body)
} else {
json.NewEncoder(w).Encode(err)
}
}
这避免了在您的应用程序上进行任何新分配。
如果您想按照评论中的说明向您的客户发送 html,请使用html/template包。
您当然可以手动准备一个 html 字符串并将其发送给客户端。但我认为很明显,使用模板可以使代码更清晰、更易于维护。它还提供自动转义。
例如下面将会使Overview您的每一个的部分Results从Payload p
func handler(w http.ResponseWriter, r *http.Request) {
// Make your api call and prepare the `Payload` object (from your example in the question)
for i := 0; i < len(p.Results); i++ {
fmt.Println(p.Results[i].Overview) // Prints to your terminal
}
// Following sends same information as above to the browser as html
t, err := template.New("foo").Parse(`
{{define "T"}}
<html><ul>{{range .Results}}<li>{{.Overview}}</li>{{end}}</ul></html>
{{end}}`)
err = t.ExecuteTemplate(w, "T", p) // This writes the client response
}
- 1 回答
- 0 关注
- 274 浏览
添加回答
举报
