go17/skills/gin/main.go

58 lines
1.4 KiB
Go
Raw Normal View History

2024-11-16 12:11:19 +08:00
package main
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
// gin Engine, 它包装了http server
server := gin.Default()
// 配置业务路有
server.GET("/hello/:name", func(ctx *gin.Context) {
// url query ?name=test
// header authentiaction: bearer token
// body
// 1. 读取URL路径参数
// 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()
// json.Unmarshal(body, book)
if err := ctx.ShouldBindJSON(book); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"code": 0, "msg": err})
return
}
// 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"`
}