User Tools

Site Tools


go:stdlib:http_server_listenandserve

http.ListenAndServe

What is it?

`http.ListenAndServe(addr, handler)` starts a basic HTTP server.

  • It listens on `addr` (for example `“:8080”`).
  • It serves requests using `handler`.
  • If `handler` is `nil`, it uses `http.DefaultServeMux`.

It blocks until the server exits (or returns an error).

What is it used for?

  • Quick local servers for learning and prototypes.
  • Simple services (health checks, internal tools).
  • Basic REST APIs when you don’t need custom server settings yet.

Example: using DefaultServeMux

package main
 
import (
    "log"
    "net/http"
)
 
func main() {
    http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("ok"))
    })
 
    log.Fatal(http.ListenAndServe(":8080", nil))
}

Example: using a custom mux

package main
 
import (
    "log"
    "net/http"
)
 
func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("hello"))
    })
 
    log.Fatal(http.ListenAndServe(":8080", mux))
}

Notes / pitfalls

  • Always handle the error returned by `ListenAndServe`.
  • `ListenAndServe` is a helper. For production, prefer `http.Server{…}` with timeouts.
  • `nil` handler means the global `DefaultServeMux` is used (be careful in large apps).

Hard words (English)

  • address (addr) /əˈdres/: địa chỉ
  • port /pɔːrt/: cổng
  • block /blɑːk/: chặn (không thoát)
  • helper /ˈhelpər/: hàm tiện ích
  • prototype /ˈproʊtətaɪp/: bản thử nghiệm
  • global /ˈɡloʊbəl/: toàn cục
go/stdlib/http_server_listenandserve.txt · Last modified: by phong2018