package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
/*
* gin简单模拟图书请求
*
*
*/
/// @dev 书本数据
/// json端传输的id标识为全小写,进行绑定
type Book struct {
ID string `json:"id"`
Title string `json:"title"`
Author string `json:"author"`
}
/// @dev 书本的切片,也就是可变数组
/// @dev 初始化了三本书籍
var books = []Book{
{ID: "1", Title: "Harry Potter", Author: "J. K. Rowling"},
{ID: "2", Title: "The Lord of the Rings", Author: "J. R. R. Tolkien"},
{ID: "3", Title: "The Wizard of Oz", Author: "L. Frank Baum"},
}
func main() {
//默认启动Gin框架
r := gin.Default()
r.GET("/books", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, books)
})
r.POST("/books", func(ctx *gin.Context) {
//声明book的副本,变量名为book
var book Book
if err := ctx.ShouldBindJSON(&book); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
//添加进去
books = append(books, book)
ctx.JSON(http.StatusCreated, book)
})
r.Run(":8080")
}