1. package main
    2. import (
    3. "net/http"
    4. "github.com/gin-gonic/gin"
    5. )
    6. /*
    7. * gin简单模拟图书请求
    8. *
    9. *
    10. */
    11. /// @dev 书本数据
    12. /// json端传输的id标识为全小写,进行绑定
    13. type Book struct {
    14. ID string `json:"id"`
    15. Title string `json:"title"`
    16. Author string `json:"author"`
    17. }
    18. /// @dev 书本的切片,也就是可变数组
    19. /// @dev 初始化了三本书籍
    20. var books = []Book{
    21. {ID: "1", Title: "Harry Potter", Author: "J. K. Rowling"},
    22. {ID: "2", Title: "The Lord of the Rings", Author: "J. R. R. Tolkien"},
    23. {ID: "3", Title: "The Wizard of Oz", Author: "L. Frank Baum"},
    24. }
    25. func main() {
    26. //默认启动Gin框架
    27. r := gin.Default()
    28. r.GET("/books", func(ctx *gin.Context) {
    29. ctx.JSON(http.StatusOK, books)
    30. })
    31. r.POST("/books", func(ctx *gin.Context) {
    32. //声明book的副本,变量名为book
    33. var book Book
    34. if err := ctx.ShouldBindJSON(&book); err != nil {
    35. ctx.JSON(http.StatusBadRequest, gin.H{
    36. "error": err.Error(),
    37. })
    38. return
    39. }
    40. //添加进去
    41. books = append(books, book)
    42. ctx.JSON(http.StatusCreated, book)
    43. })
    44. r.Run(":8080")
    45. }