Lesson 18 of 60 · Go
Standard Library: `net/http` – Building a Simple Web Server
Duration: 25 minutes
net/http Basics
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
Go’s standard library ships a fully‑featured HTTP server.
package main
import (
"fmt"
"log"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, Go HTTP!")
}
func main() {
http.HandleFunc("/hello", helloHandler)
log.Println("Server listening on :8080")
log.Fatal(http.ListenAndServe(":8080", nil)
}
Routing with http.ServeMux
mux := http.NewServeMux()
mux.HandleFunc("/", home)
mux.HandleFunc("/api", apiHandler)
http.ListenAndServe(":8080", mux)
Middleware pattern (logging)
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
http.ListenAndServe(":8080", logging(mux))