simple-server
simple-server copied to clipboard
consider stronger typing for `Server::listen` arguments
the Server::listen call currently takes an &str for both host and port. This gets fed into a format! call, using the a str impl of ToSocketAddr.
IMHO, there is no opinion to stringly-type these parameters. Taking a std::net::IpAddr and a u16 does exactly the same, with stronger typing. The combination (IpAddr, u16) even has a ToSocketAddrs-impl, so it can be directly passed into the TcpListener.
As discussed on users.rust-lang, this would add some boilerplate on the user-side to create the IpAddr:
IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); // verbose, guaranteed to work...
"127.0.0.1".parse().expect("couldn't parse IP address") // not much better...
the goals of this project are to make an easier user interface. so i dont think we'd like to push this onto our developers. however, if we implement default values for port and host (https://github.com/steveklabnik/simple-server/issues/25) i think this might be something we consider.
thanks for filing!
You're welcome! As I said on users.rust-lang, I believe a project like this can be the "gateway drug" for a whole new generation of people, just like node was. Only this time they'll learn to expect safe, native software, instead of callback-tangles (sorry, a little bit tongue-in-cheek there)
I can understand that &str is easier for the IP-address, but for the port? port: u16 seems easier to me than port: &str? And the format! should be able to take a u16 or a &str with equal ease, no?
Of course, there may be other things I'm missing; I've spent considerably less time on this than you two obviously have :-)
Even in the node example, the port is a number, not a string.
FWIW, yes to u16 for the port. A string for the host seems like the ideal choice because hostnames: "127.0.0.1" -> "localhost" is an example of a very simple transformation that users may instinctively want to use. Also, IPv6 "::1".
Cliff on URLO mentions that [127,0,0,1].into() should also work for the IP, including IPv6.
That's good enough for me!
I'm also pondering if using Into<IpAddr> might be a good type for the parameter.. this may be confusing to newcomers though...
FWIW, Unix has a concept of names for particular ports, listed in /etc/services, like
http 80/udp www www-http # World Wide Web HTTP
For this reason, Unix functions like getnameinfo and getaddrinfo are similarly stringly typed: you can pass either a decimal representation of the port number, or one of the service names.
…But I've rarely seen any modern code use this, so it feels really old-fashioned, and it's probably not worth supporting in simple-server. On the other hand, if you do end up keeping the port argument a string, for whatever reason, then it ought to be supported.