0
0
GoHow-ToBeginner · 3 min read

How to Use http.ListenAndServe in Go: Simple Guide

Use http.ListenAndServe in Go to start a web server by specifying the address and a handler. It listens on the given network address and serves HTTP requests using the provided handler, often nil for the default multiplexer.
📐

Syntax

The basic syntax of http.ListenAndServe is:

  • addr: a string specifying the network address to listen on, like :8080.
  • handler: an http.Handler to handle requests; nil uses the default handler.

The function blocks and runs the server until it stops or an error occurs.

go
func ListenAndServe(addr string, handler http.Handler) error
💻

Example

This example starts a simple web server on port 8080 that responds with "Hello, world!" to every request.

go
package main

import (
	"fmt"
	"net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hello, world!")
}

func main() {
	http.HandleFunc("/", helloHandler)
	// Start server on port 8080
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		panic(err)
	}
}
Output
When you visit http://localhost:8080 in a browser, it shows: Hello, world!
⚠️

Common Pitfalls

  • Not handling the error returned by ListenAndServe can hide server startup problems.
  • Using an invalid address like an occupied port causes the server to fail immediately.
  • Passing nil as handler uses the default http.DefaultServeMux, so you must register handlers with http.HandleFunc or http.Handle.
  • Calling ListenAndServe blocks the current goroutine, so code after it won’t run unless it runs in a separate goroutine.
go
package main

import (
	"fmt"
	"net/http"
)

func main() {
	// Wrong: ignoring error
	_ = http.ListenAndServe(":8080", nil)

	// Right: handle error
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("Server error:", err)
	}
}
📊

Quick Reference

Tips for using http.ListenAndServe:

  • Use :port format to listen on all interfaces.
  • Pass nil to use default handler or provide a custom http.Handler.
  • Always check the error returned to catch startup issues.
  • Register routes before calling ListenAndServe.

Key Takeaways

http.ListenAndServe starts an HTTP server listening on the given address and handles requests with the provided handler.
Passing nil as handler uses the default request multiplexer, so register handlers with http.HandleFunc or http.Handle.
Always check the error returned by ListenAndServe to detect startup failures like port conflicts.
ListenAndServe blocks the current goroutine; run it in a separate goroutine if you need concurrent code execution.
Use the address format ':port' to listen on all network interfaces on that port.