package functions // HTTP helper functions doing the input checking and calling the actual math functions import ( "fmt" "net/http" "strconv" ) func HttpAbort(w http.ResponseWriter, code int, message string) { w.WriteHeader(code) fmt.Fprint(w, message) } func HttpGetPostInt(request *http.Request, key string) (value int, error error) { switch request.Method { case "POST": error = request.ParseForm() if error != nil { error = fmt.Errorf("unable to parse post input: %s", error.Error()) return } value, error = strconv.Atoi(request.Form.Get(key)) if error != nil { fmt.Printf("Error parsing parameter '%s'\n", key) error = fmt.Errorf("unable to parse parameter '%s' as an integer: %s", key, error.Error()) } return default: error = fmt.Errorf("this endpoint does not support %s operations", request.Method) return } } func HttFibonacci(w http.ResponseWriter, request *http.Request) { seq, error := HttpGetPostInt(request, "seq") if error != nil { HttpAbort(w, http.StatusBadRequest, fmt.Sprintf("Could not get parameter: %s", error.Error())) } else if seq < 1 { HttpAbort(w, http.StatusBadRequest, "Please provide a positive integer as the sequence number.\n") } else { fmt.Printf("Received request for Fibonacci Sequence Number %d\n", seq) value, error := MyFibonacci(seq) if error != nil { fmt.Printf("Error trying to Fibonacci %d: %s", seq, error) fmt.Fprintf(w, "Error trying to Fibonacci %d: %s", seq, error) } else { fmt.Fprintf(w, "Fibonacci sequence index [%d]: %d\n", seq, value) } } } func HttSum(w http.ResponseWriter, request *http.Request) { var errorstr string first, error := HttpGetPostInt(request, "first") if error != nil { errorstr = error.Error() } second, error := HttpGetPostInt(request, "second") if error != nil { errorstr = error.Error() } if errorstr != "" { HttpAbort(w, http.StatusBadRequest, fmt.Sprintf("Invalid input: %s\n", errorstr)) return } fmt.Printf("Received a request to add %d and %d.\n", first, second) fmt.Fprintf(w, "The sum of %d and %d is %d.\n", first, second, sum(first, second)) }