From 20c69322009492f1abdfca1a82a9a2fd291d5553 Mon Sep 17 00:00:00 2001 From: Muyao CHEN Date: Wed, 26 Jun 2024 17:41:50 +0200 Subject: [PATCH] functions and handlers --- cmd/hello-world/main.go | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/cmd/hello-world/main.go b/cmd/hello-world/main.go index 87ca56e..e6a30b2 100644 --- a/cmd/hello-world/main.go +++ b/cmd/hello-world/main.go @@ -5,14 +5,30 @@ import ( "net/http" ) -func main() { - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - n, err := fmt.Fprintf(w, "Hello world") - if err != nil { - fmt.Println(err) - } - fmt.Printf("Number of bytes written: %d\n", n) - }) +const portNumber = ":8080" - _ = http.ListenAndServe(":8080", nil) +// Home is the about page handler +func Home(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, "This is the home page") +} + +// About is the about page handler +func About(w http.ResponseWriter, r *http.Request) { + sum := addValues(2, 2) + fmt.Fprintf(w, "This is the about page and 2 + 2 is %d", sum) +} + +// addValues adds two integers and returns the sum +func addValues(x, y int) int { + return x + y +} + +// main is the main application function +func main() { + http.HandleFunc("/", Home) + http.HandleFunc("/about", About) + + fmt.Printf("Starting application on port %s\n", portNumber) + + _ = http.ListenAndServe(portNumber, nil) }