Gorm、Hertz | 青训营笔记

88 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 5 天

Gorm

DSN

Data Source Name (DSN)的PDO命名惯例为:PDO驱动程序的名称,后面为一个冒号,再后面是可选的驱动程序连接数据库变量信息,如主机名、端口和数据库名。

注意

  1. 使用First时,需要注意查询不到数据会返回ErrRecordNotFound
  2. 使用Find查询多条数据,查询不到数据不会返回错误
  1. 使用结构体做条件查询时,GORM只会查询非零值字段。这意味着如果你的字段为“0”、“false”或者其他零值,则不会作为查询条件。
  2. 使用Struct更新时,也和上面类似,不会更新零值,若需要更新零值,则需要使用Map更新或使用Select选择字段

Kitex

基于Linux内核的,那也太难受了吧。

Hertz

文档

Hertz | CloudWeGo

依赖

  github.com/cloudwego/hertz/cmd/hz@latest

入门案例

 package main
 ​
 import (
    "context"
 ​
    "github.com/cloudwego/hertz/pkg/app"
    "github.com/cloudwego/hertz/pkg/app/server"
    "github.com/cloudwego/hertz/pkg/common/utils"
    "github.com/cloudwego/hertz/pkg/protocol/consts"
 )
 ​
 func main() {
    h := server.Default()
 ​
    h.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
       ctx.JSON(consts.StatusOK, utils.H{"message": "pong"})
    })
 ​
    h.Spin()
 }

基本使用

分组

 v1 := h.Group("v1")
 {
    v1.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
       ctx.JSON(consts.StatusOK, utils.H{"message": "pong"})
    })
 }

通配路由

 h.GET("/ping/*action", func(c context.Context, ctx *app.RequestContext) {
    action := ctx.Param("action")
    fmt.Println("action", action) 
    ctx.JSON(consts.StatusOK, utils.H{"message": action})
 })

访问 http://localhost:8888/ping/v1/v2/v3

action的值会为v1/v2/v3

struct 类型指定

 package main
 ​
 import (
     "context"
     "fmt"
     "github.com/cloudwego/hertz/pkg/app"
     "github.com/cloudwego/hertz/pkg/app/server"
     "github.com/cloudwego/hertz/pkg/common/utils"
     "net/http"
 )
 ​
 type Args struct {
     Query  string `query:"query"`
     Path   string `path:"path"`
     Header string `header:"header"`
     Form   string `form:"form"`
     Json   string `json:"json"`
 }
 ​
 func main() {
     h := server.Default(server.WithHostPorts("localhost:8080"))
     h.POST("/test", func(c context.Context, ctx *app.RequestContext) {
         args := &Args{}
         req := ctx.BindAndValidate(&args)
         if req != nil {
             panic(req.Error())
         }
         fmt.Println(args)
         ctx.JSON(http.StatusOK, utils.H{
             "msg": args,
         })
     })
     h.Spin()
 }
 ​

中间件使用

若请求的链接的404,则,路由组的中间件不会走, 全局定义的中间件依然会走

 func MyMiddleware() app.HandlerFunc {
    return func(c context.Context, ctx *app.RequestContext) {
       fmt.Println("中间件之前的业务")
       ctx.Next(c)
       fmt.Println("中间件之后的业务")
    }
 }
 ​
 func main() {
    h := server.Default(server.WithHostPorts("localhost:8080"))
    h.Use(MyMiddleware())
    h.POST("/test", func(c context.Context, ctx *app.RequestContext) {
       ctx.JSON(http.StatusOK, utils.H{
          "msg": "ok",
       })
    })
    h.Spin()
 }

扩展

image.png

HZ

Hertz 提供了代码生成工具Hz

总结

Gorm对我来说属于之前早有了解与使用的。对于今天来说,主要是对于Kitex与Hertz是了解与使用。但是,Kitex确实基于Linux内核运行的,这对我来说也太难了吧,所以,暂时有点半放弃的情况。而对于Hertz,我感觉与Gin是差不多的呢,目前还没感觉出来太大的区别,学习使用起来也不是太难。