-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
50 lines (45 loc) · 1.11 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"strconv"
)
var tpl = template.Must(template.ParseFiles("index.html"))
func main() {
http.HandleFunc("/", calculatorHandler)
fmt.Println("Starting server on :8080...")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func calculatorHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
num1, err1 := strconv.ParseFloat(r.FormValue("num1"), 64)
operator := r.FormValue("operator")
num2, err2 := strconv.ParseFloat(r.FormValue("num2"), 64)
var result string
if err1 != nil || err2 != nil {
result = "Invalid number"
} else {
switch operator {
case "+":
result = fmt.Sprintf("Result: %.2f", num1+num2)
case "-":
result = fmt.Sprintf("Result: %.2f", num1-num2)
case "*":
result = fmt.Sprintf("Result: %.2f", num1*num2)
case "/":
if num2 == 0 {
result = "Error: division by zero"
} else {
result = fmt.Sprintf("Result: %.2f", num1/num2)
}
default:
result = "Error: Invalid operator. Use +, -, *, or /."
}
}
tpl.Execute(w, result)
return
}
tpl.Execute(w, nil)
}