From 3d0a65803516a94db617192090c45bf3b538a47d Mon Sep 17 00:00:00 2001 From: "@tinacious" Date: Sat, 14 Sep 2024 15:31:27 -0400 Subject: [PATCH] serve content from current directory; configurable port --- go.mod | 3 +++ main.go | 37 +++++++++++++++++++++++++++++++++++++ utils/port_utils.go | 15 +++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 go.mod create mode 100644 main.go create mode 100644 utils/port_utils.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..2721611 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/tinacious/static-server + +go 1.20 diff --git a/main.go b/main.go new file mode 100644 index 0000000..b45e9cc --- /dev/null +++ b/main.go @@ -0,0 +1,37 @@ +package main + +import ( + "fmt" + "net/http" + "os" + "strconv" + + "github.com/tinacious/static-server/utils" +) + +func main() { + port := utils.GetRandomPort() + + // Use configured port + portString := os.Getenv("PORT") + if portString != "" { + i, err := strconv.Atoi(portString) + if err != nil { + fmt.Printf("⛔️ invalid port %s - using random port %d\n", portString, port) + } else { + port = i + } + } else { + fmt.Printf("🎲 using random port %d - to configure, set the environment variable PORT\n", port) + } + + cwd, err := os.Getwd() + if err != nil { + panic(err) + } + + fmt.Printf("🚀 static server at: http://localhost:%d with contents from %s\n", port, cwd) + + http.Handle("/", http.FileServer(http.Dir("."))) + http.ListenAndServe(fmt.Sprintf(":%d", port), nil) +} diff --git a/utils/port_utils.go b/utils/port_utils.go new file mode 100644 index 0000000..6edfc22 --- /dev/null +++ b/utils/port_utils.go @@ -0,0 +1,15 @@ +package utils + +import ( + "math/rand" + "time" +) + +func GetRandomPort() int { + var min int = 1024 + var max int = 66535 + + r := rand.New(rand.NewSource(time.Now().UnixNano())) + + return r.Intn(max-min+1) + min +}