Skip to content

Commit

Permalink
feature: add IsURLReachable
Browse files Browse the repository at this point in the history
  • Loading branch information
atjhoendz committed Jan 18, 2024
1 parent 12cfd1c commit 1d1a22f
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 4 deletions.
5 changes: 2 additions & 3 deletions bson_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
14 changes: 14 additions & 0 deletions url.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package utils

import (
"net/http"
"net/url"
"path"
)
Expand All @@ -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
}
24 changes: 23 additions & 1 deletion url_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ func Test_JoinURL(t *testing.T) {

assert.Equal(t, "https://kumparan.com/trending/feed", resURL)
assert.NoError(t, err)

})
})

Expand All @@ -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)
})
}

0 comments on commit 1d1a22f

Please sign in to comment.