使用Golang将许多数据从API解析为HTML。

huangapple go评论123阅读模式
英文:

Parse many data from api to html with golang

问题

我是Go语言的新手,所以我有一个问题。我有一个API,我需要从中解析信息到卡片中。我有一个脚本,它从API中获取所有信息,并将其放入卡片的字段中。我知道如何获取一部分信息。但是我需要根据API中的不同信息创建多个具有不同信息的卡片,并将它们放置在HTML页面上。我该如何做到这一点?

server.go文件用于HTML托管。

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. "os"
  9. "text/template"
  10. )
  11. type Response struct {
  12. Artists string `json:"artists"`
  13. Locations string `json:"locations"`
  14. Dates string `json:"dates"`
  15. Relation string `json:"relation"`
  16. }
  17. type Artist struct {
  18. ID int `json:"id"`
  19. Image string `json:"image"`
  20. Name string `json:"name"`
  21. Members []string `json:"members"`
  22. CreationDate string `json:"creationDate"`
  23. FirstAlbum string `json:"firstAlbum"`
  24. }
  25. func main() {
  26. http.HandleFunc("/", formHandler) // 定义我们将使用的路径/页面,以及我们将使用的函数
  27. fmt.Printf("Starting server at port 8080\n")
  28. if err := http.ListenAndServe(":8080", nil); err != nil { // 在端口8080上初始化我们的服务器
  29. log.Fatal("HTTP status 500 - Internal server error: %s", err)
  30. }
  31. }
  32. func formHandler(w http.ResponseWriter, r *http.Request) {
  33. response, err := http.Get("https://groupietrackers.herokuapp.com/api")
  34. if err != nil {
  35. fmt.Print(err.Error())
  36. os.Exit(1)
  37. }
  38. responseData, err := ioutil.ReadAll(response.Body)
  39. if err != nil {
  40. log.Fatal(err)
  41. }
  42. var responseObject Response
  43. json.Unmarshal(responseData, &responseObject)
  44. artist_link, err := http.Get(responseObject.Artists)
  45. if err != nil {
  46. fmt.Print(err.Error())
  47. os.Exit(1)
  48. }
  49. artistData, err := ioutil.ReadAll(artist_link.Body)
  50. if err != nil {
  51. log.Fatal(err)
  52. }
  53. var artistObject Artist
  54. json.Unmarshal(artistData, &artistObject)
  55. t, _ := template.ParseFiles("index.html")
  56. t.Execute(w, artistObject)
  57. }

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

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title></title>
  7. </head>
  8. <style>
  9. iframe {
  10. width: 99vw;
  11. }
  12. .card {
  13. box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
  14. transition: 0.3s;
  15. width: 40%;
  16. }
  17. .card:hover {
  18. box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
  19. }
  20. .container {
  21. padding: 2px 16px;
  22. }
  23. </style>
  24. <body>
  25. <header>
  26. <h1>groupie-tracker</h1>
  27. </header>
  28. <div>
  29. {{range .}}
  30. <div class="card">
  31. <div class="container">
  32. <h4><b>{{ .Name }}</b></h4>
  33. <p>{{ .FirstAlbum }}</p>
  34. </div>
  35. </div>
  36. {{end}}
  37. </div>
  38. </body>
  39. </html>
英文:

I am new in Go language so I have a question. I have API from where I need to parse information to cards. I have a script which GET all information from API and place it into fields in card. I understand how to take one part of information. But I need to create many cards with different information from API and place them on HTML page. How I can do this?

server.go file for HTML hosting.

  1. package main
  2. import (
  3. &quot;encoding/json&quot;
  4. &quot;fmt&quot;
  5. &quot;io/ioutil&quot;
  6. &quot;log&quot;
  7. &quot;net/http&quot;
  8. &quot;os&quot;
  9. &quot;text/template&quot;
  10. )
  11. type Response struct {
  12. Artists string `json:&quot;artists&quot;`
  13. Locations string `json:&quot;locations&quot;`
  14. Dates string `json:&quot;dates&quot;`
  15. Relation string `json:&quot;relation&quot;`
  16. }
  17. type Artist struct {
  18. ID int `json:&quot;id&quot;`
  19. Image string `json:&quot;image&quot;`
  20. Name string `json:&quot;name&quot;`
  21. Members []string `json:&quot;members&quot;`
  22. CreationDate string `json:&quot;creationDate&quot;`
  23. FirstAlbum string `json:&quot;firstAlbum&quot;`
  24. }
  25. func main() {
  26. http.HandleFunc(&quot;/&quot;, formHandler) // to define the path/page, where we are going to use the mentioned function
  27. fmt.Printf(&quot;Starting server at port 8080\n&quot;)
  28. if err := http.ListenAndServe(&quot;:8080&quot;, nil); err != nil { //to initialise our server on :8080
  29. log.Fatal(&quot;HTTP status 500 - Internal server error: %s&quot;, err)
  30. }
  31. }
  32. func formHandler(w http.ResponseWriter, r *http.Request) {
  33. response, err := http.Get(&quot;https://groupietrackers.herokuapp.com/api&quot;)
  34. if err != nil {
  35. fmt.Print(err.Error())
  36. os.Exit(1)
  37. }
  38. responseData, err := ioutil.ReadAll(response.Body)
  39. if err != nil {
  40. log.Fatal(err)
  41. }
  42. var responseObject Response
  43. json.Unmarshal(responseData, &amp;responseObject)
  44. artist_link, err := http.Get(responseObject.Artists)
  45. if err != nil {
  46. fmt.Print(err.Error())
  47. os.Exit(1)
  48. }
  49. artistData, err := ioutil.ReadAll(artist_link.Body)
  50. if err != nil {
  51. log.Fatal(err)
  52. }
  53. var artistObject Artist
  54. json.Unmarshal(artistData, &amp;artistObject)
  55. t, _ := template.ParseFiles(&quot;index.html&quot;)
  56. t.Execute(w, artistObject)
  57. }

index.html file for showing information to pearson.

  1. &lt;!DOCTYPE html&gt;
  2. &lt;html lang=&quot;en&quot;&gt;
  3. &lt;head&gt;
  4. &lt;meta charset=&quot;UTF-8&quot;&gt;
  5. &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
  6. &lt;title&gt;&lt;/title&gt;
  7. &lt;/head&gt;
  8. &lt;style&gt;
  9. iframe {
  10. width: 99vw;
  11. }
  12. .card {
  13. box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
  14. transition: 0.3s;
  15. width: 40%;
  16. }
  17. .card:hover {
  18. box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
  19. }
  20. .container {
  21. padding: 2px 16px;
  22. }
  23. &lt;/style&gt;
  24. &lt;body&gt;
  25. &lt;header&gt;
  26. &lt;h1&gt;groupie-tracker&lt;/h1&gt;
  27. &lt;/header&gt;
  28. &lt;div&gt;
  29. {{range .}}
  30. &lt;div class=&quot;card&quot;&gt;
  31. &lt;div class=&quot;container&quot;&gt;
  32. &lt;h4&gt;&lt;b&gt;{{ .Name }}&lt;/b&gt;&lt;/h4&gt;
  33. &lt;p&gt;{{ .FirstAlbum }}&lt;/p&gt;
  34. &lt;/div&gt;
  35. &lt;/div&gt;
  36. {{end}}
  37. &lt;/div&gt;
  38. &lt;/body&gt;
  39. &lt;/html&gt;

答案1

得分: 0

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

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

此外,你期望一个 Artist 结构的切片,对吗?所以你想要解组成一个切片,而不是一个单独的对象。如果你检查解组时的错误,你会看到这一点。

最后,CreationDate 字段存在问题。解组错误也会显示出来。

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. "os"
  9. "text/template"
  10. )
  11. type Response struct {
  12. Artists string `json:"artists"`
  13. Locations string `json:"locations"`
  14. Dates string `json:"dates"`
  15. Relation string `json:"relation"`
  16. }
  17. type Artist struct {
  18. ID int `json:"id"`
  19. Image string `json:"image"`
  20. Name string `json:"name"`
  21. Members []string `json:"members"`
  22. CreationDate int `json:"creationDate"`
  23. FirstAlbum string `json:"firstAlbum"`
  24. }
  25. var temp *template.Template
  26. func main() {
  27. temp = template.Must(template.ParseFiles("index.html"))
  28. http.HandleFunc("/", formHandler) // to define the path/page, where we are going to use the mentioned function
  29. fmt.Printf("Starting server at port 8080\n")
  30. if err := http.ListenAndServe(":8080", nil); err != nil { //to initialise our server on :8080
  31. log.Fatal("HTTP status 500 - Internal server error: %s", err)
  32. }
  33. }
  34. func formHandler(w http.ResponseWriter, r *http.Request) {
  35. response, err := http.Get("https://groupietrackers.herokuapp.com/api")
  36. if err != nil {
  37. fmt.Print(err.Error())
  38. os.Exit(1)
  39. }
  40. responseData, err := ioutil.ReadAll(response.Body)
  41. if err != nil {
  42. log.Fatal(err)
  43. }
  44. var responseObject Response
  45. json.Unmarshal(responseData, &responseObject)
  46. artist_link, err := http.Get(responseObject.Artists)
  47. if err != nil {
  48. fmt.Print(err.Error())
  49. os.Exit(1)
  50. }
  51. artistData, err := ioutil.ReadAll(artist_link.Body)
  52. if err != nil {
  53. log.Fatal(err)
  54. }
  55. var artists []Artist
  56. err = json.Unmarshal(artistData, &artists)
  57. if err != nil {
  58. log.Fatal(err)
  59. }
  60. temp.Execute(w, artists)
  61. }
英文:

There are a couple ways to handle templates. But you definitely want to parse your files once and store them.

One way is to create a global var and store the template/templates in there.

Also you expect a slice of Artist structs, correct? So you want to unmarshal into a slice, not a single object. If you check the error on unmarshal, you will see that.

Last, there is a problem with the CreationDate field. Unmarshal error shows that too.

  1. package main
  2. import (
  3. &quot;encoding/json&quot;
  4. &quot;fmt&quot;
  5. &quot;io/ioutil&quot;
  6. &quot;log&quot;
  7. &quot;net/http&quot;
  8. &quot;os&quot;
  9. &quot;text/template&quot;
  10. )
  11. type Response struct {
  12. Artists string `json:&quot;artists&quot;`
  13. Locations string `json:&quot;locations&quot;`
  14. Dates string `json:&quot;dates&quot;`
  15. Relation string `json:&quot;relation&quot;`
  16. }
  17. type Artist struct {
  18. ID int `json:&quot;id&quot;`
  19. Image string `json:&quot;image&quot;`
  20. Name string `json:&quot;name&quot;`
  21. Members []string `json:&quot;members&quot;`
  22. CreationDate int `json:&quot;creationDate&quot;`
  23. FirstAlbum string `json:&quot;firstAlbum&quot;`
  24. }
  25. var temp *template.Template
  26. func main() {
  27. temp = template.Must(template.ParseFiles(&quot;index.html&quot;))
  28. http.HandleFunc(&quot;/&quot;, formHandler) // to define the path/page, where we are going to use the mentioned function
  29. fmt.Printf(&quot;Starting server at port 8080\n&quot;)
  30. if err := http.ListenAndServe(&quot;:8080&quot;, nil); err != nil { //to initialise our server on :8080
  31. log.Fatal(&quot;HTTP status 500 - Internal server error: %s&quot;, err)
  32. }
  33. }
  34. func formHandler(w http.ResponseWriter, r *http.Request) {
  35. response, err := http.Get(&quot;https://groupietrackers.herokuapp.com/api&quot;)
  36. if err != nil {
  37. fmt.Print(err.Error())
  38. os.Exit(1)
  39. }
  40. responseData, err := ioutil.ReadAll(response.Body)
  41. if err != nil {
  42. log.Fatal(err)
  43. }
  44. var responseObject Response
  45. json.Unmarshal(responseData, &amp;responseObject)
  46. artist_link, err := http.Get(responseObject.Artists)
  47. if err != nil {
  48. fmt.Print(err.Error())
  49. os.Exit(1)
  50. }
  51. artistData, err := ioutil.ReadAll(artist_link.Body)
  52. if err != nil {
  53. log.Fatal(err)
  54. }
  55. var artists []Artist
  56. err = json.Unmarshal(artistData, &amp;artists)
  57. if err != nil {
  58. log.Fatal(err)
  59. }
  60. temp.Execute(w, artists)
  61. }

huangapple
  • 本文由 发表于 2021年12月19日 03:29:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/70406468.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定