为了账号安全,请及时绑定邮箱和手机立即绑定

在浏览器中显示 Go 应用

在浏览器中显示 Go 应用

Go
三国纷争 2021-12-20 16:51:20
我编写了一个向 API 发出请求并获得 JSON 响应的应用程序。当我运行应用程序时,它会在终端中显示 json。go run main.go我想让它在浏览器中运行,我发现了这个,它允许我将一个字符串打印到浏览器。     func handler(w http.ResponseWriter, r *http.Request) {       fmt.Fprintf(w, "This is a string")   }然后在 mainhttp.HandleFunc("/", handler) log.Fatal(http.ListenAndServe("localhost:8000", nil))现在我有一个字符串被打印到屏幕上,并且我有一个来自我正在使用的 api 的 json 响应,我如何将 json 响应添加到浏览器而不是字符串?将响应放入字符串然后将其带到浏览器是否最好?目前我正在像这样向终端打印 json 响应,type Payload struct {        Page    int        Results []Data }type Data struct {        PosterPath       string  `json:"poster_path"`        Adult            bool    `json:"adult"`        Overview         string  `json:"overview"`        ReleaseDate      string  `json:"release_date"`        GenreIds         []int   `json:"genre_ids"`        Id               int     `json:"id"`        OriginalTitle    string  `json:"original_title"`        OriginalLanguage string  `json:"original_language"`        Title            string  `json:"title"`        BackdropPath     string  `json:"backdrop_path"`        Popularity       float64 `json:"popularity"`        VoteCount        int     `json:"vote_count"`        Video            bool    `json:"video"`        VoteAverage      float64 `json:"vote_average"`}然后在里面main()我这样做,    for i := 0; i < len(p.Results); i++ {            fmt.Println(            ImgUrl+p.Results[i].PosterPath, "\n", p.Results[i].Adult,            p.Results[i].Overview, "\n", p.Results[i].ReleaseDate,            p.Results[i].GenreIds, "\n", p.Results[i].Id,            p.Results[i].OriginalTitle, "\n", p.Results[i].OriginalLanguage,            p.Results[i].Title, "\n", ImgUrl+p.Results[i].BackdropPath,            p.Results[i].Popularity, "\n", p.Results[i].VoteCount,            p.Results[i].Video, "\n", p.Results[i].VoteAverage,            )构建 Web 应用程序的 Go 方法是什么?我的最终目标是接受用户输入并根据他们提供的信息重新创建我的 api 调用。
查看完整描述

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

}


查看完整回答
反对 回复 2021-12-20
  • 1 回答
  • 0 关注
  • 274 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号