From d383386f24e46fdd0dd5ffce968858dead43a65a Mon Sep 17 00:00:00 2001 From: Mauro Scomparin Date: Wed, 26 Feb 2020 21:46:27 +0100 Subject: [PATCH] implemented --- server.go | 61 +++++++++++++++++++++++++++++++++++++++++++++ test/server_test.go | 27 ++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 server.go create mode 100644 test/server_test.go diff --git a/server.go b/server.go new file mode 100644 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 index 0000000..7d269c3 --- /dev/null +++ b/test/server_test.go @@ -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 -- 2.25.1