dsjmrpym220113739 2017-04-03 16:52
浏览 93

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

I've got a Golang Website where I want to display 'scores' from my UWP Game using SQLite's Mobile App Quickstart's API called SwaggerUI. I am getting the scores by doing a HTTP GET request. The problem is that the scores output to the Golang console in JSON Format. I want to display the scores onto the actual website. How could I call my golang function in the Frontend in order to do this? The frontend is written in HTML/Javascript/JQuery.

This is my Golang Function that does the HTTP Request to SwaggerUI and outputs to the Golang Console:

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")
} `

This is the main Function which serves up the website and handles the scores page:

func main() {
http.HandleFunc("/scores", scoresPage)

//serve on the port 8000 forever
http.ListenAndServe(":8000", nil)
} 
  • 写回答

1条回答 默认 最新

  • duanqian6295 2017-04-03 20:49
    关注

    Assuming, that you don't want to dump the json as is onto you page but instead format it in some way with html and css, then you could first decode the returned body into a slice of structs that mirror the structure of your json. For example like this:

    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

    After you've decoded the json you can use Go's template package to loop over the scores and format them as you wish. While you should use the html/template package for rendering html you should check out text/template for the documentation on how to actually program the templates, they have the same interface.

    Here's a quick example: https://play.golang.org/p/EYfV-TzoA0

    In that example I'm using the template package to parse a string (scoresPage) and output the result to stdout, but you can just as easily parse your Scores.html file with ParseFiles and return the output in the http response by passing the res http.ResponseWriter instead of os.Stdout as the first argument to template.Execute.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。