Check a list of URL's

Hi,

I am new to Go and programming in general but I’m trying to write a small program to check URL’s to see if they are valid. My code generates an error and stops once it gets to a URL where there is no response. Could someone please advise how I can print the error and continue?

The error that I get is

Exception has occurred: panic
“runtime error: invalid memory address or nil pointer dereference”
Stack:
4 0x00000000011298bd in main.checkUrl
at c:/Users/graha/Golang/url_tester/url.go:1228
5 0x000000000112996e in main.main
at c:/Users/graha/Golang/url_tester/url.go:1244


import (
	"fmt"
	"net/http"
)

var url = []string{
	"https://www.example.com",
	"https://www.thisurldoesnotexist23432.com",
}

func checkUrl(url []string) {
	for _, s := range url {
		resp, err := http.Get(s)
		fmt.Println(resp)
		if err != nil {
			fmt.Println(err)
		}
		resp.Body.Close()
	}

}

func main() {
	checkUrl(url)
}

Check for a non-nil err before accessing the response.

package main

import (
	"fmt"
	"net/http"
)

var url = []string{
	"https://www.example.com",
	"https://www.thisurldoesnotexist23432.com",
}

func checkUrl(url []string) {
	for _, s := range url {
		resp, err := http.Get(s)
		if err != nil {
			fmt.Println(err)
		} else {
			fmt.Println(resp)
			resp.Body.Close()
		}
	}
}

func main() {
	checkUrl(url)
}
1 Like

Thanks for your help.