HTTP servers

Contents
HandleFunc routes
ListenAndServe
Serve JSON
Graceful shutdown sketch

HandleFunc routes

The net/http package routes requests with plain functions, no framework needed. HandleFunc binds a path pattern to a handler on the default mux. Each handler receives a writer for the response and a request to read from. Two routes are enough to see the shape of every Go server.

package main import ( "fmt" "net/http" ) func hello(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "hello, web") } func bye(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "bye, web") } func main() { http.HandleFunc("/hello", hello) http.HandleFunc("/bye", bye) http.ListenAndServe(":8080", nil) }

Patterns match path prefixes, so /hello also covers /hello/extra unless a longer pattern wins. Handlers run in their own goroutine per request, so shared state needs locking. The sync lesson later shows Mutex for exactly that case.

ListenAndServe

ListenAndServe opens the port and blocks forever serving requests. It returns only on failure, so wrap it in log.Fatal to surface startup errors. The address has the form host:port, and an empty host means all interfaces. Run the server, then query it from a second terminal.

package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "hello, web") }) log.Fatal(http.ListenAndServe(":8080", nil)) }

curl localhost:8080/hello

hello, web

Serve JSON

APIs answer with JSON instead of plain text. Set the Content-Type header before writing, then encode the value straight into the response writer. Encoding to the writer avoids building the whole body in memory. The JSON lesson earlier covers tags that shape the output.

package main import ( "encoding/json" "net/http" ) type Status struct { OK bool `json:"ok"` Name string `json:"name"` } func status(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(Status{OK: true, Name: "api"}) } func main() { http.HandleFunc("/status", status) http.ListenAndServe(":8080", nil) }

curl localhost:8080/status

{"ok":true,"name":"api"}

Graceful shutdown sketch

Production servers finish in-flight requests before they exit. The sketch below listens for interrupt signals, then gives handlers five seconds to drain. Shutdown with a timeout context is the standard recipe. Copy this shape into every long-lived service you write.

package main import ( "context" "fmt" "net/http" "os/signal" "syscall" "time" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "hello, web") }) srv := &http.Server{Addr: ":8080", Handler: mux} ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() go func() { <-ctx.Done() shut, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() srv.Shutdown(shut) }() srv.ListenAndServe() }

NotifyContext turns OS signals into a context that closes itself on Ctrl+C. The goroutine waits for that moment and then drains the server. Contexts get a full lesson of their own two chapters ahead.

Next: HTTP clients

Article author: Arthur Isaev

Related articles
Golang
Go course: zero to hero in 50 lessons
What is Go and where it runs
Install Go and check the version
Your first Go program
Modules with go mod
Variables
Constants
Types
Numbers
Strings
Conditions with if
Switch in Go
Loops with for
Arrays in Go
Slices in Go
Maps in Go
Functions in Go
Errors as values
Pointers in Go
Structs in Go
Methods in Go
Interfaces in Go
Embedding instead of inheritance
Generics in Go
Packages and imports
The go toolchain
Testing with go test
Advanced errors
defer in Go
Strings, bytes and runes
Time in Go
JSON
Files and IO
HTTP servers
HTTP clients
Context
Goroutines
Channels
select and sync
CLI: args, flags, env
Logging
Regular expressions
Sorting
Concurrency patterns
Databases with database/sql
Benchmarks and profiling
Toolchain and CI
Project layout
Capstone: wordfreq CLI
Capstone: JSON API server
Hero roadmap: the whole course on one page
Install Go on Windows 11
Install Go on Ubuntu
Install Go on Rocky Linux
Install Go on macOS
Install Go on FreeBSD
Go in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: