liveBook · Manning

ListenAndServe

As explained in Go in Practice, Second Edition

http.Server.ListenAndServe is a Go method that starts an HTTP server and serves requests on its configured network address.

http.ListenAndServe starts an HTTP server on a configured network address and blocks while it serves requests. Register a handler first, then pass an address such as localhost:4000; a nil handler uses the package's registered handlers. section 1.5 section 2.3.2

A minimal server follows this sequence:

  • Define a handler receiving http.ResponseWriter and *http.Request. section 1.5
  • Register the handler for a path with http.HandleFunc. section 1.5
  • Call http.ListenAndServe with the listening address and handler configuration. section 1.5
  • Run during development with go run, or build and execute a binary with go build. section 1.5

Hello World server

func main() { http.HandleFunc("/", hello) http.ListenAndServe("localhost:4000", nil) } This serves the root path on localhost port 4000. For a configured http.Server, call server.ListenAndServe in a goroutine when the main goroutine must monitor operating-system signals. section 1.5 section 2.3.2

Listing 1.15 Hello World web server
package main              #1

import (             #2
     "fmt"           #2
     "net/http"      #2
)                    #2

func hello(w http.ResponseWriter, r *http.Request) {       #3
     fmt.Fprint(w, "Hello, my name is Inigo Montoya")      #3
}                                                          #3

func main() {                                       #4
     http.HandleFunc("/", hello)                    #4
     http.ListenAndServe("localhost:4000", nil)     #4
}                                                   #4

Inspect the complete Hello World implementation, including imports, handler, route registration, and server startup. section 1.5

How Go in Practice, Second Edition covers it

How deep it goes
Explains address binding, blocking execution, handler registration, and graceful-shutdown integration without detailing lower-level networking internals.
Examples
Uses a Hello World handler on localhost:4000 and a configured :8080 server stopped after an interrupt signal.
What it assumes
Assumes basic Go functions and packages while demonstrating handlers, imports, routing, goroutines, and signal channels.
What you can do after
Operate a Go HTTP server, run it with go run, build it with go build, and coordinate shutdown with http.Server.Shutdown.
How it connects
Connects HTTP handlers, routing, goroutines, operating-system signals, 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 Go in Practice, Second Edition. The section links point to the parts of the book it draws on.