diff --git a/linkchecker.go b/linkchecker.go index 97ef2ba..4695622 100644 --- a/linkchecker.go +++ b/linkchecker.go @@ -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 } diff --git a/main.go b/main.go index 43f84de..02be82c 100644 --- a/main.go +++ b/main.go @@ -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) + } } }