{"id":17645371,"url":"https://github.com/tmnhs/common","last_synced_at":"2025-05-07T05:05:18.210Z","repository":{"id":62501965,"uuid":"560647150","full_name":"tmnhs/common","owner":"tmnhs","description":"一些常用库的二次封装以及连接mysql、redis、etcd、日志的公共包，简化开发过程，能快速的搭建一个web后端服务器","archived":false,"fork":false,"pushed_at":"2023-01-31T10:32:27.000Z","size":111,"stargazers_count":8,"open_issues_count":0,"forks_count":2,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-05-07T05:05:10.728Z","etag":null,"topics":["etcd","gin","go","gorm","redis","template","viper","web","zap"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tmnhs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-11-02T00:26:42.000Z","updated_at":"2024-08-20T08:24:57.000Z","dependencies_parsed_at":"2023-02-16T18:10:45.312Z","dependency_job_id":null,"html_url":"https://github.com/tmnhs/common","commit_stats":null,"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tmnhs%2Fcommon","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tmnhs%2Fcommon/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tmnhs%2Fcommon/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tmnhs%2Fcommon/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tmnhs","download_url":"https://codeload.github.com/tmnhs/common/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252817010,"owners_count":21808705,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["etcd","gin","go","gorm","redis","template","viper","web","zap"],"created_at":"2024-10-23T10:55:37.225Z","updated_at":"2025-05-07T05:05:18.189Z","avatar_url":"https://github.com/tmnhs.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# common\n\u003cdiv align=center\u003e\n\n\u003cimg src=\"https://img.shields.io/badge/golang-1.16.5-blue\"/\u003e\n\u003cimg src=\"https://img.shields.io/badge/gin-1.8.1-lightBlue\"/\u003e\n\u003cimg src=\"https://img.shields.io/badge/gorm-1.23.10-red\"/\u003e\n\u003cimg src=\"https://img.shields.io/badge/etcd-3.5-red\"/\u003e\n\u003c/div\u003e\n\n\u003e 基于gorm、gin、zap、viper实现的对一些常用库的二次封装以及连接mysql、redis、etcd、日志的公共包，简化开发过程，能快速的搭建一个web后端服务器\n\n##  1. 技术选型\n- 数据库:         [Gorm](http://gorm.cn)\n- web框架:      [Gin](https://gin-gonic.com/)\n- 日志:              [Zap](https://github.com/uber-go/zap)\n- 读取配置文件:[Viper](https://github.com/spf13/viper)\n\n## 2.功能特性\n\n- 支持数据库mysql、redis、etcd连接\n- 提供五种文件上传(存储)的方式，包括本地上传、阿里云存储对象、七牛云存储对象、腾讯云存储对象、华为云存储对象\n- 提供通知功能，提供email和webhook两种方式\n- 提供http请求Get方法和Post方法\n- 提供日志封装\n- 通过viper加载配置文件，支持testing和production两种环境，支持json、yaml、ini三种文件格式\n- 提供一些有用的工具包\n    - event.go: 监听程序的退出信号\n    - file.go:  一些对文件目录处理的函数\n    - ip.go:    获取本机ip\n    - map.go:   对map的一些封装，提高安全性\n    - md5.go:  对数据的普通加密\n    - parse.go: 对cmd命令的解析\n    - platform.go: 一些关于各平台的常量\n    - scrypt.go: 对数据的高级加密，不可逆\n    - strings.go: 字符串转化的一些处理函数\n    - system.go:  获取服务器的cpu、硬盘、内存等信息\n    - task.go:   对定时任务的简单封装\n    - time.go:   对时间的一些处理函数\n    - uuid.go:   获取uuid（唯一）\n\n\n| 目录         | 说明                               |\n| ---------- | -------------------------------- |\n| dbclient   | 基于gorm实现的数据库mysql连接              |\n| etcdclient | 提供etcd连接                         |\n| httpclient | 提供http(get/post)请求方法             |\n| logger     | 基于zap实现的日志管理，实现日志分类以及分割          |\n| notify     | 提供email和webhook两种通知方式            |\n| server     | 基于gin实现对web服务的启动                 |\n| utils      | 一些工具类 |\n| config.go  | 配置信息的结构体并基于viper加载配置文件           |\n| upload.go  | 文件上传功能的方法封装           |\n| env.go     | 一些环境变量                           |\n| request.go | 常见的绑定请求的的结构体                     |\n| response.go | 常见的请求返回的结构体   \n\n## 3. 使用方法\n\n```shell\ngo get -u github.com/tmnhs/common\n```\n\n**详细的使用示例可见:**  [common-test](https://github.com/tmnhs/common-test)\n\n### 3.1.配置文件\n\n\u003e 配置文件支持多种环境(testing/prodution)和多种格式(json/yaml/ini)\n\u003e\n\u003e **注意事项**:配置文件的目录必须是下面这个样子\n\n\n```shell\n├── cmd\n├── conf\n|     ├── production                #生产环境，支持json、yaml、ini三种配置文件\n|     |          └── main.json\n|     └── testing\n|                └── main.json      #测试环境，支持json、yaml、ini三种配置文件\n└── internal\n```\n**配置文件示例(json格式)**\n\n```json\n{\n  \"mysql\": {\n    \"path\": \"127.0.0.1\",\n    \"port\": \"3306\",\n    \"config\": \"charset=utf8mb4\u0026parseTime=True\u0026loc=Local\",\n    \"db-name\": \"common-test\",\n    \"username\": \"\",\n    \"password\": \"\",\n    \"max-idle-conns\": 100,\n    \"max-open-conns\": 100,\n    \"log-mode\": \"info\",\n    \"log-zap\": false\n  },\n  \"redis\": {\n    \"addr\": \"127.0.0.1:6379\",\n    \"password\": \"\",\n    \"db\": 0\n  },\n  \"system\": {\n    \"env\": \"testing\",\n    \"addr\": 8089,\n    \"upload-type\": \"qiniu\",\n    \"version\": \"v1.0.2\"\n  },\n  \"etcd\": {\n    \"endpoints\": [\n      \"http://127.0.0.1:2379\"\n    ],\n    \"username\": \"\",\n    \"password\": \"\",\n    \"dial-timeout\": 2,\n    \"req-timeout\": 5\n  },\n  \"notify\": {\n    \"email\": {\n      \"port\": 465,\n      \"from\": \"test@qq.com\",\n      \"host\": \"smtp.qq.com\",\n      \"is-ssl\": true,\n      \"secret\": \"test\",\n      \"nickname\": \"common-test\",\n      \"to\": [\n        \"test@test.mobi\"\n      ]\n    },\n    \"webhook\": {\n      \"url\": \"url\",\n      \"kind\": \"feishu\"\n    }\n  },\n  \"upload\": {\n    \"local\": {\n      \"path\": \"upload\"\n    },\n    \"aliyun-oss\": {\n      \"endpoint\": \"yourEndpoint\",\n      \"access-key-id\": \"yourAccessKeyId\",\n      \"access-key-secret\": \"yourAccessKeySecret\",\n      \"bucket-name\": \"yourBucketName\",\n      \"bucket-url\": \"yourBucketUrl\",\n      \"base-path\": \"yourBasePath\"\n    },\n    \"hua-wei-obs\": {\n      \"path\": \"you-path\",\n      \"bucket\": \"you-bucket\",\n      \"endpoint\": \"you-endpoint\",\n      \"access-key\": \"you-access-key\",\n      \"secret-key\": \"you-secret-key\"\n    },\n    \"qiniu\": {\n      \"zone\": \"ZoneHuanan\",\n      \"bucket\": \"\",\n      \"img-path\": \"http://qny.tmnhs.top\",\n      \"use-https\": false,\n      \"access-key\": \"\",\n      \"secret-key\": \"\",\n      \"use-cdn-domains\": false\n    },\n    \"tencent-cos\": {\n      \"bucket\": \"xxxxx-10005608\",\n      \"region\": \"ap-shanghai\",\n      \"secret-id\": \"xxxxxxxx\",\n      \"secret-key\": \"xxxxxxxx\",\n      \"base-url\": \"xxxx\",\n      \"path-prefix\": \"your path\"\n    }\n  },\n  \"log\": {\n    \"level\": \"debug\",\n    \"format\": \"console\",\n    \"prefix\": \"[common-test]\",\n    \"director\": \"logs\",\n    \"showLine\": false,\n    \"encode-level\": \"LowercaseLevelEncoder\",\n    \"stacktrace-key\": \"stacktrace\",\n    \"log-in-console\": true\n  }\n}\n```\n\n### 3.2 开启一个web应用\n\n```go\nfunc main() {\n  \t//参数为需要启动的服务(etcd/mysql/redis)\n    //连接成功后可以通过dbclient.GetMysqlDD(),etcdClient.GetEtcd(),redisclient.GetRedis()获取对应的client\n    //通过logger.GetLogger()获取日志处理器\n    //通过common.GetConfigModels()获取配置文件的信息\n\tsrv, err := server.NewApiServer(server.WithEtcd(),server.WithMysql(),server.WithRedis())\n\tif err != nil {\n\t\tlogger.GetLogger().Error(fmt.Sprintf(\"new api server error:%s\", err.Error()))\n\t\tos.Exit(1)\n\t}\n\t// 注册路由\n\tsrv.RegisterRouters(handler.RegisterRouters)\n\n\t// 建表，当然，如果不需要可以直接注释掉\n\terr = service.RegisterTables(dbclient.GetMysqlDB())\n\tif err != nil {\n\t\tlogger.GetLogger().Error(fmt.Sprintf(\"init db table error:%#v\", err))\n\t}\n\terr = srv.ListenAndServe()\n\tif err != nil {\n\t\tlogger.GetLogger().Error(fmt.Sprintf(\"startup api server error:%v\", err.Error()))\n\t\tos.Exit(1)\n\t}\n\tos.Exit(0)\n}\n\n```\n\n### 3.3 注册路由\n\n```go\n\nfunc RegisterRouters(r *gin.Engine) {\n\n\tconfigRoute(r)\n\n\tconfigNoRoute(r)\n}\n\nfunc configRoute(r *gin.Engine) {\n\n\thello := r.Group(\"/ping\")\n\t{\n\t\thello.GET(\"\", func(c *gin.Context) {\n\t\t\tc.JSON(200, \"pong\")\n\t\t})\n\t}\n\n\tbase := r.Group(\"\")\n\t{\n\t\tbase.POST(\"register\", defaultUserRouter.Register)\n\t\tbase.POST(\"login\", defaultUserRouter.Login)\n\t}\n\n\tuser := r.Group(\"/user\")\n\tuser.Use(middlerware.JWTAuth())\n\t{\n\t\tuser.POST(\"del\", defaultUserRouter.Delete)\n\t\tuser.POST(\"update\", defaultUserRouter.Update)\n\t\tuser.POST(\"change_pw\", defaultUserRouter.ChangePassword)\n\t\tuser.GET(\"find\", defaultUserRouter.FindById)\n\t\tuser.POST(\"search\", defaultUserRouter.Search)\n\t}\n}\n\nfunc configNoRoute(r *gin.Engine) {\n\t/*\tr.LoadHTMLGlob(\"./dist/*.html\") // npm打包成dist的路径\n\t\tr.StaticFile(\"favicon.ico\", \"./dist/favicon.ico\")\n\t\tr.Static(\"/css\", \"./dist/css\")\n\t\tr.Static(\"/fonts\", \"./dist/fonts\")\n\t\tr.Static(\"/js\", \"./dist/js\")\n\t\tr.Static(\"/img\", \"./dist/img\")\n\t\tr.StaticFile(\"/\", \"./dist/index.html\") // 前端网页入口页面*/\n}\n```\n\n## 4. 可能出现的问题\n\n如果引入包并且go mod tidy 出现以下错误时\n\n```go\ngo: finding module for package google.golang.org/grpc/naming\ngithub.com/tmnhs/common-test/cmd imports\n        github.com/tmnhs/common/server imports\n        github.com/tmnhs/common/etcdclient imports\n        github.com/coreos/etcd/clientv3 tested by\n        github.com/coreos/etcd/clientv3.test imports\n        github.com/coreos/etcd/integration imports\n        github.com/coreos/etcd/proxy/grpcproxy imports\n        google.golang.org/grpc/naming: module google.golang.org/grpc@latest found (v1.50.1), but does not contain package google.golang.org/grpc/naming\n```\n\n可以在go.mod中添加以下一行（这个报错和etcd连接的第三方库有版本冲突）\n\n```\nreplace google.golang.org/grpc =\u003e google.golang.org/grpc v1.26.0\n```\n## 5. 其他功能\n如果你需要添加其他的功能，建议将common克隆到你的项目里自行修改，然后\n```\nreplace github.com/tmnhs/common =\u003e ../common\n```\n\n## 6. 交流讨论\n\n如有问题欢迎加qq:1685290935一起交流讨论","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftmnhs%2Fcommon","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftmnhs%2Fcommon","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftmnhs%2Fcommon/lists"}