From 1d1a22fa20279681e75927389e42496fce58301b Mon Sep 17 00:00:00 2001 From: Moh Achun Armando Date: Thu, 18 Jan 2024 13:41:40 +0700 Subject: [PATCH] feature: add IsURLReachable --- bson_test.go | 5 ++--- url.go | 14 ++++++++++++++ url_test.go | 24 +++++++++++++++++++++++- 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/bson_test.go b/bson_test.go index f20d19b..1b2248d 100644 --- a/bson_test.go +++ b/bson_test.go @@ -16,15 +16,14 @@ func BenchmarkTimeFromObjectIDHex(_ *testing.B) { for _, v := range cases { _, _ = TimeFromObjectIDHex(v) - } } func TestTimeFromObjectIDHex(t *testing.T) { t.Run("valid hex objectID", func(t *testing.T) { cases := map[string]time.Time{ - "63acfc824ffda9000ee65045": time.Date(2022, time.December, 29, 2, 33, 38, 0, time.Local), - "5c4b288bac1b2972d0291377": time.Date(2019, time.January, 25, 15, 17, 31, 0, time.Local), + "63acfc824ffda9000ee65045": time.Date(2022, time.December, 29, 2, 33, 38, 0, time.UTC), + "5c4b288bac1b2972d0291377": time.Date(2019, time.January, 25, 15, 17, 31, 0, time.UTC), } for k, v := range cases { diff --git a/url.go b/url.go index 6099658..b7d1db8 100644 --- a/url.go +++ b/url.go @@ -1,6 +1,7 @@ package utils import ( + "net/http" "net/url" "path" ) @@ -16,3 +17,16 @@ func JoinURL(baseURL string, pathElements ...string) (string, error) { u.Path = path.Join(append(append(elements, u.Path), pathElements...)...) return u.String(), nil } + +// IsURLReachable check is the url reachable +func IsURLReachable(url string) bool { + res, err := http.Head(url) //nolint:gosec + if err != nil { + return false + } + defer func() { + _ = res.Body.Close() + }() + + return res.StatusCode == http.StatusOK +} diff --git a/url_test.go b/url_test.go index 0e690a6..1cc9c13 100644 --- a/url_test.go +++ b/url_test.go @@ -48,7 +48,6 @@ func Test_JoinURL(t *testing.T) { assert.Equal(t, "https://kumparan.com/trending/feed", resURL) assert.NoError(t, err) - }) }) @@ -69,3 +68,26 @@ func Test_JoinURL(t *testing.T) { assert.NoError(t, err) }) } + +func TestIsURLReachable(t *testing.T) { + t.Run("should return true on valid + reachable url", func(t *testing.T) { + url := "https://google.com" + + res := IsURLReachable(url) + assert.True(t, res) + }) + + t.Run("should return false on valid + not reachable url", func(t *testing.T) { + url := "https://haha.hihi" + + res := IsURLReachable(url) + assert.False(t, res) + }) + + t.Run("should return false on invalid + not reachable url", func(t *testing.T) { + url := "haha" + + res := IsURLReachable(url) + assert.False(t, res) + }) +}