Go语言用Gin实现图书管理接口的实现示例

作者:

文章目录
  • 我们要实现以下接口: 1. 获取所有图书 GET /books 2. 根据ID获取图书 GET /books/:id 3. 添加图书 POST /books 4. 更新图书 PUT /books/:id 5. 删除图书 DELETE /books/:id
  • 确保你已安装 Go 1.18+ 和 Gin: go get -u github.com/gin-gonic/gin
  • package main import ( “github.com/gin-gonic/gin” “net/http” “strconv” ) // 图书结构体 type Book struct { ID int `json:”id”` Title string `json:”title”` Author string `json:”author”` } var books = []Book{ {ID: 1, Title: “Go语言实战”, Author: “张三”}, {ID: 2, Title: “Gin框架入门”, Author: “李四”}, } // 获取所有图书 func getBooks(c *gin.Context) { c.JSON(http.StatusOK, books) } // 根据ID获取图书 func getBookByID(c *gin.Context) { idStr := c.Param(“id”) id, _ := strconv.Atoi(idStr) for _, book := range books { if book.ID == id { c.JSON(http.StatusOK, book) return } } c.JSON(http.StatusNotFound, gin.H{“error”: “图书不存在”}) } // 添加图书 func addBook(c *gin.Context) { var newBook Book if err := c.ShouldBindJSON(&newBook); err != nil { c.JSON(http.StatusBadRequest, gin.H{“error”: err.Error()}) return } // 模拟自增ID newBook.ID = len(books) + 1 books = append(books, newBook) c.JSON(http.StatusCreated, newBook) } // 更新图书 func updateBook(c *gin.Context) { idStr := c.Param(“id”) id, _ := strconv.Atoi(idStr) var updateData Book if err := c.ShouldBindJSON(&updateData); err != nil { c.JSON(http.StatusBadRequest, gin.H{“error”: err.Error()}) return } for i, book := range books { if book.ID == id { books[i].Title = updateData.Title books[i].Author = updateData.Author c.JSON(http.StatusOK, books[i]) return } } c.JSON(http.StatusNotFound, gin.H{“error”: “图书不存在”}) } // 删除图书 func deleteBook(c *gin.Context) { idStr := c.Param(“id”) id, _ := strconv.Atoi(idStr) for i, book := range books { if book.ID == id { books = append(books[:i], books[i+1:]…) c.JSON(http.StatusOK, gin.H{“message”: “删除成功”}) return } } c.JSON(http.StatusNotFound, gin.H{“error”: “图书不存在”}) } func main() { r := gin.Default() r.GET(“/books”, getBooks) r.GET(“/books/:id”, getBookByID) r.POST(“/books”, addBook) r.PUT(“/books/:id”, updateBook) r.DELETE(“/books/:id”, deleteBook) r.Run(“:8080”) }
  • 运行服务: go run main.go
  • • 使用 Gin 可以非常轻松地构建 RESTful API • 路由映射到不同的处理函数 • JSON 参数解析只需 ShouldBindJSON • 后续可以把 books 切片替换为数据库(MySQL、PostgreSQL、MongoDB等) 到此这篇关于Go语言用Gin实现图书管理接口的实现示例的文章就介绍到这了,更多相关Gin 图书管理接口内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!  您可能感兴趣的文章: 使用Golang采集Nginx接口流量大小的步骤 go基于Gin框架的HTTP接口限速实践 Go Ginrest实现一个RESTful接口 GO语言gin框架实现管理员认证登陆接口
  • 目录
    • 一、功能目标
    • 二、项目初始化
    • 三、代码实现
    • 四、运行与测试
      • 1. 获取所有图书
      • 2. 获取单本图书
      • 3. 添加图书
      • 4. 更新图书
      • 5. 删除图书
    • 五、总结

      在 Web API 开发中,最常见的场景之一就是构建 增删改查(CRUD)  接口。
      本篇我们将用 Gin 框架 来实现一个简单的图书管理系统 API,数据会存储在内存中(方便演示),但结构设计可方便以后替换为数据库。

      我们要实现以下接口:

      1. 1. 获取所有图书 GET /books
      2. 2. 根据ID获取图书 GET /books/:id
      3. 3. 添加图书 POST /books
      4. 4. 更新图书 PUT /books/:id
      5. 5. 删除图书 DELETE /books/:id

      确保你已安装 Go 1.18+ 和 Gin:

      go get -u github.com/gin-gonic/gin
      

      package main
      
      import (
          "github.com/gin-gonic/gin"
          "net/http"
          "strconv"
      )
      
      // 图书结构体
      type Book struct {
          ID     int    `json:"id"`
          Title  string `json:"title"`
          Author string `json:"author"`
      }
      
      var books = []Book{
          {ID: 1, Title: "Go语言实战", Author: "张三"},
          {ID: 2, Title: "Gin框架入门", Author: "李四"},
      }
      
      // 获取所有图书
      func getBooks(c *gin.Context) {
          c.JSON(http.StatusOK, books)
      }
      
      // 根据ID获取图书
      func getBookByID(c *gin.Context) {
          idStr := c.Param("id")
          id, _ := strconv.Atoi(idStr)
      
          for _, book := range books {
              if book.ID == id {
                  c.JSON(http.StatusOK, book)
                  return
              }
          }
          c.JSON(http.StatusNotFound, gin.H{"error": "图书不存在"})
      }
      
      // 添加图书
      func addBook(c *gin.Context) {
          var newBook Book
          if err := c.ShouldBindJSON(&newBook); err != nil {
              c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
              return
          }
      
          // 模拟自增ID
          newBook.ID = len(books) + 1
          books = append(books, newBook)
      
          c.JSON(http.StatusCreated, newBook)
      }
      
      // 更新图书
      func updateBook(c *gin.Context) {
          idStr := c.Param("id")
          id, _ := strconv.Atoi(idStr)
      
          var updateData Book
          if err := c.ShouldBindJSON(&updateData); err != nil {
              c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
              return
          }
      
          for i, book := range books {
              if book.ID == id {
                  books[i].Title = updateData.Title
                  books[i].Author = updateData.Author
                  c.JSON(http.StatusOK, books[i])
                  return
              }
          }
          c.JSON(http.StatusNotFound, gin.H{"error": "图书不存在"})
      }
      
      // 删除图书
      func deleteBook(c *gin.Context) {
          idStr := c.Param("id")
          id, _ := strconv.Atoi(idStr)
      
          for i, book := range books {
              if book.ID == id {
                  books = append(books[:i], books[i+1:]...)
                  c.JSON(http.StatusOK, gin.H{"message": "删除成功"})
                  return
              }
          }
          c.JSON(http.StatusNotFound, gin.H{"error": "图书不存在"})
      }
      
      func main() {
          r := gin.Default()
      
          r.GET("/books", getBooks)
          r.GET("/books/:id", getBookByID)
          r.POST("/books", addBook)
          r.PUT("/books/:id", updateBook)
          r.DELETE("/books/:id", deleteBook)
      
          r.Run(":8080")
      }
      

      运行服务:

      go run main.go
      

      curl http://localhost:8080/books
      

      curl http://localhost:8080/books/1
      

      curl -X POST http://localhost:8080/books 
        -H "Content-Type: application/json" 
        -d '{"title":"Go Web编程","author":"王五"}'
      

      curl -X PUT http://localhost:8080/books/1 
        -H "Content-Type: application/json" 
        -d '{"title":"Go语言进阶","author":"张三改"}'
      

      curl -X DELETE http://localhost:8080/books/2
      

      • • 使用 Gin 可以非常轻松地构建 RESTful API
      • • 路由映射到不同的处理函数
      • • JSON 参数解析只需 ShouldBindJSON
      • • 后续可以把 books 切片替换为数据库(MySQL、PostgreSQL、MongoDB等)

      到此这篇关于Go语言用Gin实现图书管理接口的实现示例的文章就介绍到这了,更多相关Gin 图书管理接口内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 

      您可能感兴趣的文章:

      • 使用Golang采集Nginx接口流量大小的步骤
      • go基于Gin框架的HTTP接口限速实践
      • Go Ginrest实现一个RESTful接口
      • GO语言gin框架实现管理员认证登陆接口

      站内搜索