# Gin 框架使用 + [官方文档](https://gin-gonic.com/zh-cn/docs/) ```go package main import ( "log" "net/http" "github.com/gin-gonic/gin" ) func main() { // gin Engine, 它包装了http server server := gin.Default() // 配置业务路有 server.GET("/hello", func(ctx *gin.Context) { // url query ?name=test // header authentiaction: bearer token // body // 1. 读取URL路径参数: /hello/:name // ctx: http Request/Respose, /hello/tony // name := ctx.Param("name") // 2. 从URL ? query string 读取用户的参数 // /books?page_size=10&page_number=20 // ps := ctx.Query("page_size") // pn := ctx.Query("page_number") // 3. 从Header中读取用户参数 // 典型场景: 接口认证 // Authenticaton: Bearer xxxxxxx // ctx.GetHeader("Authenticaton") // ctx.Request.Header.Get("Authenticaton") // 4. 从body中读取参数 // 用于数据的创建,往数据库里添加一条数据,比如 Create Book // {"name": "Go语言项目", "author": "老喻"} // JSON ----> Struct{} book := new(Book) // body, _ := io.ReadAll(ctx.Request.Body) // defer ctx.Request.Body.Close() // if string(body) == "" { // ctx.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "请传达JSON格式的参数"}) // return // } // json.Unmarshal(body, book) // if err := ctx.BindJSON(book); err != nil { // ctx.JSON(http.StatusBadRequest, gin.H{"code": 0, "msg": err.Error()}) // return // } // 业务出来 // db.save(db) // json.Marshal(book) ctx.JSON(http.StatusOK, book) }) if err := server.Run("127.0.0.1:8080"); err != nil { log.Println(err) } } type Book struct { Name string `json:"name"` Author string `json:"author"` } ``` ```sh [GIN-debug] POST /api/books --> main.main.func1 (3 handlers) [GIN-debug] GET /api/books --> main.main.func2 (3 handlers) [GIN-debug] GET /api/books/:isbn --> main.main.func3 (3 handlers) [GIN-debug] PUT /api/books/:isbn --> main.main.func4 (3 handlers) [GIN-debug] DELETE /api/books/:isbn --> main.main.func5 (3 handlers) ``` ## 如何测试 创建书籍: ```sh curl -X POST http://localhost:8080/api/books -H "Content-Type: application/json" -d '{"title": "Go 语言", "author": "张三", "price": 39.99}' ``` 获取所有书籍: ```sh curl http://localhost:8080/api/books ``` 根据 ID 获取书籍: ```sh curl http://localhost:8080/api/books/1 ``` 更新书籍: ```sh curl -X PUT http://localhost:8080/api/books/1 -H "Content-Type: application/json" -d '{"price": 49.99}' ``` 删除书籍: ```sh curl -X DELETE http://localhost:8080/api/books/1 ``` 这样就完成了一个简单的使用 MySQL 的 Book CRUD 示例。你可以根据需要进一步扩展功能。