liveBook · Manning

ListenAndServe

As explained in Learn Go with Pocket-Sized Projects

ListenAndServe is a Go server API that starts accepting network connections and returns an error when serving stops or fails.

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

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains addresses, ports, handlers, blocking behavior, errors, listeners, registration, and testable startup structure.
Examples
Uses localhost:8080, curl, a minimal main function, and a habits-tracker gRPC server with injected logging.
What it assumes
Assumes basic Go and net/http familiarity while introducing ports, handlers, listeners, service registration, and injected loggers.
What you can do after
Operate/configure a Go HTTP or gRPC service, verify it with curl, and report startup or serving failures.
How it connects
Connects HTTP servers, request handlers, TCP listeners, gRPC servers, service registration, error handling, logging, and graceful shutdown.

Also explained in

Compare how 2 books explain ListenAndServe →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.