Go框架三件套基本使用|青训营笔记

236 阅读3分钟

Gorm基础使用

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

1. Gorm的基本使用

1.1 Gorm的约定

  • gorm使用名为id的字段作为主键
  • 使用结构体的蛇形负数作为表名
  • 字段名的蛇形作为列名
  • 使用CreateAt、UpdateAt字段作为创建、更新时间

1.2使用gorm操作数据库

  • 连接数据库
    dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    
  • 创建数据
    user := User{Name: "Jinzhu", Age: 18, Birthday: time.Now()}  
    result := db.Create(&user) // pass pointer of data to Create
    
  • 查询数据
    // Get the first record ordered by primary key 
    db.First(&user) 
    // SELECT * FROM users ORDER BY id LIMIT 1;  
    // Get one record, no specified order 
    db.Take(&user) 
    // SELECT * FROM users LIMIT 1;  
    // Get last record, order by primary key desc 
    db.Last(&user) 
    // SELECT * FROM users ORDER BY id DESC LIMIT 1;
    
  • 更新数据
    db.First(&user)  
    user.Name = "jinzhu 2" 
    user.Age = 100 db.Save(&user) 
    // UPDATE users SET name='jinzhu 2', age=100, birthday='2016-01-01', updated_at = '2013-11-17 21:34:10' WHERE id=111; 
    
  • 删除数据
    // Email's ID is `10` 
    db.Delete(&email) 
    // DELETE from emails where id = 10;  
    // Delete with additional conditions 
    db.Where("name = ?", "jinzhu").Delete(&email) 
    // DELETE from emails where id = 10 AND name = "jinzhu"; 
    
  • Gorm事务
    • gorm提供了Begin、Commit、Rollback方法用于使用事务
    tx := db.Begin()
    tx.Create(...)
    //rollback the transaction in case of error
    tx.Rollback()
    // or commit the transaction
    tx.Commit()
    
    • gorm提供transaction方法用于自动提交事务,避免用户漏写Commit、Rollback。
    db.Transaction(func(tx *gorm.DB) error {   
    // do some database operations in the transaction (use 'tx' from this point, not 'db')   
        if err := tx.Create(&Animal{Name: "Giraffe"}).Error; err != nil {    
            // return any error will rollback     
            return err   
        }    
        if err := tx.Create(&Animal{Name: "Lion"}).Error; err != nil {     
            return err   
        }    
        // return nil will commit the whole transaction   
        return nil 
    })
    
  • Gorm Hook
    • gorm提供了CURD的Hook能力。
    • Hook是在创建、查询、更新、删除等操作之前、之后自动调用的函数。
    • 如果任何hook返回错误,gorm将停止后续操作。
    // begin transaction  
    BeforeSave  
    BeforeCreate  
    // save before associations  
    // insert into database  
    // save after associations  
    AfterCreate  
    AfterSave  
    // commit or rollback transaction
    

Kitex基础使用

1. Kitex生成代码

  • 使用kitex -module example -service example echo.thrift 命令生成代码 截屏2023-01-18 15.47.31.png
    • build.sh: 构建脚本
    • kitex_gen :IDL内容相关的生成代码,主要是基础的Server/Client代码
    • main.go程序入口
    • handle.go用户在该文件里实现IDL service定义的方法

2. Kitex基本使用

  • 服务默认监听8888端口 截屏2023-01-18 16.06.47.png

3.Kitex Client 发起请求

  • 创建Client 截屏2023-01-18 16.07.56.png
  • 发起请求 截屏2023-01-18 16.08.43.png

4. Kitex服务注册与发现

截屏2023-01-18 16.09.19.png

Kitex生态

  • Kitex拥有非常丰富的扩展生态,以下列举一部分常用扩展 截屏2023-01-18 16.11.10.png

Hertz

1. Hertz的基本使用

  • 使用Hertz实现,服务监听8080端口并注册一个GET方法的路由函数 截屏2023-01-18 18.09.11.png

2. Hertz路由

  • Hertz提供了GET、POST、PUT、DELETE、ANY等方法用于注册路由。 截屏2023-01-18 18.14.28.png
  • Hertz提供了路由组(Group)的能力,用于支持路由分组的功能。 截屏2023-01-18 18.15.46.png
  • Hertz提供了参数和通配路由,路由的优先级:静态路由 > 命名路由 > 通配路由 截屏2023-01-18 18.17.25.png

3. Hertz参数绑定

  • Hertz提供了Bind、Validate、BindAndValidate、函数用于进行参数绑定 截屏2023-01-18 18.19.00.png

4. Hertz中间件

  • Hertz的中间件主要分为客户端中间件与服务端中间件,如下展示一个服务端中间件 截屏2023-01-18 18.20.58.png

5. Hertz Client

  • Hertz提供了HTTP Client用于帮助用户发送HTTP请求 截屏2023-01-18 18.22.59.png