Files
fibonacci/functions/fibonacci.go

58 lines
1.5 KiB
Go

package functions
import (
"fmt"
"net/http"
"strconv"
)
func HttpAbort(w http.ResponseWriter, code int, message string) {
w.WriteHeader(code)
fmt.Fprint(w, message)
}
func MyFibonacci(count int) (fibonaccivalue int) {
fibonaccivalue = 1
var prev_fibonacci int = 0
for i := 1; i < count; i++ {
fibonaccivalue += prev_fibonacci
prev_fibonacci = fibonaccivalue - prev_fibonacci
}
return
}
func HttFibonacci(w http.ResponseWriter, request *http.Request) {
switch request.Method {
case "POST":
error := request.ParseForm()
if error != nil {
fmt.Printf("Error parsing POST request: %s\n", error)
HttpAbort(w, http.StatusUnprocessableEntity,
"Unable to parse your POST request.\n")
} else {
s_seq := request.Form.Get("seq")
seq, error := strconv.Atoi(s_seq)
if error != nil {
fmt.Printf("Error parsing integer value out of %s: %s\n",
s_seq,
error)
HttpAbort(w, http.StatusExpectationFailed,
fmt.Sprintf("[%s] is not a number.\n", s_seq))
} else if seq < 1 {
fmt.Printf("Invalid sequence number: %d\n", seq)
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))
}
}
default:
HttpAbort(w, http.StatusMethodNotAllowed,
fmt.Sprintf("Operation %s not implemented for this URL", request.Method))
}
}