From 4eefdfe47cefc79849cca7324d7410c2b900366f Mon Sep 17 00:00:00 2001 From: Muyao CHEN Date: Wed, 26 Jun 2024 17:49:08 +0200 Subject: [PATCH] Error checking --- cmd/hello-world/main.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/cmd/hello-world/main.go b/cmd/hello-world/main.go index e6a30b2..1361da2 100644 --- a/cmd/hello-world/main.go +++ b/cmd/hello-world/main.go @@ -1,6 +1,7 @@ package main import ( + "errors" "fmt" "net/http" ) @@ -23,10 +24,29 @@ func addValues(x, y int) int { return x + y } +// About is the about page handler +func Divide(w http.ResponseWriter, r *http.Request) { + f, err := divideValues(100.0, 0.0) + if err != nil { + fmt.Fprintf(w, "Cannot divide by 0\n") + return + } + fmt.Fprintf(w, "%f divided by %f is %f\n", 100.0, 0.0, f) +} + +func divideValues(x, y float32) (float32, error) { + if y <= 0 { + err := errors.New("cannot divide by zero") + return 0, err + } + return x / y, nil +} + // main is the main application function func main() { http.HandleFunc("/", Home) http.HandleFunc("/about", About) + http.HandleFunc("/divide", Divide) fmt.Printf("Starting application on port %s\n", portNumber)