Go HTML模板

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

Go HTML template

问题

我已经创建了一个简单的爬虫程序,它从一个网站获取前10条新闻,并返回一个包含标题和分数的JSON。我想将标题和分数作为HTML模板传递,以便生成一个网页。我对Go语言的模板语法不熟悉,也不知道如何为每个链接传递数值。以下是我应该使用的HTML代码和目前的实现:

<!DOCTYPE html>
<html>
   <head><link rel="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{
    			//在这里应该放什么?
    		},
    	}
    	tmpl.Execute(w, data)
    }
    
    func main() {
    	mux := http.NewServeMux()
    	mux.HandleFunc("/top", HTMLHandler)
    	http.ListenAndServe(":8080", mux)
    }
英文:

I have created a simple scraper that takes the top 10 news from a website and returns a JSON with the title and the score. I want to pass the title and the score as HTML template so I can generate a webpage. I'm not familiar with the templating Go language and I don't know how to pass the values for each of the links. Here is the HTML code that I should use and my implementation for now:

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;&lt;linkrel=&quot;stylesheet&quot; href=&quot;https://unpkg.com/mvp.css&quot;
/&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;{{.PageTitle}}&lt;/h1&gt;
&lt;ul&gt;
{{range .Links}}
&lt;li&gt;{{.Title}}: {{.Score}}&lt;/li&gt;
{{end}}
&lt;/ul&gt;
&lt;/body&gt;
&lt;/html&gt;

My code:

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

答案1

得分: 0

我看到你的代码有三个问题:

a) template.html 文件中 link 和 rel 之间应该有空格

&lt;linkrel=&quot;stylesheet&quot; href=&quot;https://unpkg.com/mvp.css&quot;/&gt;

改为

&lt;link rel=&quot;stylesheet&quot; href=&quot;https://unpkg.com/mvp.css&quot;/&gt;

b) template.html 文件中应该使用 .Data 而不是 .Links

c) go 代码应该替换为以下内容

Data :[]TopStories{ 
//在这里放什么?
},

改为

Data : scraper.Data,
英文:

I see three issues with your code:

a) The template.html file should have space between link & rel

&lt;linkrel=&quot;stylesheet&quot; href=&quot;https://unpkg.com/mvp.css&quot;/&gt;

to

&lt;link rel=&quot;stylesheet&quot; href=&quot;https://unpkg.com/mvp.css&quot;/&gt;

b) The template.html file should contain .Data instead of .Links.

c) The go code should be replaced from the below

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

to

Data : scraper.Data,

huangapple
  • 本文由 发表于 2022年4月18日 00:44:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/71903697.html
匿名

发表评论

匿名网友

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

确定