package main import ( "fmt" "html/template" "log" "strings" "sync" "github.com/PuerkitoBio/goquery" ) type Post struct { BlogTitle string Lang string Id string Title string Author string Date string HTML template.HTML ShortText string 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() { fmt.Println("----", p.Title) if len(p.HTML) > 0 { fmt.Println("Short text is html", p.HTML) heading, err := p.GetFirstHeading(string(p.HTML)) if err != nil { log.Println(err) } paragraph, err := p.GetFirstParagraph(string(p.HTML)) if err != nil { log.Println(err) } if len(heading) > 0 { log.Println("heading is:", heading) p.ShortText += heading } if len(paragraph) > 0 { log.Println("paragraph is:", paragraph) p.ShortText += paragraph } } else { fmt.Println("Short text is text", p.Text) p.ShortText = 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) GetFirstParagraph(html string) (string, error) { doc, err := goquery.NewDocumentFromReader(strings.NewReader(html)) if err != nil { return "", err } firstParagraph := doc.Find("p").First() if firstParagraph.Length() == 0 { return "", fmt.Errorf("no paragraph found") } htmlContent, err := goquery.OuterHtml(firstParagraph) if err != nil { return "", err } return htmlContent, nil }