feat: Add status code reporting for broken links
This commit is contained in:
parent
5d646091a2
commit
43d7a785ab
|
@ -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
|
||||
}
|
||||
|
|
6
main.go
6
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue