Creating an HTTP Server
Start with Creating an HTTP Server
In this lesson, explore creating an http server through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of creating an http server.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
http.Server listens for connections, calls a handler for each request, and manages request lifecycles. Production servers should set sensible timeouts and plan graceful shutdown.
The primary example demonstrates a handler without opening a socket; the additional snippet shows the real server call.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Actual localhost server
package main
import (
"fmt"
"log"
"net/http"
"time"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") })
server := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5*time.Second}
log.Fatal(server.ListenAndServe())
}Run with go run . and open http://localhost:8080/. The process keeps running until stopped. For shutdown, call server.Shutdown(ctx) after a termination signal.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Go server is ready") })
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
fmt.Println(rec.Body.String())
}
Output
Go server is readyTrace what the program does
NewServeMux registers a GET endpoint. The example sends a request through the mux and captures the handler output.
Avoid common mistakes
- http.ListenAndServe blocks while the server runs.
- Use a dedicated http.Server with timeouts and a controlled shutdown path in production.
Try it yourself
Run the server snippet locally, visit /, and try a request with the wrong method.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Creating an HTTP Server in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.