package main
import (
"errors"
"fmt"
"net/http"
"strconv"
)
const formPage = `
Calculator
Calculator
`
const limit = 1000000
// readNumber converts one form value, and checks its range.
func readNumber(label string, text string) (int, error) {
n, err := strconv.Atoi(text)
if err != nil {
return 0, fmt.Errorf("%s must be a whole number", label)
}
if n < -limit || n > limit {
return 0, fmt.Errorf("%s must be from %d to %d", label, -limit, limit)
}
return n, nil
}
// calculate returns the answer, or an error that is safe to show the visitor.
func calculate(a int, op string, b int) (int, error) {
switch op {
case "add":
return a + b, nil
case "sub":
return a - b, nil
case "mul":
return a * b, nil
case "div":
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}
return 0, errors.New("op must be add, sub, mul or div")
}
func handleForm(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, formPage)
}
func handleCalc(w http.ResponseWriter, r *http.Request) {
a, err := readNumber("a", r.FormValue("a"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
b, err := readNumber("b", r.FormValue("b"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
op := r.FormValue("op")
answer, err := calculate(a, op, b)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Fprintf(w, "%d %s %d = %d\n", a, op, b, answer)
}
func main() {
http.HandleFunc("GET /{$}", handleForm)
http.HandleFunc("GET /calc", handleCalc)
fmt.Println("Server running at http://localhost:8080")
fmt.Println("Press Ctrl+C to stop it.")
err := http.ListenAndServe("localhost:8080", nil)
if err != nil {
fmt.Println("Server stopped:", err)
}
}