154 lines
3.4 KiB
Go
154 lines
3.4 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/gin-contrib/cors"
|
|
"github.com/gin-gonic/gin"
|
|
"gopkg.in/yaml.v3"
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/gorm"
|
|
"log"
|
|
"os"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
// Config 结构体用于读取YAML配置文件
|
|
type Config struct {
|
|
Debug bool `yaml:"debug"`
|
|
Web string `yaml:"web"`
|
|
Database struct {
|
|
User string `yaml:"user"`
|
|
Password string `yaml:"password"`
|
|
Host string `yaml:"host"`
|
|
Port int `yaml:"port"`
|
|
DBName string `yaml:"dbname"`
|
|
} `yaml:"database"`
|
|
}
|
|
|
|
type Wlzb struct {
|
|
ID int `json:"id" gorm:"primaryKey"`
|
|
PostID string `json:"post_id" gorm:"primaryKey"`
|
|
CreateTime time.Time `json:"create_time"`
|
|
Author string `json:"author"`
|
|
PostMessage string `json:"post_message" gorm:"column:post_massage"`
|
|
}
|
|
|
|
func (Wlzb) TableName() string {
|
|
return "wlzb"
|
|
}
|
|
|
|
// LoadConfig 读取YAML配置文件
|
|
func LoadConfig(filePath string) (*Config, error) {
|
|
file, err := os.ReadFile(filePath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var config Config
|
|
err = yaml.Unmarshal(file, &config)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &config, nil
|
|
}
|
|
|
|
func main() {
|
|
// 读取配置文件
|
|
config, err := LoadConfig("config/config.yaml")
|
|
if err != nil {
|
|
log.Fatalf("Error loading config file: %v", err)
|
|
}
|
|
|
|
r := gin.Default()
|
|
|
|
// 自定义 CORS 中间件配置
|
|
CORSconfig := cors.DefaultConfig()
|
|
if config.Debug {
|
|
// 允许所有来源
|
|
CORSconfig.AllowAllOrigins = true
|
|
} else {
|
|
CORSconfig.AllowOrigins = []string{fmt.Sprintf("%s", config.Web),
|
|
fmt.Sprintf("http://localhost:5197")} // 允许的前端源
|
|
}
|
|
CORSconfig.AllowMethods = []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}
|
|
CORSconfig.AllowHeaders = []string{"Origin", "Content-Length", "Content-Type", "Authorization"}
|
|
CORSconfig.AllowCredentials = true
|
|
|
|
r.Use(cors.New(CORSconfig))
|
|
|
|
// 数据库连接
|
|
// 构建DSN
|
|
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
|
config.Database.User,
|
|
config.Database.Password,
|
|
config.Database.Host,
|
|
config.Database.Port,
|
|
config.Database.DBName,
|
|
)
|
|
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
|
if err != nil {
|
|
panic("failed to connect database")
|
|
}
|
|
|
|
r.GET("/api/posts", func(c *gin.Context) {
|
|
var posts []Wlzb
|
|
pageStr := c.DefaultQuery("page", "1")
|
|
limitStr := c.DefaultQuery("limit", "10")
|
|
|
|
page, err := strconv.Atoi(pageStr)
|
|
if err != nil {
|
|
c.JSON(400, gin.H{"error": "Invalid page number"})
|
|
return
|
|
}
|
|
|
|
limit, err := strconv.Atoi(limitStr)
|
|
if err != nil {
|
|
c.JSON(400, gin.H{"error": "Invalid limit number"})
|
|
return
|
|
}
|
|
|
|
// 额外的检查
|
|
if page < 1 {
|
|
page = 1
|
|
}
|
|
|
|
if limit < 1 || limit > 100 {
|
|
limit = 10
|
|
}
|
|
|
|
offset := (page - 1) * limit
|
|
|
|
result := db.Order("id DESC").Limit(limit).Offset(offset).Find(&posts)
|
|
if result.Error != nil {
|
|
c.JSON(500, gin.H{"error": result.Error.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(200, posts)
|
|
})
|
|
|
|
// 新增的 API 路由,根据 ID 查询单个条目
|
|
r.GET("/api/post/:id", func(c *gin.Context) {
|
|
id, err := strconv.Atoi(c.Param("id"))
|
|
if err != nil {
|
|
c.JSON(400, gin.H{"error": "Invalid ID"})
|
|
return
|
|
}
|
|
|
|
var post Wlzb
|
|
result := db.First(&post, id)
|
|
if result.Error != nil {
|
|
if result.Error == gorm.ErrRecordNotFound {
|
|
c.JSON(404, gin.H{"error": "Post not found"})
|
|
} else {
|
|
c.JSON(500, gin.H{"error": result.Error.Error()})
|
|
}
|
|
return
|
|
}
|
|
|
|
c.JSON(200, post)
|
|
})
|
|
|
|
r.Run(":8080")
|
|
}
|