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?
CodePudding user response:
There are several problems:
- flag.String returns a pointer to a string. The application must dereference the pointer when calling http.ListenAndServe:
log.Fatal(http.ListenAndServe(*ip, nil))
- The http.ListenAndServe function blocks until an error. The second server will not start until the first server fails and so on. Run the servers in goroutines if the intent is to run multiple servers.
- The application does not have any code to implement the defaults described in the comments.
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))
CodePudding user response:
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))