This commit is contained in:
parent
1fa557838b
commit
75c2becc40
1
.env.example
Normal file
1
.env.example
Normal file
@ -0,0 +1 @@
|
||||
MESSAGE=Test MESSAGE
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -1,2 +1,3 @@
|
||||
|
||||
main
|
||||
.env
|
5
go.mod
Normal file
5
go.mod
Normal file
@ -0,0 +1,5 @@
|
||||
module git.woodburn.au/nathanwoodburn/go-webserver-template
|
||||
|
||||
go 1.21.3
|
||||
|
||||
require github.com/joho/godotenv v1.5.1
|
2
go.sum
Normal file
2
go.sum
Normal file
@ -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=
|
21
main.go
21
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)
|
||||
}
|
||||
|
@ -9,6 +9,9 @@
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello, World!</h1>
|
||||
{{if .envMessage }}
|
||||
<p>{{.envMessage}}</p>
|
||||
{{end}}
|
||||
|
||||
{{if .message}}
|
||||
<p>{{.message}}</p>
|
||||
|
Loading…
Reference in New Issue
Block a user