Golang开发效率是杠杠滴,简单几行代码就可完成一个可用的服务,如下代码:
- 采用Gin作为web framework
- 采用Gorm作为持久化ORM
- 采用Swagger作为OpenAPI文档管理工具
package mainimport ("encoding/csv""fmt""os""strconv""time"_ "export/docs""github.com/gin-gonic/gin"swaggerFiles "github.com/swaggo/files"ginSwagger "github.com/swaggo/gin-swagger""gorm.io/driver/mysql""gorm.io/gorm"
)type Detail struct {Id intName stringFirstTime time.TimeLastTime time.Time
}// @title NeoApi Swagger 标题
// @version 1.0 版本
// @description NeoApi Service 描述
// @BasePath /api 基础路径
// @query.collection.format multi
func main() {r := gin.Default()r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))r.GET("/api/export", export)r.POST("/api/data", func(c *gin.Context) {c.JSON(200, gin.H{"message": "success",})})r.Run("0.0.0.0:9527")
}// @Summary 导出数据
// @Description 导出数据
// @Accept json
// @Produce json
// @Success 200 string string "success"
// @Router /api/export [get]
func export(c *gin.Context) {dsn := "dev:123456@tcp(192.168.1.203:33306)/menshen?charset=utf8mb4&parseTime=true"db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})if err != nil {panic("failed to connect database")}var persons []uintdb.Raw("select id from person").Scan(&persons)fmt.Println(persons)month := 3monthFile := "08.csv"csvfile, err := os.Create(monthFile)if err != nil {fmt.Println("Error:", err)return}defer csvfile.Close()for _, id := range persons {var data []Detail// 注意 Gorm 字段映射默认严格驼峰命名,否则取不到值db.Raw(`select s.person_id as id, s.person_name as name, min(s.origin_time) as first_time, max(s.origin_time) as last_time from (select person_id, person_name, origin_time, date_format(origin_time, '%d') as day FROM event_recordwhere person_id=? and primary_type=100 and PERIOD_DIFF(date_format(now( ), '%Y%m'), date_format(origin_time, '%Y%m'))=?) s group by s.day`, id, month).Scan(&data)writer := csv.NewWriter(csvfile)for _, da := range data {record := []string{strconv.Itoa(da.Id), da.Name, da.FirstTime.Format("2006-01-02 15:04:05"), da.LastTime.Format("2006-01-02 15:04:05")}err := writer.Write(record)if err != nil {fmt.Println("Error:", err)return}}writer.Flush()}c.JSON(200, gin.H{"message": "export success",})
}
简单介绍一下Swagger的使用。
首先导入swagger相关的包
swaggerFiles "github.com/swaggo/files"ginSwagger "github.com/swaggo/gin-swagger"_ "export/docs"
- swaggerFiles和ginSwagger是swaggo库提供
- export/docs是swag命令生成的本地API文档源代码(export是我的项目名称),在golang里面只需要docs.go,如下:
其次,想要生成swagger文档也非常简单,
- 安装swag命令行工具:go get github.com/swaggo/swag/cmd/swag@v1.8.12
- 编写项目的swagger注释文档,详见swagger README
- 执行生成命令:swag init 在项目docs目录下生成相关文件
然后,为swagger注册gin路由
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
最后,启动服务,访问地址:Swagger UI 即可,如果想查看json格式的文档,可访问地址:localhost:9527/swagger/doc.json