go语言图书管理系统
时间: 2023-11-30 07:43:22 浏览: 54
以下是一个简单的Go语言图书管理系统的实现,包括添加图书、删除图书、查询图书和展示所有图书的功能。其中使用了Gin框架和GORM库。
```go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Book struct {
ID uint `json:"id" gorm:"primaryKey"`
Title string `json:"title"`
Author string `json:"author"`
}
func main() {
// 连接数据库
dsn := "root:password@tcp(127.0.0.1:3306)/library?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// 自动迁移模式
db.AutoMigrate(&Book{})
// 创建路由
router := gin.Default()
// 添加图书
router.POST("/books", func(c *gin.Context) {
var book Book
if err := c.ShouldBindJSON(&book); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
db.Create(&book)
c.JSON(http.StatusOK, gin.H{"data": book})
})
// 删除图书
router.DELETE("/books/:id", func(c *gin.Context) {
var book Book
if err := db.Where("id = ?", c.Param("id")).First(&book).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
return
}
db.Delete(&book)
c.JSON(http.StatusOK, gin.H{"data": true})
})
// 查询图书
router.GET("/books/:id", func(c *gin.Context) {
var book Book
if err := db.Where("id = ?", c.Param("id")).First(&book).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
return
}
c.JSON(http.StatusOK, gin.H{"data": book})
})
// 展示所有图书
router.GET("/books", func(c *gin.Context) {
var books []Book
db.Find(&books)
c.JSON(http.StatusOK, gin.H{"data": books})
})
// 运行服务器
router.Run(":8080")
}
```