Your First Go Web Server


Progress
0/4

🎯 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.

1Create a directory for this lessonCurrent

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-server
2Initialize a Go moduleLocked

Go modules track your dependencies. Think of it like package.json in Node.js.

go mod init hello-server

This creates a go.mod file in your directory. Run ls to see it.

3Write the server in main.goLocked

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 program
  • import (…) β€” pull in log and net/http
  • func helloHandler(w, r) β€” writes β€œHello, Gopher!” to every response
  • http.HandleFunc(β€œ/”, …) β€” register handler for the root path
  • log.Fatal(…) β€” start server; if it fails, log and exit
4Run and test the serverLocked

Start the server:

go run main.go

You’ll see: Server starting on http://localhost:8080

Open a second terminal and test it:

curl http://localhost:8080

Or 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?