functions and handlers

This commit is contained in:
Muyao CHEN 2024-06-26 17:41:50 +02:00
parent 54d1f91e7e
commit 20c6932200

View File

@ -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)
}