Moving go code to subdir.
This commit is contained in:
60
code/main.go
Normal file
60
code/main.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"flag"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
|
||||
"darjeeling.systemec.nl/rhouben/fibonacci/functions"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var port_number int = 8098 // hard default
|
||||
var error error
|
||||
var bind_socket string
|
||||
var seq, port int
|
||||
|
||||
error = godotenv.Load() // Load .env file
|
||||
if error != nil {
|
||||
fmt.Printf("Error trying to load .env file: %s\n", error)
|
||||
}
|
||||
port_arg := os.Getenv("FIB_PORT")
|
||||
if port_arg != "" {
|
||||
fmt.Printf("Loaded port value '%s' from environment.\n",port_arg)
|
||||
port_number, error = strconv.Atoi(port_arg)
|
||||
if error != nil {
|
||||
fmt.Printf("I had an error trying to parse '%s' into a number: %s\n",
|
||||
port_arg,
|
||||
error)
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
flag.IntVar(&port, "port", 8098,
|
||||
fmt.Sprintf("Port number to bind to, default %d", port_number))
|
||||
flag.IntVar(&seq, "number", 0,
|
||||
"Fibonacci sequence value to calculate")
|
||||
flag.Parse()
|
||||
|
||||
if functions.FlagSet("port") { // Command line overrides env
|
||||
port_number = port
|
||||
}
|
||||
|
||||
if !functions.FlagSet("number") {
|
||||
fmt.Printf("Listening on port %d...\n", port_number)
|
||||
bind_socket = fmt.Sprintf(":%d", port_number)
|
||||
http.HandleFunc("/fibonacci", functions.HttFibonacci)
|
||||
http.HandleFunc("/sum", functions.HttSum)
|
||||
http.ListenAndServe(bind_socket, nil)
|
||||
} else {
|
||||
value, error := functions.MyFibonacci(seq)
|
||||
if error != nil {
|
||||
fmt.Printf("Failed to Fibonacci %d: %s", seq, error)
|
||||
} else {
|
||||
fmt.Printf("%d", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user