implemented
authorMauro Scomparin <scompo@gmail.com>
Wed, 26 Feb 2020 20:46:27 +0000 (21:46 +0100)
committerMauro Scomparin <scompo@gmail.com>
Wed, 26 Feb 2020 20:46:27 +0000 (21:46 +0100)
server.go [new file with mode: 0644]
test/server_test.go [new file with mode: 0644]

diff --git a/server.go b/server.go
new file mode 100644 (file)
index 0000000..2d972e1
--- /dev/null
+++ b/server.go
@@ -0,0 +1,61 @@
+package main
+
+import (
+        "fmt"
+        "log"
+        "net/http"
+        "os"
+        "strings"
+)
+
+const (
+        ENV_VAR_SERVER_PORT = "SERVER_PORT"
+        ENV_VAR_SERVER_DIR = "SERVER_DIR"
+        DEFAULT_SERVER_PORT = ":4000"
+        DEFAULT_SERVER_DIR = "./static"
+)
+
+func configuredPort() string {
+        return ReadEnvVar(ENV_VAR_SERVER_PORT, DEFAULT_SERVER_PORT)
+}
+
+func configuredDir() string {
+        return ReadEnvVar(ENV_VAR_SERVER_DIR, DEFAULT_SERVER_DIR)
+}
+
+func ReadEnvVar(name string, defaultValue string) string {
+        variable := os.Getenv(name)
+        if variable == "" {
+                variable = defaultValue
+        }
+        return variable
+}
+
+func main() {
+        port := configuredPort()
+        dir := configuredDir()
+        log.Println("static-server serving directory: ", dir, " on port: " port)
+        err := http.ListenAndServe(port, http.FileServer(neuteredFileSystem{http.Dir(dir)}))
+        log.Fatal(err)
+}
+
+type neuteredFileSystem struct {
+        fs http.FileSystem
+}
+
+func (nfs neuteredFileSystem) Open(path string) (http.File, error) {
+        f, err := nfs.fs.Open(path)
+        if err != nil {
+                return nil, err
+        }
+
+        s, err := f.Stat()
+        if s.IsDir() {
+                index := strings.TrimSuffix(path, "/") + "/index.html"
+                if _, err := nfs.fs.Open(index); err != nil {
+                        return nil, err
+                }
+        }
+
+        return f, nil
+}
\ No newline at end of file
diff --git a/test/server_test.go b/test/server_test.go
new file mode 100644 (file)
index 0000000..7d269c3
--- /dev/null
@@ -0,0 +1,27 @@
+package main
+
+import (
+        "testing"
+        "os"
+)
+
+const (
+        defaultValue = "DEFAULT VALUE"
+        envVar = "MY_TEST_VAR"
+        expectedValue = "MY TEST VALUE"
+)
+
+func TestReadEnvVarReturnsDefaultValueWhenEnvVarNotSet(t *testing.T) {
+        res := ReadEnvVar("NOT_PRESENT", defaultValue)
+       if res != defaultValue {
+                t.Errorf("Did not return the default value when the enviroinment variable wasn't set")
+        }
+}
+
+func TestReadEnvVarReturnsTheExpectedValueWhenSet(t *testing.T) {
+        os.SetEnv(envVar, expectedValue)
+        res := ReadEnvVar(envVar, defaultValue)
+       if res != expectedValue {
+                t.Errorf("Did not return the expected value set in the enviroinment variable")
+        }
+}
\ No newline at end of file