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

