如何使用html/javascript/jquery将golang http json正文输出到网站页面



我有一个Golang网站,我想使用SQLite的移动应用程序快速入门的API称为SwaggerUI显示UWP游戏的"分数"。我通过执行HTTP GET请求来获得分数。问题是分数以 JSON 格式输出到 Golang 控制台。我想在实际网站上显示分数。我如何在前端调用我的 golang 函数才能做到这一点?前端是用HTML/Javascript/JQuery编写的。

这是我的Golang函数,它向SwaggerUI执行HTTP请求并输出到Golang控制台:

func scoresPage(res http.ResponseWriter, req *http.Request) {
//Connecting to SwaggerUI API to get Scores from Azure for UWP Application
req, err := http.NewRequest("GET", os.ExpandEnv("https://brainworksappservice.azurewebsites.net/tables/TodoItem?$select=score"), nil)
if err != nil {
log.Fatal(err)
}
//You have to specify these headers
req.Header.Set("Accept", "application/json")
//If you do not specify what version your API is, you cannot receive the JSON
req.Header.Set("Zumo-Api-Version", "2.0.0")
//Do the request
resp, err := http.DefaultClient.Do(req)
//Error if the request cannot be done
if err != nil {
log.Fatal(err)
}
//You need to close the Body everytime, as if you don't you could leak information
defer resp.Body.Close()
//Read all of the information from the body
body, err := ioutil.ReadAll(resp.Body)
//Error if the info cannot be read
if err != nil {
log.Fatal(err)
}
//Write the JSON to the standard output (the Console)
_, err = os.Stdout.Write(body)
//Error if the info cannot be output to the console
if err != nil {
log.Fatal(err)
}
http.ServeFile(res, req, "Scores.html")
} `

这是提供网站并处理分数页面的主要功能:

func main() {
http.HandleFunc("/scores", scoresPage)
//serve on the port 8000 forever
http.ListenAndServe(":8000", nil)
} 

假设您不想将 json 按原样转储到您的页面上,而是使用 html 和 CSS 以某种方式格式化它,那么您可以首先将返回的正文解码为反映 JSON 结构的结构片。例如像这样:

type Score struct {
Id        string    `json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Version   string    `json:"version"`
Deleted   bool      `json:"deleted"`
Text      string    `json:"text"`
Complete  bool      `json:"complete"`
Score     string    `json:"score"`
}
scores := []*Score{}
if err := json.Unmarshal(body, &scores); err != nil {
panic(err)
}
fmt.Println(scores[0])

https://play.golang.org/p/m_ySdZulqy

解码 json 后,您可以使用 Go 的模板包循环查看分数并根据需要对其进行格式化。虽然您应该使用 html/template 包来呈现 html,但您应该查看有关如何实际编程模板的文档的文本/模板,它们具有相同的界面。

下面是一个简单的示例:https://play.golang.org/p/EYfV-TzoA0

在该示例中,我使用模板包来解析字符串(scoresPage)并将结果输出到stdout,但是您可以使用ParseFiles轻松解析Scores.html文件,并通过传递res http.ResponseWriter而不是os.Stdout作为模板的第一个参数来返回http响应中的输出。执行。

最新更新