package main import ( "backend/config" "backend/queries" "fmt" "io" "log" "net/http" "os" "strconv" "strings" "text/template" "github.com/labstack/echo/v4" ) type Server struct { config *config.Config } func NewServer(cfg *config.Config) (*Server, error) { return &Server{ config: cfg, }, nil } func (s *Server) SetupRoutes() *echo.Echo { funcs := map[string]any{ "contains": strings.Contains, "hasPrefix": strings.HasPrefix, "hasSuffix": strings.HasSuffix, "getImage": func(txt string) string { return txt[7:] }, "isWebp": func(txt string) bool { return strings.Contains(txt, "webp") }, } t := &Template{ templates: template.Must(template.New("").Funcs(funcs).ParseGlob("public/views/*.html")), } e := echo.New() e.Renderer = t // MISC e.Static("/static", "public/static") e.GET("/", func(c echo.Context) error { return c.Render(http.StatusOK, "main", map[string]any{ "imageOption": s.config.Images.Enabled, "concurrentImages": s.config.Images.ConcurrentLimit, }) }) e.GET("/test", func(c echo.Context) error { return c.JSONPretty(http.StatusOK, map[string]any{ "files": "", }, " ") }) e.POST("/testpost", func(c echo.Context) error { // Get the form value test := c.FormValue("test") fmt.Println("test:", test) return c.String(http.StatusOK, "OK") }) e.GET("/health", func(c echo.Context) error { h := queries.HealthCheck() return c.JSONPretty(http.StatusOK, fmt.Sprintf("DB Connection: %v", h), " ") }) e.GET("/update", func(c echo.Context) error { //da inizializzare on server startup non qui u := NewUpdater(UpdaterConfig{ isDryRun: c.QueryParam("dryrun") == "true", codFilter: c.QueryParam("cod"), forceMediaRefresh: c.QueryParam("forcemedia") == "true", }) err := u.Update() if err != nil { return c.String(http.StatusInternalServerError, err.Error()) } return c.String(http.StatusOK, "update") }) //IMAGE ROUTES e.GET("/initcwebp", func(c echo.Context) error { Conversion("test.jpg") return c.String(http.StatusOK, "Cwebp initialized") }) e.POST("/image-option-toggle", func(c echo.Context) error { // Toggle the imageOption value s.config.Images.Enabled = !s.config.Images.Enabled // Convert the boolean value to a string and set the environment variable os.Setenv("IMAGEOPTION", strconv.FormatBool(s.config.Images.Enabled)) return c.String(http.StatusOK, "OK") }) return e } func (s *Server) Start() { e := s.SetupRoutes() Conversion("test.jpg") fmt.Println("Image Option: ", s.config.Images.Enabled) fmt.Println("Concurrent Images: ", s.config.Images.ConcurrentLimit) fmt.Println("Server url: http://localhost:" + strconv.Itoa(s.config.Server.Port)) e.Logger.Info(e.Start(":" + strconv.Itoa(s.config.Server.Port))) } func main() { cfg := config.Load() server, err := NewServer(cfg) if err != nil { log.Fatalf("Server initialization error: %v", err) } server.Start() } type Template struct { templates *template.Template } func (t *Template) Render(w io.Writer, name string, data any, c echo.Context) error { return t.templates.ExecuteTemplate(w, name, data) }