I had some time to research the net-package in Go today. Here is what I found. It’s really not meant to be a tutorial or anything like that. It’s just my notes.
net-package is used to abstract some of the lower level socket things. This allows us to create more platform independent programs. A small illustration of a comparision of C and Go can be like this:
| C | Go |
|---|---|
| socket() | … |
| bind() | … |
| listen() | Listen(network, addr) |
| accept() | Listen().Accept() |
Listen(network, addr) returns a Listener interface used for stream-oriented protocol network: “tcp”, “tcp4”, “tcp6”, or “unix”. Listen() will take care of calling the socket() and bind() syscalls and set the correct parameters depending on what kind of network you set-up.
For example creating a tcp server we can call Listen("tcp", "127.0.0.1") which in net.go will run through a switch case and call the appropriate network Listen function(ListenTCP(), ListenUnix()). ListenTCP, for instance, will then create a internetSocket with all correct settings in order: syscall.SOCKSTREAM, syscall.AF_INET(IPv4), syscall.Sockaddr, syscall.Socket, syscall.Bind and a non-blocking I/O to syscall.Accept using the thread safe syscall.ForkLock (see l.fd.accept() in fd.go). Thats why leave out the syscall socket() and bind() in Go when using the net-package.
Listen(net, laddr string) (l Listener, err os.Error)
type Listener interface { Accept() (c Conn, err os.Error); Close() os.Error; Addr() Addr; // Listener's network address }
func Accept(fd int) (nfd int, sa Sockaddr, errno int)
http- and websocket[1]-packages are making things even simpler. An example found in pkg.http.server.go for creating a trivial server:
package main
import ( "http"; "io"; ) // hello world, the web server func HelloServer(c http.Conn, req http.Request) { io.WriteString(c, "hello, world!n"); }
func main() { http.Handle("/hello", http.HandlerFunc(HelloServer)); err := http.ListenAndServe(":12345", nil); if err != nil { panic("ListenAndServe: ", err.String()) } }
[1] websocket package is per date only available in the development trunk.