Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: getHostByName #412

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions network.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
package sprig

import (
"math/rand"
"net"
)

func getHostByName(name string) string {
addrs, _ := net.LookupHost(name)
//TODO: add error handing when release v3 comes out
return addrs[rand.Intn(len(addrs))]
const NUM_TRIES = 3

func getHostByName(name string) ([]string, error) {
err := error(nil)
addrs := []string(nil)
for tries := 0; tries < NUM_TRIES; tries++ {
if addrs, err = net.LookupHost(name); err == nil {
return addrs, nil
}
}
return addrs, err
}
33 changes: 28 additions & 5 deletions network_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,40 @@ package sprig

import (
"net"
"strings"
"testing"

"github.com/stretchr/testify/assert"
)

func TestGetHostByName(t *testing.T) {
tpl := `{{"www.google.com" | getHostByName}}`
// GIVEN a valid hostname
tpl := `{{"google.com" | getHostByName}}`

resolvedIP, _ := runRaw(tpl, nil)
// WHEN getHostByName is executed
resolvedIP, err := runRaw(tpl, nil)

ip := net.ParseIP(resolvedIP)
assert.NotNil(t, ip)
assert.NotEmpty(t, ip)
// THEN the resolved IP should not be empty and no error should be returned
assert.NotEmpty(t, resolvedIP)
assert.NoError(t, err)

// result has type string, but it should be a slice of strings
// convert it to a slice of strings
resolvedIPs := strings.Split(resolvedIP[1:len(resolvedIP)-1], " ")

// Check if the resolved IP is a valid IP address
parsedIP := net.ParseIP(resolvedIPs[0])
assert.NotNil(t, parsedIP)
}

func TestGetHostByNameNXDomain(t *testing.T) {
// GIVEN an invalid hostname
tpl := `{{"invalid.invalid" | getHostByName}}`

// WHEN getHostByName is executed
resolvedIP, err := runRaw(tpl, nil)

// THEN the resolved IP should be empty and an error should be returned
assert.Empty(t, resolvedIP)
assert.Error(t, err)
}