This commit is contained in:
Laurent Ulrich
2025-08-20 08:56:37 +02:00
parent 8c76f5e6f0
commit 10ebdaad4a
6 changed files with 134 additions and 14 deletions

70
blog.go
View File

@@ -1,8 +1,13 @@
package main
import (
"fmt"
"html/template"
"log"
"strings"
"sync"
"github.com/PuerkitoBio/goquery"
)
type Post struct {
@@ -13,6 +18,7 @@ type Post struct {
Author string
Date string
HTML template.HTML
ShortText string
Text string
}
@@ -37,3 +43,67 @@ func (b *Blog) GetPost(Id string) (Post, bool) {
}
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
}