Java 太卷了转 GO(二)

上一篇文章简单的学习了 GO 的基础语法,本篇文章用 GO 的框架开发一个短链应用。

短链应用功能:

  1. 创建短链
  2. 根据短链 code 重定向到原始链接

主要用到的框架:

  1. ORM 框架 gorm
    https://gorm.io/zh_CN/docs/index.html
  2. Web 框架 gin
    https://gin-gonic.com/zh-cn/docs/

gin

最快的 http 路由器和框架。

package main

import "github.com/gin-gonic/gin"

func main() {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.Run() // 监听并在 0.0.0.0:8080 上启动服务
}

一个最简单的例子,启动后浏览器访问 http://localhost:8080/ping

使用路由:

func main() {
	engine := gin.Default()
	engine.Group("/")

	engine.GET("/ping", func(context *gin.Context) {
		context.JSON(200, gin.H{
			"message": "pong",
		})
	})
	engine.Run()
}

将接口放在程序入口 main 方法中不太合适,通常会创建多个 handler,类似于 java 中的 controller。

gorm

连接数据库

// 数据库连接:"用户名:密码@tcp(IP:端口)/数据库?charset=utf8"
sqlcon := "root:123456@tcp(127.0.0.1:3306)/amc?charset=utf8&parseTime=True&loc=Local"


DB, err := gorm.Open(mysql.Open(sqlcon), &gorm.Config{
	DisableForeignKeyConstraintWhenMigrating: true, //禁用物理外键
})
if err != nil {
	log.Fatal("连接失败!")
	return nil
}
// 连接池设置
sqlDB, err := DB.DB()
// 设置数据库最大连接数
sqlDB.SetMaxOpenConns(500)
// 设置数据库最大闲置数
sqlDB.SetMaxIdleConns(20)
// 全局禁用表名复数
//sqlDB.SingularTable(true)
// 调试模式,可以打印sql语句
//sqlDB.LogMode(true)

CRUD

insert

保存单条数据

createConfig := dao.ShortLinkConfig{
	Enable:      1,
	OriginUrl:   "http://localhost:8080",
	ShortCode:   "test",
	CreatedTime: time.Now(),
	UpdatedTime: time.Now(),
}
mysql.Db.Save(&createConfig)

保存多条数据

shortLinkConfigs := []dao.ShortLinkConfig{
	{
		Enable:      1,
		OriginUrl:   "http://localhost:8080",
		ShortCode:   "test1",
		CreatedTime: time.Now(),
		UpdatedTime: time.Now()},
	{
		Enable:      1,
		OriginUrl:   "http://localhost:8080",
		ShortCode:   "test2",
		CreatedTime: time.Now(),
		UpdatedTime: time.Now(),
	},
	{
		Enable:      1,
		OriginUrl:   "http://localhost:8080",
		ShortCode:   "test3",
		CreatedTime: time.Now(),
		UpdatedTime: time.Now(),
	},
}
// 批量数据一次性插入
//mysql.Db.Create(&shortLinkConfigs)
// 分批次插入
mysql.Db.CreateInBatches(&shortLinkConfigs, 1000)

select

config := dao.ShortLinkConfig{
	Enable: 1,
}

var shortLinkConfig = dao.ShortLinkConfig{}

//获取第一条记录,主键升序 select * from table ORDER BY id asc LIMIT 1
mysql.Db.Where(&config).First(&shortLinkConfig)
log.Printf("first config = %v", shortLinkConfig)

shortLinkConfig = dao.ShortLinkConfig{}
//获取最后一条记录,主键降序 select * from table ORDER BY id desc LIMIT 1
mysql.Db.Where(&config).Last(&shortLinkConfig)
log.Printf("last config = %v", shortLinkConfig)

shortLinkConfig = dao.ShortLinkConfig{}
// 获取一条记录,没有指定字段排序
mysql.Db.Where(&config).Take(&shortLinkConfig)
log.Printf("config = %v", shortLinkConfig)

shortLinkConfig = dao.ShortLinkConfig{}
mysql.Db.First(&shortLinkConfig, 9)
log.Printf("id = 9,config = %v", shortLinkConfig)

// 查询多条记录
shortLinkConfigs := make([]dao.ShortLinkConfig, 3)
mysql.Db.Find(&shortLinkConfigs, []int{8, 9, 10})
for i, linkConfig := range shortLinkConfigs {
	log.Printf("i = %d,config = %v", i, linkConfig)
}

// 指定字段查询
shortCode := "acegf"
shortLinkConfig = dao.ShortLinkConfig{}
mysql.Db.Where("short_code = ? and enable = 1", shortCode).First(&shortLinkConfig)
log.Printf("short_code = %s,config = %v", shortCode, shortLinkConfig)

// 指定字段查询 struct,这种方式要求 struct 中的字段不能为零值,0、false 这种是不会创建查询条件的。
shortLinkConfig = dao.ShortLinkConfig{}
mysql.Db.Where(&dao.ShortLinkConfig{ShortCode: shortCode, Enable: 0}).First(&shortLinkConfig)
log.Printf("short_code = %s,enable = 0,config = %v", shortCode, shortLinkConfig)

// 指定字段查询 map
shortLinkConfigs = make([]dao.ShortLinkConfig, 10)
mysql.Db.Where(map[string]interface{}{"enable": 1, "short_code": shortCode}).Find(&shortLinkConfigs)
for i, linkConfig := range shortLinkConfigs {
	log.Printf(" --- i = %d,config = %v", i, linkConfig)
}

update

Save

shortCode := "test3"
shortLinkConfig := dao.ShortLinkConfig{}
mysql.Db.Where("short_code = ? and enable = 1", shortCode).First(&shortLinkConfig)
log.Printf("short_code = %s,config = %v", shortCode, shortLinkConfig)

shortLinkConfig.ShortCode = "test5"
mysql.Db.Save(&shortLinkConfig)

Update 更新单个列

// update short_link_config set short_code = "123" where short_code = "test5" and enable = 1
mysql.Db.Model(&dao.ShortLinkConfig{}).Where("short_code = ? and enable = 1", shortCode).Update("short_code", "123")

更新多列,struct 方式,只会更新非零值

mysql.Db.Where(&dao.ShortLinkConfig{
	Enable: 1,
}).Updates(dao.ShortLinkConfig{
	Enable:    0,
	OriginUrl: "http://www.123.com",
})

更新多列,map 方式

mysql.Db.Model(&dao.ShortLinkConfig{}).Where(&dao.ShortLinkConfig{Enable: 1}).Updates(map[string]interface{}{"origin_url": "http://www.baidu.com"})

delete

根据主键删除

// delete from short_link_config where id = 10
mysql.Db.Delete(&dao.ShortLinkConfig{}, 10)

短链应用:
github: https://github.com/hitolz/shortLink

2022/09/09 09:43 上午 posted in  GO