Added configuration from environment variables

This commit is contained in:
2025-02-08 16:27:33 +11:00
parent 1004dc9563
commit a842d09f96
7 changed files with 48 additions and 19 deletions

View File

@@ -3,7 +3,6 @@ package cookies
import ( import (
"net/http" "net/http"
"net/url" "net/url"
"os"
"time" "time"
) )
@@ -18,15 +17,14 @@ func CheckPageFrom(w http.ResponseWriter, r *http.Request) string {
return pageFrom return pageFrom
} }
func SetPageFrom(w http.ResponseWriter, r *http.Request) { func SetPageFrom(w http.ResponseWriter, r *http.Request, trustedHost string) {
referer := r.Referer() referer := r.Referer()
parsedURL, err := url.Parse(referer) parsedURL, err := url.Parse(referer)
if err != nil { if err != nil {
return return
} }
var pageFrom string var pageFrom string
expectedHost := os.Getenv("TRUSTED_HOST") if parsedURL.Path == "" || parsedURL.Host != trustedHost {
if parsedURL.Path == "" || parsedURL.Host != expectedHost {
pageFrom = "/" pageFrom = "/"
} else { } else {
pageFrom = parsedURL.Path pageFrom = parsedURL.Path

1
go.mod
View File

@@ -5,4 +5,5 @@ go 1.23.5
require ( require (
github.com/a-h/templ v0.3.833 github.com/a-h/templ v0.3.833
github.com/joho/godotenv v1.5.1 github.com/joho/godotenv v1.5.1
github.com/pkg/errors v0.9.1
) )

2
go.sum
View File

@@ -4,3 +4,5 @@ github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=

View File

@@ -65,10 +65,10 @@ func HandleLoginRequest() http.Handler {
) )
} }
func HandleLoginPage() http.Handler { func HandleLoginPage(trustedHost string) http.Handler {
return http.HandlerFunc( return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) { func(w http.ResponseWriter, r *http.Request) {
cookies.SetPageFrom(w, r) cookies.SetPageFrom(w, r, trustedHost)
page.Login().Render(r.Context(), w) page.Login().Render(r.Context(), w)
}, },
) )

14
main.go
View File

@@ -4,7 +4,7 @@ import (
"context" "context"
"embed" "embed"
"fmt" "fmt"
"github.com/joho/godotenv" "github.com/pkg/errors"
"io" "io"
"net" "net"
"net/http" "net/http"
@@ -19,12 +19,12 @@ func run(ctx context.Context, w io.Writer) error {
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt) ctx, cancel := signal.NotifyContext(ctx, os.Interrupt)
defer cancel() defer cancel()
config := &server.Config{ config, err := server.GetConfig()
Host: "", if err != nil {
Port: "3333", return errors.Wrap(err, "server.GetConfig")
} }
srv := server.NewServer() srv := server.NewServer(config)
httpServer := &http.Server{ httpServer := &http.Server{
Addr: net.JoinHostPort(config.Host, config.Port), Addr: net.JoinHostPort(config.Host, config.Port),
Handler: srv, Handler: srv,
@@ -58,10 +58,6 @@ func run(ctx context.Context, w io.Writer) error {
var static embed.FS var static embed.FS
func main() { func main() {
err := godotenv.Load(".env")
if err != nil {
panic(err.Error())
}
ctx := context.Background() ctx := context.Background()
if err := run(ctx, os.Stdout); err != nil { if err := run(ctx, os.Stdout); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err) fmt.Fprintf(os.Stderr, "%s\n", err)

View File

@@ -8,6 +8,7 @@ import (
func addRoutes( func addRoutes(
mux *http.ServeMux, mux *http.ServeMux,
config *Config,
) { ) {
// Static files // Static files
mux.Handle("GET /static/", http.StripPrefix("/static/", handlers.HandleStatic())) mux.Handle("GET /static/", http.StripPrefix("/static/", handlers.HandleStatic()))
@@ -19,6 +20,6 @@ func addRoutes(
mux.Handle("GET /about", handlers.HandlePage(page.About())) mux.Handle("GET /about", handlers.HandlePage(page.About()))
// Login page and handlers // Login page and handlers
mux.Handle("GET /login", handlers.HandleLoginPage()) mux.Handle("GET /login", handlers.HandleLoginPage(config.TrustedHost))
mux.Handle("POST /login", handlers.HandleLoginRequest()) mux.Handle("POST /login", handlers.HandleLoginRequest())
} }

View File

@@ -1,19 +1,50 @@
package server package server
import ( import (
"errors"
"fmt"
"net/http" "net/http"
"os"
"projectreshoot/middleware" "projectreshoot/middleware"
"github.com/joho/godotenv"
) )
type Config struct { type Config struct {
Host string TrustedHost string
Port string Host string
Port string
} }
func NewServer() http.Handler { func GetConfig() (*Config, error) {
err := godotenv.Load(".env")
if err != nil {
fmt.Println(".env file not found.")
}
config := &Config{
Host: os.Getenv("HOST"),
Port: os.Getenv("PORT"),
TrustedHost: os.Getenv("TRUSTED_HOST"),
}
if config.Host == "" {
return nil, errors.New("Envar not set: HOST")
}
if config.Port == "" {
return nil, errors.New("Envar not set: PORT")
}
if config.TrustedHost == "" {
return nil, errors.New("Envar not set: TRUSTED_HOST")
}
return config, nil
}
func NewServer(config *Config) http.Handler {
mux := http.NewServeMux() mux := http.NewServeMux()
addRoutes( addRoutes(
mux, mux,
config,
) )
var handler http.Handler = mux var handler http.Handler = mux
handler = middleware.Logging(handler) handler = middleware.Logging(handler)