package main
import (
"github.com/gin-gonic/gin"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"net/http"
)
type User struct {
ID uint `json:"id" gorm:"primaryKey"`
Name string `json:"name"`
Email string `json:"email"`
}
func setupDatabase() *gorm.DB {
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
db.AutoMigrate(&User{})
return db
}
func createUser(c *gin.Context) {
db := setupDatabase()
var user User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
db.Create(&user)
c.JSON(http.StatusOK, user)
}
func getUsers(c *gin.Context) {
db := setupDatabase()
var users []User
db.Find(&users)
c.JSON(http.StatusOK, users)
}
func getUserByID(c *gin.Context) {
db := setupDatabase()
id := c.Param("id")
var user User
if err := db.First(&user, id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "用户未找到"})
return
}
c.JSON(http.StatusOK, user)
}
func updateUser(c *gin.Context) {
db := setupDatabase()
var user User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := db.Where("id = ?", user.ID).Updates(user).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "更新失败: " + err.Error()})
return
}
c.JSON(http.StatusOK, user)
}
func updateEmail(c *gin.Context) {
db := setupDatabase()
id := c.Param("id")
DefaultEmail := "www.example.com"
updateData := struct {
Email *string `json:"email"`
}{
Email: &DefaultEmail,
}
if err := db.Model(&User{}).Where("id = ?", id).Updates(updateData).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "更新失败: " + err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "用户 email 已设置为指定Email"})
}
func deleteUser(c *gin.Context) {
db := setupDatabase()
id := c.Param("id")
if err := db.Delete(&User{}, id).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "删除失败: " + err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "用户已删除"})
}
func main() {
r := gin.Default()
r.POST("/users", createUser)
r.GET("/users", getUsers)
r.PUT("/users", updateUser)
r.DELETE("/users/:id", deleteUser)
r.GET("/users/:id", getUserByID)
r.PUT("/users/:id", updateEmail)
r.Run(":9080")
}