Moved http related functions to their own file; added 'sum.go' for a second endpoint.
This commit is contained in:
74
functions/http.go
Normal file
74
functions/http.go
Normal file
@@ -0,0 +1,74 @@
|
||||
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 HTTP 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.\n", 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))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
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))
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user