Your First Go Web Server
π― Your mission: Build backend services with Go. This lesson gets you running a real HTTP server in under 15 lines β your first tangible step toward building APIs.
What youβll build: A tiny web server on localhost:8080 that responds βHello, Gopher!β to every request.
Every Go program lives in a package
An executable must be in package main with a func main() entry point. β spec
You import what you use
Unused imports are a compile error. We need net/http for the HTTP server and log for printing messages. β net/http docs
A handler function responds to requests
Signature: func(w http.ResponseWriter, r *http.Request). Write to w to send a response, read from r for request details. β HandleFunc docs
ListenAndServe starts the server
http.ListenAndServe(β:8080β, nil) blocks forever, handling requests on port 8080. β docs
Follow each step in order. Click Done β after completing it to unlock the next one.
Open your terminal and create a fresh directory:
mkdir -p ~/dev/learn/go-lang/lessons/0001-hello-server
cd ~/dev/learn/go-lang/lessons/0001-hello-serverGo modules track your dependencies. Think of it like package.json in Node.js.
go mod init hello-serverThis creates a go.mod file in your directory. Run ls to see it.
Create a file named main.go with this content:
package main
import (
"log"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, Gopher!\n"))
}
func main() {
http.HandleFunc("/", helloHandler)
log.Println("Server starting on http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}Whatβs happening line by line?
package mainβ executable programimport (β¦)β pull in log and net/httpfunc helloHandler(w, r)β writes βHello, Gopher!β to every responsehttp.HandleFunc(β/β, β¦)β register handler for the root pathlog.Fatal(β¦)β start server; if it fails, log and exit
Start the server:
go run main.goYouβll see: Server starting on http://localhost:8080
Open a second terminal and test it:
curl http://localhost:8080Or open http://localhost:8080 in your browser.
Expected response: Hello, Gopher!
Press Ctrl+C in the server terminal to stop it.
Check your understanding
Q1: What does package main tell Go?
Q2: What happens if you import "fmt" but never use it?