I'm coding in golang some tools to make my life easier and I'm not understanding at all how the types in the net package works. This is part of my code:
import (
"bufio"
"fmt"
"log"
"net"
"os"
)
type configFile struct {
gateway, net net.IP
mask, port int
telnetUser, telnetPasswd string
}
var dataConfig configFile
func createConfigFile() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Let's fill te config file for the application.")
fmt.Println("Which is your gateway IP?")
readGateway, err := reader.ReadString('
')
if err != nil {
log.Fatal(err)
}
dataConfig.gateway = net.ParseIP(readGateway)
if dataConfig.gateway == nil {
log.Fatal("Problem here")
} else {
fmt.Println("Your gateway is: ", dataConfig.gateway.String())
}
}
My problem is the next:
I want to read an IP address from the command line and storage it in the configFile object, which I will user later to create a .json
file with all the configuration of my program.
When I read from the command line the IP address the readGateway
variable storages it ok, that's expected, but when I try to make dataConfig.gateway = net.ParseIP(readGateway)
and I try to cast the string object to a net.IP
object I'm always getting a nill
in the dataConfig.gateway
field, so I'm not able to work with that parameter neither convert it to a string.
Could somebody help me? Thanks in advance.
bufio.Reader.ReadString
's docs explain (emphasis mine)
ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter
So readGateway
ends up looking like "192.168.1.1 "
. Your newline delimiter would not exist in a properly formatted IP address, which means when you parse it with net.ParseIP
it's kicking it out as nil
.
You can use strings.TrimRight
to trim out the newline:
readGateway, err := reader.ReadString('
')
if err != nil {
log.Fatal(err)
}
readGateway = strings.TrimRight(readGateway, "
")
The documentation of net.ParseIP(s string)
states that if the string s provided is not a valid textual representation of an IP address the function will return a nil
value, so that must be the case.
Please log the string s before calling net.ParseIP
so you can check if you are passing and reading it properly in the program.