d821d392/main.go
1970-01-01 00:00:00 +00:00

82 lines
1.7 KiB
Go

package main
import (
"test/crud"
. "test/html_components"
"test/user"
"test/test"
"github.com/joho/godotenv"
. "github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
etag "github.com/pablor21/echo-etag/v4"
"net/http"
"os"
"strings"
)
func main() {
err := godotenv.Load()
if err != nil {
crud.LogError("Error loading .env file: %v", err)
panic(err)
}
pool, err := crud.CreatePostgresConnpool(os.Getenv("DATABASE_URL"))
if err != nil {
crud.LogError("Failed to create connection pool: %v", err)
panic(err)
}
e := New()
e.Use(middleware.Logger())
htmlHandler := NewGoHtmlHandler()
staticGroup := e.Group("/static")
staticGroup.Use(etag.Etag())
staticGroup.Static("/", "static")
e.GET("/", func(c Context) error {
return RenderGoHtmlPage(c, "index", nil)
})
userRepo := user.NewUserRepository(pool)
userLogin := user.NewUserLogin(e, userRepo, htmlHandler)
userLogin.AddLoginRoute()
testRepo := test.NewTestRepository(pool)
testCrud := test.NewTestCrud(e, testRepo, htmlHandler)
testCrud.AddRoutes()
e.Use(CreateAuthenticationMiddleware(userLogin))
e.Logger.Fatal(e.Start(":8089"))
}
func CreateAuthenticationMiddleware(userLogin *user.UserLogin) MiddlewareFunc {
return func(next HandlerFunc) HandlerFunc {
return func(c Context) error {
if strings.HasPrefix(c.Path(), "/static") {
return next(c)
}
paths := []string{"/logout", "/login"}
for _, path := range paths {
if c.Path() == path {
return next(c)
}
}
if userLogin.IsSessionAuthenticated(c) {
return next(c)
}
return redirectToAuthentication(c)
}
}
}
func redirectToAuthentication(c Context) error {
return c.Redirect(http.StatusTemporaryRedirect, "/login")
}