Building an HTTP server
โ Report an issue with this lessonpackage main
import (
"encoding/json"
"net/http"
)
type Course struct {
Title string `json:"title"`
Price float64 `json:"price"`
}
func coursesHandler(w http.ResponseWriter, r *http.Request) {
courses := []Course{{"HTML Fundamentals", 29.99}}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(courses)
}
func main() {
http.HandleFunc("/courses", coursesHandler)
http.ListenAndServe(":8080", nil)
}
The standard library's net/http is enough to build a real
API without any framework -- Go's philosophy leans toward a strong
standard library over heavy dependencies.
Try it yourself
Exercise: Complete coursesHandler so it JSON-encodes the courses slice directly into w using json.NewEncoder(w).Encode(...) -- the same io.Writer pattern a real http.ResponseWriter satisfies, here using a plain bytes.Buffer so it runs without starting an actual server.
Expected output:
[{"title":"HTML Fundamentals","price":29.99}]
Run your code and get it working before marking this lesson complete.
// that was the last free lesson
9 more lessons โ including Project: build and deploy a courses API โ and a final exam plus a certificate are waiting.
Unlock the full course โ $99.99