Files
fibonacci/functions/http.go

74 lines
1.9 KiB
Go

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)
fmt.Fprintf(w, "Fibonacci sequence index [%d]: %d\n",
seq, MyFibonacci(seq))
}
}
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))
}