feat: Add status code reporting for broken links

This commit is contained in:
Erik Winter (aider) 2024-11-25 09:51:51 +01:00
parent 5d646091a2
commit 43d7a785ab
2 changed files with 24 additions and 8 deletions

View File

@ -19,19 +19,31 @@ func NewLinkChecker() *LinkChecker {
}
}
func (lc *LinkChecker) CheckLinks(baseURL string) ([]string, error) {
type BrokenLink struct {
URL string
StatusCode int
Error string
}
func (lc *LinkChecker) CheckLinks(baseURL string) ([]BrokenLink, error) {
// Get all links from the page
links, err := lc.getLinks(baseURL)
if err != nil {
return nil, fmt.Errorf("error getting links: %w", err)
}
var brokenLinks []string
var brokenLinks []BrokenLink
// Check each link
for _, link := range links {
if !lc.isLinkValid(link) {
brokenLinks = append(brokenLinks, link)
if status, err := lc.isLinkValid(link); status >= 400 || err != nil {
broken := BrokenLink{URL: link}
if err != nil {
broken.Error = err.Error()
} else {
broken.StatusCode = status
}
brokenLinks = append(brokenLinks, broken)
}
}
@ -87,12 +99,12 @@ func (lc *LinkChecker) getLinks(pageURL string) ([]string, error) {
return links, nil
}
func (lc *LinkChecker) isLinkValid(link string) bool {
func (lc *LinkChecker) isLinkValid(link string) (int, error) {
resp, err := lc.client.Get(link)
if err != nil {
return false
return 0, err
}
defer resp.Body.Close()
return resp.StatusCode >= 200 && resp.StatusCode < 400
return resp.StatusCode, nil
}

View File

@ -27,6 +27,10 @@ func main() {
fmt.Println("Found broken links:")
for _, link := range brokenLinks {
fmt.Printf("- %s\n", link)
if link.Error != "" {
fmt.Printf("- %s (Error: %s)\n", link.URL, link.Error)
} else {
fmt.Printf("- %s (Status: %d)\n", link.URL, link.StatusCode)
}
}
}