登录
首页 >  Golang >  Go问答

使用Golang将API中的数据解析为HTML格式

来源:stackoverflow

时间:2024-02-11 23:18:23 200浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《使用Golang将API中的数据解析为HTML格式》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我是 go 语言新手,所以我有一个问题。我有 api,需要将信息解析到卡片上。我有一个脚本,可以从 api 获取所有信息并将其放入卡中的字段中。我了解如何获取一部分信息。但我需要使用 api 中的不同信息创建许多卡片并将它们放置在 html 页面上。我怎样才能做到这一点?

用于 html 托管的 server.go 文件。

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
    "text/template"
)

type response struct {
    artists   string `json:"artists"`
    locations string `json:"locations"`
    dates     string `json:"dates"`
    relation  string `json:"relation"`
}
type artist struct {
    id           int      `json:"id"`
    image        string   `json:"image"`
    name         string   `json:"name"`
    members      []string `json:"members"`
    creationdate string   `json:"creationdate"`
    firstalbum   string   `json:"firstalbum"`
}

func main() {
    http.handlefunc("/", formhandler) // to define the path/page, where we are going to use the mentioned function
    fmt.printf("starting server at port 8080\n")
    if err := http.listenandserve(":8080", nil); err != nil { //to initialise our server on :8080
        log.fatal("http status 500 - internal server error: %s", err)
    }
}
func formhandler(w http.responsewriter, r *http.request) {
    response, err := http.get("https://groupietrackers.herokuapp.com/api")
    if err != nil {
        fmt.print(err.error())
        os.exit(1)
    }

    responsedata, err := ioutil.readall(response.body)
    if err != nil {
        log.fatal(err)
    }

    var responseobject response

    json.unmarshal(responsedata, &responseobject)
    artist_link, err := http.get(responseobject.artists)
    if err != nil {
        fmt.print(err.error())
        os.exit(1)
    }

    artistdata, err := ioutil.readall(artist_link.body)
    if err != nil {
        log.fatal(err)
    }

    var artistobject artist

    json.unmarshal(artistdata, &artistobject)
    t, _ := template.parsefiles("index.html")
    t.execute(w, artistobject)
}

index.html 文件,用于向 pearson 显示信息。





    
    
    


    


  

groupie-tracker

{{range .}}

{{ .Name }}

{{ .FirstAlbum }}

{{end}}

正确答案


有几种处理模板的方法。但您肯定希望解析一次文件并存储它们。

一种方法是创建一个全局变量并将模板存储在其中。

您还期望使用 artist 结构的一部分,对吗?所以你想解组成一个切片,而不是单个对象。如果您检查 unmarshal 上的错误,您会看到这一点。

最后,creationdate 字段存在问题。解组错误也表明了这一点。

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
    "text/template"
)

type Response struct {
    Artists   string `json:"artists"`
    Locations string `json:"locations"`
    Dates     string `json:"dates"`
    Relation  string `json:"relation"`
}
type Artist struct {
    ID           int      `json:"id"`
    Image        string   `json:"image"`
    Name         string   `json:"name"`
    Members      []string `json:"members"`
    CreationDate int      `json:"creationDate"`
    FirstAlbum   string   `json:"firstAlbum"`
}

var temp *template.Template

func main() {
    temp = template.Must(template.ParseFiles("index.html"))

    http.HandleFunc("/", formHandler) // to define the path/page, where we are going to use the mentioned function
    fmt.Printf("Starting server at port 8080\n")
    if err := http.ListenAndServe(":8080", nil); err != nil { //to initialise our server on :8080
        log.Fatal("HTTP status 500 - Internal server error: %s", err)
    }
}
func formHandler(w http.ResponseWriter, r *http.Request) {
    response, err := http.Get("https://groupietrackers.herokuapp.com/api")
    if err != nil {
        fmt.Print(err.Error())
        os.Exit(1)
    }

    responseData, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatal(err)
    }

    var responseObject Response

    json.Unmarshal(responseData, &responseObject)
    artist_link, err := http.Get(responseObject.Artists)
    if err != nil {
        fmt.Print(err.Error())
        os.Exit(1)
    }

    artistData, err := ioutil.ReadAll(artist_link.Body)
    if err != nil {
        log.Fatal(err)
    }

    var artists []Artist

    err = json.Unmarshal(artistData, &artists)
    if err != nil {
        log.Fatal(err)
    }

    temp.Execute(w, artists)
}

今天关于《使用Golang将API中的数据解析为HTML格式》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>