58 lines
1.6 KiB
Go
58 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-contrib/cors"
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"mengyastore-backend/internal/config"
|
|
"mengyastore-backend/internal/handlers"
|
|
"mengyastore-backend/internal/storage"
|
|
)
|
|
|
|
func main() {
|
|
cfg, err := config.Load("data/json/settings.json")
|
|
if err != nil {
|
|
log.Fatalf("load config failed: %v", err)
|
|
}
|
|
|
|
store, err := storage.NewJSONStore("data/json/products.json")
|
|
if err != nil {
|
|
log.Fatalf("init store failed: %v", err)
|
|
}
|
|
|
|
r := gin.Default()
|
|
r.Use(cors.New(cors.Config{
|
|
AllowOrigins: []string{"*"},
|
|
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
|
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"},
|
|
ExposeHeaders: []string{"Content-Length"},
|
|
AllowCredentials: false,
|
|
MaxAge: 12 * time.Hour,
|
|
}))
|
|
|
|
r.GET("/api/health", func(c *gin.Context) {
|
|
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
|
})
|
|
|
|
publicHandler := handlers.NewPublicHandler(store)
|
|
adminHandler := handlers.NewAdminHandler(store, cfg)
|
|
|
|
r.GET("/api/products", publicHandler.ListProducts)
|
|
|
|
r.GET("/api/admin/token", adminHandler.GetAdminToken)
|
|
r.GET("/api/admin/products", adminHandler.ListAllProducts)
|
|
r.POST("/api/admin/products", adminHandler.CreateProduct)
|
|
r.PUT("/api/admin/products/:id", adminHandler.UpdateProduct)
|
|
r.PATCH("/api/admin/products/:id/status", adminHandler.ToggleProduct)
|
|
r.DELETE("/api/admin/products/:id", adminHandler.DeleteProduct)
|
|
|
|
log.Println("萌芽小店后端启动于 http://localhost:8080")
|
|
if err := r.Run(":8080"); err != nil {
|
|
log.Fatalf("server run failed: %v", err)
|
|
}
|
|
}
|