A port number identifies a virtual endpoint on a host. Servers listen through ports for messages arriving from internal processes or the wider network, allowing an application to receive requests. section 10.2.2 section 8.0
When configuring a Go service, choose and use the port deliberately:
- Use a standard port when appropriate: HTTP commonly uses 80 and HTTPS commonly uses 443. section 10.2.2
- Use a development port such as 8000 or 8080 instead of 80 when another process may already occupy it. section 8.1.2
- For internal usage, choose a port between 1024 and 49151; only one application can listen to a given port on the same machine. section 10.2.2
- Use port 0 when the listener should allocate a free port randomly. section 10.2.2
Starting an HTTP service on port 8080
A minimal Go server binds to localhost on port 8080 with http.ListenAndServe(":8080", nil). The call keeps running while the service listens; curl http://localhost:8080 can send a test request. section 8.1.2
Listing 10.9 server.go: Listening to a given port
import (
...
"google.golang.org/grpc"
"learngo-pockets/habits/api"
)
// ListenAndServe starts listening to the port and serving requests.
func (s *Server) ListenAndServe(port int) error {
const addr = "127.0.0.1"
listener, err := net.Listen("tcp",
net.JoinHostPort(addr, strconv.Itoa(port))) #1
if err != nil {
return fmt.Errorf("unable to listen to tcp port %d: %w", port, err)
}
grpcServer := grpc.NewServer() #2
api.RegisterHabitsServer(grpcServer, s) #3
s.lgr.Logf("starting server on port %d\n", port)
err = grpcServer.Serve(listener) #4
if err != nil {
return fmt.Errorf("error while listening: %w", err)
}
// Stop or GracefulStop was called, no reason to be alarmed.
return nil
}
This implementation shows a gRPC server joining an address and port with net.Listen, registering its API, and serving requests through the listener. section 10.2.2






