From 756c4dbf5310b566070807b778768e7fcf695805 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pedro=20P=C3=A9rez?= Date: Fri, 30 May 2025 01:09:08 +0200 Subject: [PATCH] add sub function --- main.go | 9 +++++++++ main_test.go | 17 +++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/main.go b/main.go index 136433f..b4aff60 100644 --- a/main.go +++ b/main.go @@ -27,6 +27,11 @@ func main() { b, _ := strconv.Atoi(r.URL.Query().Get("b")) json.NewEncoder(w).Encode(map[string]int{"result": sum(a, b)}) }) + mux.HandleFunc("/sub", func(w http.ResponseWriter, r *http.Request) { + a, _ := strconv.Atoi(r.URL.Query().Get("a")) + b, _ := strconv.Atoi(r.URL.Query().Get("b")) + json.NewEncoder(w).Encode(map[string]int{"result": sub(a, b)}) + }) http.ListenAndServe(":8080", mux) } @@ -34,3 +39,7 @@ func main() { func sum(a, b int) int { return a + b } + +func sub(a, b int) int { + return a - b +} diff --git a/main_test.go b/main_test.go index 1e71c14..940a389 100644 --- a/main_test.go +++ b/main_test.go @@ -20,3 +20,20 @@ func Test_sum(t *testing.T) { } } } + +func Test_sub(t *testing.T) { + tests := []struct { + a, b int + want int + }{ + {1, 2, -1}, + {-1, 1, -2}, + {0, 0, 0}, + } + + for _, test := range tests { + if got := sub(test.a, test.b); got != test.want { + t.Errorf("sub(%d, %d) = %d, want %d", test.a, test.b, got, test.want) + } + } +}