转到 HTML 模板

Go HTML template

我创建了一个简单的抓取工具,它从网站获取前 10 条新闻,returns JSON 带有标题和分数。我想将标题和分数作为 HTML 模板传递,以便生成网页。我不熟悉模板化 Go 语言,也不知道如何为每个链接传递值。这是我现在应该使用的 HTML 代码和我的实现:

<!DOCTYPE html>
<html>
   <head><linkrel="stylesheet" href="https://unpkg.com/mvp.css"
      />
   </head>
   <body>
      <h1>{{.PageTitle}}</h1>
      <ul>
         {{range .Links}}
         <li>{{.Title}}: {{.Score}}</li>
         {{end}}
      </ul>
   </body>
</html>

我的代码:

package main
    
    import (
        "encoding/json"
        "html/template"
        "log"
        "net/http"
        "strconv"
    )
    
    type TopStories struct {
        Title string `json:"title"`
        Score int    `json:"score"`
    }
    
    type TopStoriesPayload struct {
        TopStories []TopStories
    }
    
    type NewsScraper struct {
        url  string
        Data []TopStories
    }
    
    type templateData struct {
        PageTitle string
        Data      []TopStories
    
    }
    
    func NewNewsScraper(url string) *NewsScraper {
        return &NewsScraper{url: url}
    }
    
    func Top10Stories() []string {
        req, err := http.NewRequest("GET", "https://hacker-news.firebaseio.com/v0/topstories.json", nil)
        if err != nil {
            log.Fatal(err)
        }
        resp, err := http.DefaultClient.Do(req)
        if err != nil {
            log.Fatal(err)
        }
        var IDs []int
        json.NewDecoder(resp.Body).Decode(&IDs)
        IDs = IDs[:10]
        var IDsString []string
        for _, id := range IDs {
            IDsString = append(IDsString, strconv.Itoa(id))
        }
        return IDsString
    }
    
    func (n *NewsScraper) GetTopStories() {
        req, err := http.NewRequest("GET", n.url, nil)
        if err != nil {
            log.Fatal(err)
        }
    
        for _, id := range Top10Stories() {
            req.URL.Path = "/v0/item/" + id + ".json"
            resp, err := http.DefaultClient.Do(req)
            if err != nil {
                log.Fatal(err)
            }
            var topStory TopStories
            json.NewDecoder(resp.Body).Decode(&topStory)
            n.Data = append(n.Data, topStory)
        }
    }
    
    //create html template handler for top stories
    func HTMLHandler(w http.ResponseWriter, r *http.Request) {
        scraper := NewNewsScraper("https://hacker-news.firebaseio.com")
        scraper.GetTopStories()
        tmpl:= template.Must(template.ParseFiles("template.html"))
        data := templateData{
            PageTitle: "Top Stories",
            Data :[]TopStories{
                //what should I put here?
            },
        }
        tmpl.Execute(w, data)
    }
    
    func main() {
        mux := http.NewServeMux()
        mux.HandleFunc("/top", HTMLHandler)
        http.ListenAndServe(":8080", mux)
    }

我发现您的代码存在三个问题:

a) template.html 文件应该在 link 和 rel

之间有 space
<linkrel="stylesheet" href="https://unpkg.com/mvp.css"/>

<link rel="stylesheet" href="https://unpkg.com/mvp.css"/>

b) template.html 文件应包含 .Data 而不是 .Links.

c) go代码应该从下面替换

Data :[]TopStories{ 
  //what should I put here?
},

Data : scraper.Data,