knative-report-functions/isprime-go/isprime.go

42 lines
773 B
Go
Raw Normal View History

2019-10-06 23:56:19 +02:00
package main
import (
"fmt"
"log"
"net/http"
"os"
2019-10-07 00:03:34 +02:00
"math"
"strconv"
2019-10-06 23:56:19 +02:00
)
func handler(w http.ResponseWriter, r *http.Request) {
target := os.Getenv("TARGET")
num, err := strconv.Atoi(target)
if err != nil {
2019-10-07 00:04:46 +02:00
fmt.Errorf("Failed to parse %s as int! %v", target, err)
2019-10-06 23:56:19 +02:00
}
2019-10-07 00:03:34 +02:00
log.Print("Checking if %s is prime", target)
2019-10-06 23:56:19 +02:00
if num <= 1 {
2019-10-07 00:07:26 +02:00
fmt.Sprintf("%d is not prime", num)
2019-10-06 23:56:19 +02:00
}
for i := 2; i <= int(math.Floor(float64(num)/2)); i++ {
if num%i == 0 {
2019-10-07 00:07:26 +02:00
fmt.Sprintf("%d is not prime", num)
2019-10-06 23:56:19 +02:00
}
}
2019-10-07 00:07:26 +02:00
fmt.Sprintf("%d is prime", num)
2019-10-06 23:56:19 +02:00
}
func main() {
log.Print("Hello world sample started.")
http.HandleFunc("/", handler)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}