我有一个 Golang 网站,我想在其中使用名为 SwaggerUI 的 SQLite 移动应用快速入门 API 显示我的 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 以某种方式对其进行格式化,那么您可以首先将返回的正文解码为一段反射(reflect)结构的结构你的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 的包,你应该查看 text/template对于有关如何对模板进行实际编程的文档,它们具有相同的界面。
这是一个简单的例子:https://play.golang.org/p/EYfV-TzoA0
在该示例中,我使用模板包来解析字符串 (scoresPage
) 并将结果输出到标准输出,但您也可以轻松地解析您的 Scores.html
文件ParseFiles并通过将 res http.ResponseWriter
而不是 os.Stdout
作为第一个参数传递给 template.Execute 来返回 http 响应中的输出.
关于html - 如何使用 html/javascript/jquery 将 golang http json 主体输出到网站页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43190185/