selvaGo/cmd/main.go

68 lines
2.1 KiB
Go
Raw Permalink Normal View History

2025-03-21 21:22:38 +00:00
package main
import (
2025-03-21 22:21:00 +00:00
"html/template"
2025-03-21 21:22:38 +00:00
"log"
2025-04-04 21:55:58 +00:00
"net/http"
2025-03-21 21:22:38 +00:00
_ "github.com/go-sql-driver/mysql"
2025-04-04 21:55:58 +00:00
"github.com/gorilla/mux"
2025-03-21 21:22:38 +00:00
"go_selva/internal/api"
"go_selva/internal/db"
)
func main() {
// Initialize database connection
database, err := db.InitDB()
if err != nil {
log.Fatalf("Failed to initialize database: %v", err)
}
defer database.Close()
2025-04-04 21:55:58 +00:00
// Initialize Gorilla Mux router
router := mux.NewRouter()
2025-03-21 21:22:38 +00:00
2025-04-04 21:55:58 +00:00
// Create a template registry and register the safeHTML function
funcMap := template.FuncMap{
2025-03-21 22:21:00 +00:00
"safeHTML": func(s string) template.HTML {
return template.HTML(s)
},
2025-04-04 21:55:58 +00:00
}
tmpl := template.New("").Funcs(funcMap)
2025-03-21 22:21:00 +00:00
2025-03-21 22:08:47 +00:00
// Load HTML templates
2025-04-04 21:55:58 +00:00
tmpl, err = tmpl.ParseGlob("templates/*")
if err != nil {
log.Fatalf("Failed to load HTML templates: %v", err)
}
2025-03-21 22:08:47 +00:00
// Serve static files (CSS)
2025-04-04 21:55:58 +00:00
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
2025-03-21 22:08:47 +00:00
2025-03-21 22:21:00 +00:00
// Initialize API handlers
2025-04-04 21:55:58 +00:00
apiHandler := api.NewAPIHandler(database, tmpl) // Pass the loaded templates
2025-03-21 21:22:38 +00:00
// Define API routes
2025-04-04 21:55:58 +00:00
apiGroup := router.PathPrefix("/nombres").Subrouter()
apiGroup.HandleFunc("/search", apiHandler.SearchNombres).Methods("GET")
apiGroup.HandleFunc("", apiHandler.CreateNombre).Methods("POST")
apiGroup.HandleFunc("", apiHandler.GetNombres).Methods("GET")
apiGroup.HandleFunc("/{id}", apiHandler.GetNombreByID).Methods("GET")
apiGroup.HandleFunc("/{id}", apiHandler.UpdateNombre).Methods("PUT")
apiGroup.HandleFunc("/{id}", apiHandler.DeleteNombre).Methods("DELETE")
apiGroup.HandleFunc("/html/edit/{id}", apiHandler.EditNombreHTML).Methods("GET")
apiGroup.HandleFunc("/html/update/{id}", apiHandler.UpdateNombreHTML).Methods("POST")
2025-03-21 21:22:38 +00:00
2025-03-21 22:21:00 +00:00
// HTML Routes
2025-04-04 21:55:58 +00:00
router.HandleFunc("/", apiHandler.GetIndexPlantsHTML).Methods("GET")
router.HandleFunc("/nombres/html", apiHandler.GetNombresHTML).Methods("GET")
router.HandleFunc("/nombres/html/{id}", apiHandler.GetNombreByIDHTML).Methods("GET")
2025-03-21 22:08:47 +00:00
2025-03-21 21:22:38 +00:00
// Start the server
2025-04-04 21:55:58 +00:00
log.Println("Server started on :8080")
if err := http.ListenAndServe(":8080", router); err != nil {
2025-03-21 21:22:38 +00:00
log.Fatalf("Failed to start server: %v", err)
}
}