Files
OwOrganizer/backend/main.go
T
2026-07-16 19:24:39 -07:00

65 lines
1.7 KiB
Go

package main
import (
"log"
"net/http"
"os"
"strings"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
db, err := InitDB()
if err != nil {
log.Fatalf("failed to initialize database: %v", err)
}
DB = db
router := gin.Default()
// Configure CORS. In production, set CORS_ALLOWED_ORIGINS to your public domain.
allowedOrigins := []string{"http://localhost:5173"}
if envOrigins := os.Getenv("CORS_ALLOWED_ORIGINS"); envOrigins != "" {
allowedOrigins = strings.Split(envOrigins, ",")
}
router.Use(cors.New(cors.Config{
AllowOrigins: allowedOrigins,
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
MaxAge: 12 * 60 * 60,
}))
router.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
router.GET("/db-check", func(c *gin.Context) {
if err := DB.Ping(); err != nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"status": "unreachable", "error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
// User routes
router.POST("/users", createUserHandler)
router.GET("/users/:id", getUserHandler)
router.PUT("/users/:id", updateUserHandler)
router.DELETE("/users/:id", deleteUserHandler)
// Object routes
router.POST("/objects", createObjectHandler)
router.GET("/objects/:id", getObjectHandler)
router.GET("/users/:id/objects", getObjectsByUserHandler)
router.PUT("/objects/:id", updateObjectHandler)
router.DELETE("/objects/:id", deleteObjectHandler)
router.Run() // listens on 0.0.0.0:8080 by default
}