ListenAndServe starts a Go network service on a specified address or port and blocks while the service runs. It returns an error when serving stops or fails. section 8.1.2 section 10.2.2
Use the call as the boundary between application setup and long-running service execution:
- Pass an address such as localhost:8080 to the HTTP API, or a port to an application-specific server method. section 8.1.2 section 10.2.2
- Provide a request handler to net/http.ListenAndServe; the initial example keeps the handler nil while request logic is developed separately. section 8.1.2
- Handle the returned error explicitly instead of exposing a panic stack trace to users. section 8.1.2
- Keep service construction outside main when using a server method, allowing dependencies such as a logger to be injected and logic to remain testable. section 10.2.3
Starting an HTTP server
err := http.ListenAndServe(":8080", nil) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } Running the program appears to hang because the server remains active. Test it with curl http://localhost:8080. section 8.1.2
Wrapping a gRPC server
A custom Server.ListenAndServe method can create a TCP listener, register the service implementation, log startup, and call grpcServer.Serve(listener). The method returns a wrapped error if listening or serving fails. section 10.2.2
Listing 8.1 main.go: Creating the server
package main
import "net/http"
func main() {
// Start the server.
err := http.ListenAndServe(":8080", nil) #1
if err != nil {
panic(err) #2
}
}
Browse the complete minimal net/http server, including its address, handler argument, and returned-error check. 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
}
Browse a reusable gRPC server method that separates listening, service registration, logging, serving, and error handling. section 10.2.2

