package main import ( "fmt" "net/http" ) const pageFormat = `
%s
` // writePage sends a whole page. The title and the body must be text from this // program, never text from a visitor, because they go into the HTML as they are. func writePage(w http.ResponseWriter, status int, title string, body string) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(status) fmt.Fprintf(w, pageFormat, title, title, body) } func handleHome(w http.ResponseWriter, r *http.Request) { writePage(w, http.StatusOK, "Home", "Welcome to a small site.") } func handleAbout(w http.ResponseWriter, r *http.Request) { writePage(w, http.StatusOK, "About", "This site is one Go file.") } func handleGames(w http.ResponseWriter, r *http.Request) { writePage(w, http.StatusOK, "Games", "Number Guess and Monster Battle.") } func handleNotFound(w http.ResponseWriter, r *http.Request) { writePage(w, http.StatusNotFound, "Not found", "There is no page at this address.") } func main() { http.HandleFunc("GET /{$}", handleHome) http.HandleFunc("GET /about", handleAbout) http.HandleFunc("GET /games", handleGames) http.HandleFunc("GET /", handleNotFound) fmt.Println("Server running at http://localhost:8080") fmt.Println("Press Ctrl+C to stop it.") err := http.ListenAndServe("localhost:8080", nil) if err != nil { fmt.Println("Server stopped:", err) } }