Files
counter/main.go
aovantsev 324e861218
Some checks failed
continuous-integration/drone/pr Build is failing
continuous-integration/drone/push Build is passing
basic frontend
2025-10-03 11:32:59 +03:00

94 lines
2.2 KiB
Go

package main
import (
"log"
"os"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
)
func main() {
// Load environment variables
if err := godotenv.Load(); err != nil {
log.Println("No .env file found, using system environment variables")
}
// Initialize JWT
InitJWT()
// Initialize database
if err := InitDB(); err != nil {
log.Fatal("Failed to initialize database:", err)
}
// Create tables
if err := CreateTables(); err != nil {
log.Fatal("Failed to create tables:", err)
}
// Set Gin mode
if os.Getenv("GIN_MODE") == "release" {
gin.SetMode(gin.ReleaseMode)
}
// Create Gin router
r := gin.Default()
// Configure CORS
config := cors.DefaultConfig()
config.AllowOrigins = []string{"http://localhost:3000", "http://localhost:5173"} // React dev servers
config.AllowMethods = []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}
config.AllowHeaders = []string{"Origin", "Content-Type", "Accept", "Authorization"}
config.AllowCredentials = true
r.Use(cors.New(config))
// Health check endpoint
r.GET("/health", func(c *gin.Context) {
c.JSON(200, gin.H{"status": "ok"})
})
// API routes
api := r.Group("/api/v1")
{
// Authentication routes
auth := api.Group("/auth")
{
auth.POST("/register", RegisterHandler)
auth.POST("/login", LoginHandler)
auth.GET("/me", AuthMiddleware(), GetCurrentUserHandler)
}
// Counter routes (protected)
counters := api.Group("/counters")
counters.Use(AuthMiddleware())
{
counters.POST("", CreateCounterHandler)
counters.GET("", GetCountersHandler)
counters.GET("/:id", GetCounterHandler)
counters.PUT("/:id", UpdateCounterHandler)
counters.DELETE("/:id", DeleteCounterHandler)
counters.POST("/:id/increment", IncrementCounterHandler)
counters.GET("/:id/entries", GetCounterEntriesHandler)
counters.GET("/:id/stats", GetCounterStatsHandler)
}
}
// Serve static files (React app)
r.Static("/static", "./frontend/build/static")
r.StaticFile("/", "./frontend/build/index.html")
r.NoRoute(func(c *gin.Context) {
c.File("./frontend/build/index.html")
})
// Start server
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Printf("Server starting on port %s", port)
log.Fatal(r.Run(":" + port))
}