simple makeObjByID refactoring

This commit is contained in:
Kirill Zhuravlev 2023-02-14 20:06:46 +01:00 committed by Avelino
parent d029cd932a
commit b15a1ffc03
No known key found for this signature in database
GPG Key ID: B345B4D52E98180A

24
main.go
View File

@ -2,6 +2,7 @@ package main
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
cp "github.com/otiai10/copy" cp "github.com/otiai10/copy"
"os" "os"
@ -82,10 +83,11 @@ func main() {
if !exists { if !exists {
return return
} }
obj := makeObjByID(selector, query.Find("body")) obj, err := makeObjByID(selector, query.Find("body"))
if obj == nil { if err != nil {
return return
} }
objs[selector] = *obj objs[selector] = *obj
}) })
}) })
@ -160,12 +162,15 @@ func makeSitemap(objs map[string]Object) {
_ = tplSitemap.Execute(f, objs) _ = tplSitemap.Execute(f, objs)
} }
func makeObjByID(selector string, s *goquery.Selection) (obj *Object) { func makeObjByID(selector string, s *goquery.Selection) (*Object, error) {
var obj Object
var err error
s.Find(selector).Each(func(_ int, s *goquery.Selection) { s.Find(selector).Each(func(_ int, s *goquery.Selection) {
desc := s.NextFiltered("p") desc := s.NextFiltered("p")
ul := s.NextFilteredUntil("ul", "h2") ul := s.NextFilteredUntil("ul", "h2")
links := []Link{} var links []Link
ul.Find("li").Each(func(_ int, s *goquery.Selection) { ul.Find("li").Each(func(_ int, s *goquery.Selection) {
url, _ := s.Find("a").Attr("href") url, _ := s.Find("a").Attr("href")
link := Link{ link := Link{
@ -175,17 +180,24 @@ func makeObjByID(selector string, s *goquery.Selection) (obj *Object) {
} }
links = append(links, link) links = append(links, link)
}) })
// FIXME: In this case we would have an empty category in main index.html with link to 404 page.
if len(links) == 0 { if len(links) == 0 {
err = errors.New("object has no links")
return return
} }
obj = &Object{ obj = Object{
Slug: slug.Generate(s.Text()), Slug: slug.Generate(s.Text()),
Title: s.Text(), Title: s.Text(),
Description: desc.Text(), Description: desc.Text(),
Items: links, Items: links,
} }
}) })
return
if err != nil {
return nil, fmt.Errorf("unable to build an object: %w", err)
}
return &obj, nil
} }
func changeLinksInIndex(html string, query *goquery.Document, objs map[string]Object) { func changeLinksInIndex(html string, query *goquery.Document, objs map[string]Object) {