Skip to content

Commit

Permalink
serve content from current directory; configurable port
Browse files Browse the repository at this point in the history
  • Loading branch information
tinacious committed Sep 14, 2024
1 parent 3054eb0 commit 3d0a658
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/tinacious/static-server

go 1.20
37 changes: 37 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -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)
}
15 changes: 15 additions & 0 deletions utils/port_utils.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 3d0a658

Please sign in to comment.