Reputation:
Im trying to create little program where if user inputs ip or port from command line it connect to a server.
my code
ip := flag.String("i","","") // i choosen user provide ip but port will be default :8080
port := flag.String("p", "","") // p choosen has connect to port :???? but ip will be local host
ipPort := flaf.String("b","","") // b choosen user provides both ip and port
default_Ip := flag.String("d","","")// d choosen it connect to localhost ip and port 127.0.0.1:8080
flag.Parse()
log.Fatal(http.ListenAndServe(ip, nil))
log.Fatal(http.ListenAndServe(port, nil))
log.Fatal(http.ListenAndServe(ipPort, nil))
log.Fatal(http.ListenAndServe(default, nil))
what im doing wrong? Point me out to right direction?
Upvotes: 0
Views: 406
Reputation: 1
Take advantage of the flag defaults.
addr := flag.String("a", "", "")
host := flag.String("i","127.0.0.1","")
port := flag.String("p", "8080","")
flag.Parse()
hostport := *addr
if hostport = "" {
hostPort = net.JoinHostPort(*host, *port)
}
log.Fatal(http.ListenAndServe(hostport, nil))
Upvotes: 0
Reputation: 1
There are several problems:
log.Fatal(http.ListenAndServe(*ip, nil))
Here's a better direction that provides the defaults: Use a single string flag. Examine the flag value to determine if host, port or both are specified. Fill in defaults as needed.
func fixAddr(s string) string {
host, port, err := net.SplitHostPort(s)
if err != nil {
host = s // assume s is host only on error
port = ""
}
// Fill in defaults.
if host == "" {
host = "127.0.0.1"
}
if port == "" {
port = "8080"
}
return host + ":" + port
}
addr := flag.String("a","127.0.0.1:8080","")
flag.Parse()
log.Fatal(http.ListenAndServe(fixAddr(*addr), nil))
An even better direction is to require the user to enter a valid address on the command line and pass that directly to ListenAndServe.
addr := flag.String("a","127.0.0.1:8080","")
flag.Parse()
log.Fatal(http.ListenAndServe(*addr, nil))
Upvotes: 0