diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..0f60c40 --- /dev/null +++ b/.env.example @@ -0,0 +1 @@ +MESSAGE=Test MESSAGE \ No newline at end of file diff --git a/.gitignore b/.gitignore index 6dd513d..912acd9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ main +.env \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..0598b50 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module git.woodburn.au/nathanwoodburn/go-webserver-template + +go 1.21.3 + +require github.com/joho/godotenv v1.5.1 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..d61b19e --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= diff --git a/main.go b/main.go index 6433f3c..0a3377e 100644 --- a/main.go +++ b/main.go @@ -5,10 +5,23 @@ import ( "html/template" "log" "net/http" + "os" "path/filepath" + + "github.com/joho/godotenv" ) func main() { + // Load the .env file + err := godotenv.Load() + if err != nil { + // Try to load the .env.example file + fmt.Println("Error loading .env file, trying .env.example") + err = godotenv.Load(".env.example") + if err != nil { + log.Fatal("Error loading .env.example file") + } + } http.HandleFunc("/", mainHandler) http.HandleFunc("/assets/", assetHandler) @@ -39,6 +52,9 @@ func mainHandler(w http.ResponseWriter, r *http.Request) { func getHandler(relPath string, w http.ResponseWriter, r *http.Request) { tmplPath := filepath.Join("templates", filepath.Clean(relPath)+".html") + // Get message from Env + message := os.Getenv("MESSAGE") + // Parse the template tmpl, err := template.ParseFiles(tmplPath) if err != nil { @@ -46,8 +62,11 @@ func getHandler(relPath string, w http.ResponseWriter, r *http.Request) { return } + // Create a map to hold the data + requestData := map[string]interface{}{"envMessage": message} + // Execute the template - err = tmpl.Execute(w, nil) + err = tmpl.Execute(w, requestData) if err != nil { http.Error(w, "Error rendering template", http.StatusInternalServerError) } diff --git a/templates/index.html b/templates/index.html index 6e0048d..d9ef1c7 100644 --- a/templates/index.html +++ b/templates/index.html @@ -9,6 +9,9 @@
{{.envMessage}}
+ {{end}} {{if .message}}{{.message}}