我創建了一個簡單的抓取工具,它從網站獲取前 10 條新聞并返回包含標題和分數的 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) }
1 回答

慕蓋茨4494581
TA貢獻1850條經驗 獲得超11個贊
我發現您的代碼存在三個問題:
a) template.html 文件應該在 link & rel 之間有空格
<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,
- 1 回答
- 0 關注
- 124 瀏覽
添加回答
舉報
0/150
提交
取消