package main import ( "fmt" "html/template" "log" "strings" "sync" "time" "github.com/PuerkitoBio/goquery" ) type Post struct { BlogTitle string Lang string Id string Title string Author string Date string DateTime time.Time HTML template.HTML ShortText template.HTML Text string } type Blog struct { Title string Lang string Posts []Post mutex sync.Mutex } func (b *Blog) GetPost(Id string) (Post, bool) { var ret Post b.mutex.Lock() defer b.mutex.Unlock() for _, p := range b.Posts { if p.Id == Id { ret = p ret.BlogTitle = b.Title ret.Lang = b.Lang return ret, true } } return ret, false } func (p *Post) GenerateExcerpt() { p.ShortText = "" if len(p.HTML) > 0 { heading, err := p.GetFirstHeading(string(p.HTML)) if err != nil { log.Println(err) } paragraph, err := p.GetFirstParagraphs(string(p.HTML)) if err != nil { log.Println(err) } if len(heading) > 0 { p.ShortText += template.HTML(heading) } if len(paragraph) > 0 { p.ShortText += template.HTML(paragraph) } } else { p.ShortText = template.HTML(p.Text) } } func (p *Post) GetFirstHeading(html string) (string, error) { doc, err := goquery.NewDocumentFromReader(strings.NewReader(html)) if err != nil { return "", err } // Chercher le premier titre (h1, h2, h3, h4, h5, h6) firstHeading := doc.Find("h1, h2, h3, h4, h5, h6").First() if firstHeading.Length() == 0 { return "", fmt.Errorf("no heading found") } htmlContent, err := goquery.OuterHtml(firstHeading) if err != nil { return "", err } return htmlContent, nil } func (p *Post) GetFirstParagraphs(html string) (string, error) { doc, err := goquery.NewDocumentFromReader(strings.NewReader(html)) if err != nil { return "", err } var htmlContent string var numberOfTextChars int // Eventuellement trouver un moyen de ne plus examiner le reste du document // si 200 caractères atteints doc.Find("p,div,h1,h2,h3,h4,h5").Each(func(i int, s *goquery.Selection) { if numberOfTextChars < 200 { numberOfTextChars += len(s.Text()) content, err := goquery.OuterHtml(s) if err != nil { log.Println(err) } htmlContent += content } }) return htmlContent, nil }