Repository navigation
Serve a sitemap of each site's pages and images, and a robots.txt that points to it #24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| package site | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/xml" | ||
| "fmt" | ||
| "log/slog" | ||
| "net/http" | ||
| "net/url" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/nyaruka/helpsites/v26/core/models" | ||
| "github.com/nyaruka/helpsites/v26/runtime" | ||
| "github.com/nyaruka/helpsites/v26/web" | ||
| "golang.org/x/net/html" | ||
| ) | ||
|
|
||
| // how long a crawler can keep a root file - pages are rendered fresh on every request, so not long | ||
| const rootFileCacheControl = "public, max-age=300" | ||
|
|
||
| // handleRobots serves the site's robots.txt, which lets crawlers have everything and tells them where the sitemap is. | ||
| // Only the site on its own domain has one - a preview isn't for crawling. | ||
| func handleRobots(ctx context.Context, rt *runtime.Runtime, r *http.Request, w http.ResponseWriter) error { | ||
| sc := web.GetSiteContext(ctx) | ||
| if sc.IsPreview { | ||
| return handleNotFound(ctx, rt, r, w) | ||
| } | ||
|
|
||
| w.Header().Set("Content-Type", "text/plain; charset=utf-8") | ||
| w.Header().Set("Cache-Control", rootFileCacheControl) | ||
| w.WriteHeader(http.StatusOK) | ||
| fmt.Fprintf(w, "User-agent: *\nAllow: /\n\nSitemap: %s\n", siteURL(r, "/sitemap.xml")) | ||
| return nil | ||
| } | ||
|
|
||
| type sitemapURLSet struct { | ||
| XMLName xml.Name `xml:"urlset"` | ||
| XMLNS string `xml:"xmlns,attr"` | ||
| XMLNSImage string `xml:"xmlns:image,attr"` | ||
| URLs []sitemapURL `xml:"url"` | ||
| } | ||
|
|
||
| type sitemapURL struct { | ||
| Loc string `xml:"loc"` | ||
| LastMod string `xml:"lastmod,omitempty"` | ||
| Images []sitemapImage `xml:"image:image"` | ||
| } | ||
|
|
||
| type sitemapImage struct { | ||
| Loc string `xml:"image:loc"` | ||
| } | ||
|
|
||
| // handleSitemap serves the site's sitemap: its home page, each section and each article, with the images each | ||
| // article shows - so that search engines can find all of them. Only the site on its own domain has one. | ||
| func handleSitemap(ctx context.Context, rt *runtime.Runtime, r *http.Request, w http.ResponseWriter) error { | ||
| sc := web.GetSiteContext(ctx) | ||
| if sc.IsPreview { | ||
| return handleNotFound(ctx, rt, r, w) | ||
| } | ||
|
|
||
| sections, err := models.LoadSections(ctx, rt.DB, sc.Site.Source.ID) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| articles, err := models.LoadReadable(ctx, rt.DB, sc.Site.Source.ID) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| // a section's page lists its articles, so it changes whenever one of them does | ||
| sectionModified := make(map[models.ArticleID]time.Time, len(sections)) | ||
| for _, s := range sections { | ||
| sectionModified[s.ID] = s.ModifiedOn | ||
| } | ||
| for _, a := range articles { | ||
| if a.ModifiedOn.After(sectionModified[a.Parent.ID]) { | ||
| sectionModified[a.Parent.ID] = a.ModifiedOn | ||
| } | ||
| } | ||
|
|
||
| set := &sitemapURLSet{ | ||
| XMLNS: "http://www.sitemaps.org/schemas/sitemap/0.9", | ||
| XMLNSImage: "http://www.google.com/schemas/sitemap-image/1.1", | ||
| URLs: []sitemapURL{{Loc: siteURL(r, "/")}}, | ||
| } | ||
| for _, s := range sections { | ||
| set.URLs = append(set.URLs, sitemapURL{ | ||
| Loc: siteURL(r, "/"+s.Slug+"/"), | ||
| LastMod: sectionModified[s.ID].UTC().Format(time.RFC3339), | ||
| }) | ||
| } | ||
| for _, a := range articles { | ||
| loc := siteURL(r, "/"+a.Parent.Slug+"/"+a.Slug+"/") | ||
| u := sitemapURL{Loc: loc, LastMod: a.ModifiedOn.UTC().Format(time.RFC3339)} | ||
| for _, src := range ImageURLs(ResolveImages(a.BodyHTML, rt.Config.StorageURL), loc) { | ||
| u.Images = append(u.Images, sitemapImage{Loc: src}) | ||
| } | ||
| set.URLs = append(set.URLs, u) | ||
| } | ||
|
|
||
| out, err := xml.MarshalIndent(set, "", " ") | ||
| if err != nil { | ||
| return fmt.Errorf("error marshaling sitemap: %w", err) | ||
| } | ||
|
|
||
| w.Header().Set("Content-Type", "application/xml; charset=utf-8") | ||
| w.Header().Set("Cache-Control", rootFileCacheControl) | ||
| w.WriteHeader(http.StatusOK) | ||
| if _, err := w.Write(append([]byte(xml.Header), out...)); err != nil { | ||
| slog.Debug("error writing response", "error", err) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // siteURL returns the absolute URL of the given path on the site, on the host the request reached it on - lowercased | ||
| // and without its scheme's default port, so that the same host asked for differently gives the same addresses | ||
| func siteURL(r *http.Request, path string) string { | ||
| scheme, defaultPort := "http", ":80" | ||
| if r.TLS != nil { | ||
| scheme, defaultPort = "https", ":443" | ||
| } | ||
| host := strings.TrimSuffix(strings.ToLower(r.Host), defaultPort) | ||
| return (&url.URL{Scheme: scheme, Host: host, Path: path}).String() | ||
| } | ||
|
|
||
| // ImageURLs returns the addresses of the images the given rendered body shows, resolved against the address of its | ||
| // page, each once and in the order they appear. A fragment is only for the page, so isn't part of the image's address. | ||
| func ImageURLs(body, pageURL string) []string { | ||
| base, err := url.Parse(pageURL) | ||
| if err != nil { | ||
| return nil | ||
| } | ||
| doc, err := html.Parse(strings.NewReader(body)) | ||
| if err != nil { | ||
| return nil | ||
| } | ||
|
|
||
| var urls []string | ||
| seen := map[string]bool{} | ||
| for n := range doc.Descendants() { | ||
| if n.Type != html.ElementNode || n.Data != "img" { | ||
| continue | ||
| } | ||
| for _, attr := range n.Attr { | ||
| value := strings.TrimSpace(attr.Val) | ||
| if attr.Namespace != "" || attr.Key != "src" || value == "" { | ||
| continue | ||
| } | ||
| src, err := base.Parse(value) | ||
| if err != nil || (src.Scheme != "http" && src.Scheme != "https") { | ||
| continue | ||
| } | ||
| src.Fragment, src.RawFragment = "", "" | ||
| if address := src.String(); !seen[address] { | ||
| seen[address] = true | ||
| urls = append(urls, address) | ||
| } | ||
| } | ||
| } | ||
| return urls | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Performance: this is an unauthenticated endpoint. Every hit loads the body of every readable article and HTML-parses each one.
Cache-Control: max-age=300only helps clients that respect it; anything else can request it repeatedly and cost DB load and CPU in proportion to the site's size. Two options:srcs can't come from SQL, butbody_htmlcould be fetched without the other columns.Also, there's no guard for the sitemaps.org limits (50,000 URLs / 50MB uncompressed). That's probably fine for help sites, but it's worth a comment.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Left as is. That's two queries and an HTML parse of each body, about what a busy page already costs (an article page loads every link target on the site). An in-process cache would also go stale across instances until it expired. Help sites are orders of magnitude below the 50,000 URL / 50MB limits.
🤖 Addressed by Claude Code