├── .gitignore ├── LICENSE ├── README.md ├── app.ini ├── app_dev.ini ├── config └── config.go ├── controller ├── article_controller.go └── base_controller.go ├── go.mod ├── go.sum ├── log ├── gorm_logger.go └── logger.go ├── main.go ├── middleware ├── access_log.go └── add_trace.go ├── model ├── article.go ├── comment.go └── db.go ├── router └── router.go ├── service └── article_service.go ├── storage └── databases │ └── blog.sql └── util ├── const.go └── func.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | .idea 3 | storage/* 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Gen Web 2 | 3 | ## 介绍 4 | 众所周知,Go在Web领域有很多应用,不少公司拿Go来写一些接口,不仅在安全性可靠性上面有优势,而且得益于Go强大的协程机制,性能也很高,但是Go至今仍然缺乏一个全栈的Web框架。 5 | 6 | 或者说,并不是缺乏,因为也一直有各种Web框架诞生,但是至今仍然没有一个框架得到广泛的认同和普及,没有一个框架能达到Java界的Spring,或者PHP界的Laravel那种程度。 7 | 8 | 在我看来,一个Web框架至少应该包括以下几个方面: 9 | 10 | - 路由 11 | - 日志 12 | - 数据库|ORM 13 | - 配置管理 14 | - 控制器 15 | - 中间件 16 | - 鉴权 17 | 18 | 其实这些组件单独拎出来都有很多知名的项目,但是组合到一起的并不多,比如Gin这个框架,非常优秀,但是缺少配置、数据库的组件,它只包括一个核心的Web模块,也有一些框架虽然包括了这些组件,但是过于复杂了,也许你并不需要这些功能。 19 | 20 | 这个项目就是一个基于Gin框架封装的脚手架工具,在Gin框架的基础上增加了日志、ORM、配置等模块,其实只是把一些开源的组件拼了一下,便于用Go快速开发一些Web API,使用以下开源组件: 21 | 22 | * [github.com/gin-gonic/gin](https://github.com/gin-gonic/gin) 23 | * [gorm.io/gorm](https://gorm.io/gorm) 24 | * [go.uber.org/zap](https://go.uber.org/zap) 25 | * [github.com/go-playground/validator/v10](https://github.com/go-playground/validator/v10) 26 | * [github.com/go-redis/redis](https://github.com/go-redis/redis) 27 | 28 | 项目主打的就是一个简单易用,快速上手,如果你觉得哪里不合适,自己改一改就行了,包含了一个文章增删改查等功能的 Restful API 应用,如果你喜欢Gin框架,不妨参考一下! 29 | 30 | 主要包含以下API: 31 | 32 | | METHOD |URI|DESCRIPTION| 33 | |--------|---|---| 34 | | GET |/|默认首页 35 | | GET |/api/v1/articles|文章列表 36 | | POST |/api/v1/articles|发布文章 37 | | GET |/api/v1/articles/:id|文章详情 38 | | PUT |/api/v1/articles/:id|修改文章 39 | | DELETE |/api/v1/articles/:id|删除文章 40 | | GET |/api/v1/articles/:id/comments|查看文章评论 41 | | POST |/api/v1/articles/:id/comments|添加文章评论 42 | 43 | ## 架构 44 | 之前有一版是借鉴了著名Go开源项目 [Grafana](https://github.com/grafana/grafana) 的设计,使用了依赖注入机制,但是感觉过于复杂,不容易理解和使用,所以又改了。 45 | 46 | 本着简单易用易修改的原则,采用了**包全局变量**的方式初始化配置、日志、DB连接,项目目录如下: 47 | ``` 48 | ├── config //配置 49 | ├── controller //控制器 50 | ├── log //日志 51 | ├── middleware //中间件 52 | ├── model //数据表模型 53 | ├── router //路由 54 | ├── service //服务 55 | └── util //工具函数 56 | ``` 57 | 在 ```main.go``` 里面依次**显示**初始化各个组件,清晰明了,简单易懂。 58 | 59 | ## 模块 60 | ### 1.配置 61 | 往往框架启动第一件事就是加载配置,Go的配置形式有很多种,比如最简单的JSON,但是JSON存在一个很大的问题就是无法注释,其次每增加一个配置就需要在结构体上面增加成员变量,也很麻烦。 62 | 63 | 我这里使用了ini作为配置文件格式,采用第三方库[gopkg.in/ini.v1](gopkg.in/ini.v1)来解析。 64 | 65 | 项目对这三方库的对象进行了简单包装,方便后续扩展,提供了一个Get()方法给外部调用,具体的用法可以参考库的文档。 66 | ```go 67 | var cfg *App 68 | 69 | func Get() *App { 70 | return cfg 71 | } 72 | 73 | type App struct { 74 | Env string 75 | HttpPort string 76 | LogFile string 77 | LogConsole bool 78 | LogLevel string 79 | 80 | *ini.File 81 | } 82 | ``` 83 | 另外,推荐不同环境采用不同的配置,比如app_dev.ini就是开发配置,可以通过-conf指定配置文件,默认会使用app.ini配置。 84 | 85 | ### 2.日志 86 | 日志这块最大的改变就是实现了全链路日志,方便问题排查,采用了第三方库zap log,在此基础上进行了封装。 87 | 88 | ```go 89 | var zapLogger *zap.Logger 90 | 91 | type Logger struct { 92 | context.Context 93 | *zap.Logger 94 | } 95 | 96 | // WithCtx 带请求上下文的Logger,可以记录一些额外信息,比如traceId 97 | func WithCtx(ctx context.Context) *Logger { 98 | return &Logger{ctx, zapLogger} 99 | } 100 | ``` 101 | 还有一个就是实现了gorm的的sql日志,把sql日志也加上了traceId,为了实现链路日志,需要在记录日志的时候传入context对象,另外在控制器到模型层之间的调用也需要显示的传递context对象。 102 | 103 | ### 3.数据库 104 | 这块就是采用了第三方库gorm,具体用法可以参考其官方文档,这里面比较大的改动就是对日志的接口的实现,把sql日志记录下来了,详细可以看一下**gorm_logger.go**文件。 105 | 106 | 在配置里面支持多个数据库切换。 107 | ```go 108 | var connPool = make(map[string]*gorm.DB) 109 | 110 | // NewOrm 默认返回default数据库连接 111 | func NewOrm(ctx context.Context, dbName ...string) *gorm.DB { 112 | conn := connPool["default"] 113 | if len(dbName) > 0 { 114 | if cn, ok := connPool[dbName[0]]; ok { 115 | conn = cn 116 | } 117 | } 118 | return conn.WithContext(ctx) 119 | } 120 | ``` 121 | 122 | ### 4.中间件 123 | 中间件这块添加了2个默认的,一个是增加链接日志用到的traceId,另一个记录一个访问日志,类似于Nginx的access_log,方便排查问题。 124 | 125 | 其余的话如果有需要可以自行增加。 126 | 127 | ### 5.MVC模型 128 | 由于接口并不涉及到视图文件,所以也不完全是MVC模型,不过我个人推荐3层结构: 129 | 130 | controller ---> service ----> model 131 | 132 | controller层的主要作用的对参数进行校验,项目采用了一个validation组件,通过结构体tag形式进行校验,校验通过后调用service层。 133 | 134 | service层的主要作用是完成一些比较复杂的业务逻辑处理,不过很多增删改查接口逻辑本来就简单,这块也可以考虑去掉,直接调用model也不是不可。 135 | 136 | model层的主要作用就是涉及数据库的操作。 137 | 138 | 这3层我都建议采用结构体成员函数的形式,然后使用全局变量初始化,这样用的时候就不用初始化了,直接调就行了,主要好处就是简单方便,当然这里注意一定不要在结构体里面存储私有数据,这样会出问题。 139 | ```go 140 | type articleController struct { 141 | *Controller 142 | *service.ArticleService 143 | } 144 | 145 | var ArticleController = articleController{ 146 | Controller: BaseController, 147 | ArticleService: service.NewArticleService(), 148 | } 149 | 150 | // Create 添加文章 151 | func (r articleController) Create(ctx *gin.Context) { 152 | var param model.CreateArticleCommand 153 | err := ctx.ShouldBindJSON(¶m) 154 | if err != nil { 155 | r.Failed(ctx, ParamError, translate(err)) 156 | return 157 | } 158 | if article, err := r.ArticleService.Create(ctx, ¶m); err != nil { 159 | r.Failed(ctx, Failed, err.Error()) 160 | } else { 161 | r.Success(ctx, "添加文章成功", article) 162 | } 163 | return 164 | ``` 165 | 166 | ## 命名规范 167 | 个人建议参考以下规范: 168 | 169 | - 表名、文件夹名使用单数,比如```article、phone``` 170 | - 文件夹名全部小写,多个单词的话直接相连。如 ```eventhandler``` 171 | - 文件名小写下划线,如 ```article_controller.go``` 172 | - 变量名驼峰,如 ```var userId int```,```pageSize := 10```,首字母是否大写根据实际需要(是否要公开) 173 | - 结构体名驼峰,如 ```type userService struct ```,首字母是否大写根据实际需要(是否要公开) 174 | - 函数名驼峰,如果 ```func getUserById()```,首字母是否大写根据实际需要(是否要公开) 175 | 176 | 其它规范建议以Goland内置标准为准,一般情况下IDE都会提示,建议遵循。 177 | 178 | ## 使用 179 | 直接git clone本项目,然后根据自己的需求删除多余的控制器、模型等文件,如果有特殊需求直接修改代码即可,没有什么限制,Go的代码本来就很简单,我这里也只是给大家一个参考。 -------------------------------------------------------------------------------- /app.ini: -------------------------------------------------------------------------------- 1 | [app] 2 | env = prod 3 | http_port = 8080 4 | #日志存储文件 5 | log_file = storage/app.log 6 | #是否在控制台输出日志 7 | log_console = false 8 | log_level = error 9 | 10 | #默认数据库 11 | [db.default] 12 | dialect = mysql 13 | dsn = root:123456@tcp(127.0.0.1:3306)/blog?charset=utf8mb4&parseTime=True&loc=Local 14 | max_idle_conn = 5 15 | max_open_conn = 50 16 | 17 | [db.user] 18 | dialect = mysql 19 | dsn = root:123456@tcp(127.0.0.1:3306)/blog?charset=utf8mb4&parseTime=True&loc=Local 20 | max_idle_conn = 5 21 | max_open_conn = 50 22 | 23 | [db.other] 24 | dialect = mysql 25 | dsn = root:123456@tcp(127.0.0.1:3306)/blog?charset=utf8mb4&parseTime=True&loc=Local 26 | max_idle_conn = 5 27 | max_open_conn = 50 28 | 29 | [redis] 30 | host = 127.0.0.1 31 | port = 6379 32 | pass = 33 | min_idle = 10 -------------------------------------------------------------------------------- /app_dev.ini: -------------------------------------------------------------------------------- 1 | [app] 2 | env = dev 3 | http_port = 8080 4 | #日志存储文件 5 | log_file = storage/app.log 6 | #是否在控制台输出日志 7 | log_console = true 8 | log_level = debug 9 | 10 | #默认数据库 11 | [db.default] 12 | dialect = mysql 13 | dsn = root:123456@tcp(127.0.0.1:3306)/blog?charset=utf8mb4&parseTime=True&loc=Local 14 | max_idle_conn = 5 15 | max_open_conn = 50 16 | 17 | [db.user] 18 | dialect = mysql 19 | dsn = root:123456@tcp(127.0.0.1:3306)/blog?charset=utf8mb4&parseTime=True&loc=Local 20 | max_idle_conn = 5 21 | max_open_conn = 50 22 | 23 | [db.other] 24 | dialect = mysql 25 | dsn = root:123456@tcp(127.0.0.1:3306)/blog?charset=utf8mb4&parseTime=True&loc=Local 26 | max_idle_conn = 5 27 | max_open_conn = 50 28 | 29 | [redis] 30 | host = 127.0.0.1 31 | port = 6379 32 | pass = 33 | min_idle = 10 -------------------------------------------------------------------------------- /config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "fmt" 5 | "gopkg.in/ini.v1" 6 | "os" 7 | ) 8 | 9 | const ( 10 | Dev = "dev" 11 | Prod = "prod" 12 | Test = "test" 13 | ) 14 | 15 | var cfg *App 16 | 17 | func Get() *App { 18 | return cfg 19 | } 20 | 21 | type App struct { 22 | Env string 23 | HttpPort string 24 | LogFile string 25 | LogConsole bool 26 | LogLevel string 27 | 28 | *ini.File 29 | } 30 | 31 | // Init 加载app.ini配置文件 32 | func Init(file string) (*App, error) { 33 | cfg = &App{ 34 | Env: Dev, 35 | HttpPort: "8080", 36 | LogConsole: true, 37 | LogLevel: "info", 38 | File: ini.Empty(), 39 | } 40 | if _, err := os.Stat(file); os.IsNotExist(err) { 41 | return nil, fmt.Errorf("cfg file [%s] not existed", file) 42 | } 43 | conf, err := ini.Load(file) 44 | if err != nil { 45 | return nil, fmt.Errorf("load file [%s] failed", file) 46 | } 47 | cfg.File = conf 48 | cfg.loadAppCfg() 49 | return cfg, nil 50 | } 51 | 52 | func (cfg *App) IsDevEnv() bool { 53 | return cfg.Env == Dev 54 | } 55 | 56 | func (cfg *App) loadAppCfg() { 57 | section := cfg.Section("app") 58 | env := section.Key("env").String() 59 | if env != "" { 60 | cfg.Env = env 61 | } 62 | httpPort := section.Key("http_port").String() 63 | if httpPort != "" { 64 | cfg.HttpPort = httpPort 65 | } 66 | logFile := section.Key("log_file").String() 67 | if logFile != "" { 68 | cfg.LogFile = logFile 69 | } 70 | if section.Key("log_console").String() == "true" { 71 | cfg.LogConsole = true 72 | } 73 | logLevel := section.Key("log_level").String() 74 | if logLevel != "" { 75 | cfg.LogLevel = logLevel 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /controller/article_controller.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "gen/config" 5 | "gen/log" 6 | "gen/model" 7 | "gen/service" 8 | "github.com/gin-gonic/gin" 9 | "strconv" 10 | ) 11 | 12 | type articleController struct { 13 | *Controller 14 | *service.ArticleService 15 | } 16 | 17 | var ArticleController = articleController{ 18 | Controller: BaseController, 19 | ArticleService: service.NewArticleService(), 20 | } 21 | 22 | // Create 添加文章 23 | func (r articleController) Create(ctx *gin.Context) { 24 | var param model.CreateArticleCommand 25 | err := ctx.ShouldBindJSON(¶m) 26 | if err != nil { 27 | r.Failed(ctx, ParamError, translate(err)) 28 | return 29 | } 30 | if article, err := r.ArticleService.Create(ctx, ¶m); err != nil { 31 | r.Failed(ctx, Failed, err.Error()) 32 | } else { 33 | r.Success(ctx, "添加文章成功", article) 34 | } 35 | return 36 | } 37 | 38 | // Update 修改文章 39 | func (r articleController) Update(ctx *gin.Context) { 40 | var param model.UpdateArticleCommand 41 | err := ctx.ShouldBindJSON(¶m) 42 | if err != nil { 43 | r.Failed(ctx, Failed, translate(err)) 44 | return 45 | } 46 | param.Id, err = strconv.Atoi(ctx.Param("id")) 47 | if err != nil || param.Id <= 0 { 48 | r.Failed(ctx, ParamError, "id不能为空") 49 | return 50 | } 51 | if err := r.ArticleService.Update(ctx, ¶m); err != nil { 52 | r.Failed(ctx, Failed, err.Error()) 53 | } else { 54 | r.Success(ctx, "修改文章成功", nil) 55 | } 56 | return 57 | } 58 | 59 | // GetById 文章详情 60 | func (r articleController) GetById(ctx *gin.Context) { 61 | id, err := strconv.Atoi(ctx.Param("id")) 62 | if err != nil || id <= 0 { 63 | r.Failed(ctx, ParamError, "id不能为空") 64 | return 65 | } 66 | article, err := r.ArticleService.GetById(ctx, id) 67 | if err != nil { 68 | r.Failed(ctx, Failed, err.Error()) 69 | } else { 70 | r.Success(ctx, "ok", article) 71 | } 72 | return 73 | } 74 | 75 | // GetAll 文章列表 76 | func (r articleController) GetAll(ctx *gin.Context) { 77 | r.ParsePage(ctx) 78 | log.WithCtx(ctx).Info("GetAll Articles: " + config.Get().Env) 79 | articles, totalCount, err := r.ArticleService.GetAll(ctx, r.Page, r.PageSize) 80 | if err != nil { 81 | r.Failed(ctx, Failed, err.Error()) 82 | } else { 83 | r.Success(ctx, "ok", Pagination{ 84 | List: articles, 85 | Page: r.Page, 86 | PageSize: r.PageSize, 87 | TotalCount: totalCount, 88 | }) 89 | } 90 | return 91 | } 92 | 93 | // Delete 删除文章 94 | func (r articleController) Delete(ctx *gin.Context) { 95 | id, err := strconv.Atoi(ctx.Param("id")) 96 | if err != nil || id <= 0 { 97 | r.Failed(ctx, ParamError, "id不能为空") 98 | return 99 | } 100 | err = r.ArticleService.Delete(ctx, id) 101 | if err != nil { 102 | r.Failed(ctx, Failed, err.Error()) 103 | } else { 104 | r.Success(ctx, "删除成功", nil) 105 | } 106 | return 107 | } 108 | 109 | // AddComment 新增评论 110 | func (r articleController) AddComment(ctx *gin.Context) { 111 | var param model.CreateArticleCommentCommand 112 | err := ctx.ShouldBindJSON(¶m) 113 | if err != nil { 114 | r.Failed(ctx, Failed, "请求错误") 115 | return 116 | } 117 | id, err := strconv.Atoi(ctx.Param("id")) 118 | if err != nil || id <= 0 { 119 | r.Failed(ctx, ParamError, "id不能为空") 120 | return 121 | } 122 | param.Id = id 123 | err = r.ArticleService.AddComment(ctx, ¶m) 124 | if err != nil { 125 | r.Failed(ctx, Failed, err.Error()) 126 | } else { 127 | r.Success(ctx, "ok", "评论成功") 128 | } 129 | return 130 | } 131 | -------------------------------------------------------------------------------- /controller/base_controller.go: -------------------------------------------------------------------------------- 1 | package controller 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/gin-gonic/gin/binding" 6 | "github.com/go-playground/locales/en" 7 | "github.com/go-playground/locales/zh" 8 | ut "github.com/go-playground/universal-translator" 9 | "github.com/go-playground/validator/v10" 10 | zht "github.com/go-playground/validator/v10/translations/zh" 11 | "net/http" 12 | "strconv" 13 | "strings" 14 | ) 15 | 16 | type errorCode int 17 | 18 | const ( 19 | Success errorCode = 200 20 | Failed errorCode = 500 21 | ParamError errorCode = 400 22 | NotFound errorCode = 404 23 | UnAuthorized errorCode = 401 24 | ) 25 | 26 | var codeMsg = map[errorCode]string{ 27 | Success: "正常", 28 | Failed: "系统异常", 29 | ParamError: "参数错误", 30 | NotFound: "记录不存在", 31 | UnAuthorized: "未授权", 32 | } 33 | 34 | type Controller struct { 35 | Page int 36 | PageSize int 37 | } 38 | 39 | type Pagination struct { 40 | List interface{} `json:"list"` 41 | Page int `json:"page"` 42 | PageSize int `json:"page_size"` 43 | TotalCount int64 `json:"total_count"` 44 | } 45 | 46 | var BaseController = &Controller{} 47 | 48 | var trans ut.Translator 49 | 50 | // 注册validator中文翻译 51 | func init() { 52 | uni := ut.New(en.New(), zh.New()) 53 | trans, _ = uni.GetTranslator("zh") 54 | validate := binding.Validator.Engine().(*validator.Validate) 55 | _ = zht.RegisterDefaultTranslations(validate, trans) 56 | } 57 | 58 | func translate(err error) string { 59 | errors, ok := err.(validator.ValidationErrors) 60 | if !ok { 61 | return err.Error() 62 | } 63 | result := make([]string, 0) 64 | for _, err := range errors { 65 | errMsg := err.Translate(trans) 66 | if errMsg == "" { 67 | continue 68 | } 69 | result = append(result, errMsg) 70 | } 71 | return strings.Join(result, ",") 72 | } 73 | 74 | func (r *Controller) ParsePage(ctx *gin.Context) { 75 | page, err := strconv.Atoi(ctx.Query("page")) 76 | if err != nil || page <= 0 { 77 | page = 1 78 | } 79 | pageSize, err := strconv.Atoi(ctx.Query("page_size")) 80 | if err != nil || pageSize <= 0 { 81 | pageSize = 15 82 | } 83 | if pageSize > 1000 { 84 | pageSize = 1000 85 | } 86 | r.Page = page 87 | r.PageSize = pageSize 88 | } 89 | 90 | func (*Controller) Index(ctx *gin.Context) { 91 | ctx.String(http.StatusOK, "Gen Web") 92 | } 93 | 94 | func (*Controller) Success(ctx *gin.Context, msg string, data interface{}) { 95 | ctx.JSON(http.StatusOK, gin.H{ 96 | "code": Success, 97 | "msg": msg, 98 | "data": data, 99 | "trace_id": ctx.GetString("trace_id"), 100 | }) 101 | } 102 | 103 | func (*Controller) Failed(ctx *gin.Context, code errorCode, msg string) { 104 | errMsg := codeMsg[code] + ": " + msg 105 | ctx.AbortWithStatusJSON(http.StatusOK, gin.H{ 106 | "code": code, 107 | "msg": errMsg, 108 | "data": nil, 109 | "trace_id": ctx.GetString("trace_id"), 110 | }) 111 | if code != Success { 112 | ctx.Set("error_code", int(code)) 113 | ctx.Set("error_msg", msg) 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module gen 2 | 3 | go 1.19 4 | 5 | require ( 6 | github.com/gin-gonic/gin v1.9.1 7 | github.com/google/uuid v1.3.0 8 | go.uber.org/zap v1.24.0 9 | gopkg.in/ini.v1 v1.67.0 10 | gorm.io/driver/mysql v1.5.1 11 | gorm.io/gorm v1.25.2 12 | ) 13 | 14 | require ( 15 | github.com/bytedance/sonic v1.9.2 // indirect 16 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect 17 | github.com/gabriel-vasile/mimetype v1.4.2 // indirect 18 | github.com/gin-contrib/sse v0.1.0 // indirect 19 | github.com/go-playground/locales v0.14.1 // indirect 20 | github.com/go-playground/universal-translator v0.18.1 // indirect 21 | github.com/go-playground/validator/v10 v10.14.1 // indirect 22 | github.com/go-sql-driver/mysql v1.7.1 // indirect 23 | github.com/goccy/go-json v0.10.2 // indirect 24 | github.com/jinzhu/inflection v1.0.0 // indirect 25 | github.com/jinzhu/now v1.1.5 // indirect 26 | github.com/json-iterator/go v1.1.12 // indirect 27 | github.com/klauspost/cpuid/v2 v2.2.5 // indirect 28 | github.com/leodido/go-urn v1.2.4 // indirect 29 | github.com/mattn/go-isatty v0.0.19 // indirect 30 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 31 | github.com/modern-go/reflect2 v1.0.2 // indirect 32 | github.com/pelletier/go-toml/v2 v2.0.8 // indirect 33 | github.com/twitchyliquid64/golang-asm v0.15.1 // indirect 34 | github.com/ugorji/go/codec v1.2.11 // indirect 35 | go.uber.org/atomic v1.11.0 // indirect 36 | go.uber.org/multierr v1.11.0 // indirect 37 | golang.org/x/arch v0.4.0 // indirect 38 | golang.org/x/crypto v0.10.0 // indirect 39 | golang.org/x/net v0.11.0 // indirect 40 | golang.org/x/sys v0.10.0 // indirect 41 | golang.org/x/text v0.11.0 // indirect 42 | google.golang.org/protobuf v1.31.0 // indirect 43 | gopkg.in/yaml.v3 v3.0.1 // indirect 44 | ) 45 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= 2 | github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= 3 | github.com/bytedance/sonic v1.9.2 h1:GDaNjuWSGu09guE9Oql0MSTNhNCLlWwO8y/xM5BzcbM= 4 | github.com/bytedance/sonic v1.9.2/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= 5 | github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= 6 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= 7 | github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= 8 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 9 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 10 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 11 | github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= 12 | github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= 13 | github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= 14 | github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= 15 | github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= 16 | github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= 17 | github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= 18 | github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= 19 | github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= 20 | github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= 21 | github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= 22 | github.com/go-playground/validator/v10 v10.14.1 h1:9c50NUPC30zyuKprjL3vNZ0m5oG+jU0zvx4AqHGnv4k= 23 | github.com/go-playground/validator/v10 v10.14.1/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= 24 | github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= 25 | github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= 26 | github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= 27 | github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= 28 | github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= 29 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= 30 | github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= 31 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 32 | github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 33 | github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= 34 | github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 35 | github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= 36 | github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= 37 | github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= 38 | github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= 39 | github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= 40 | github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 41 | github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= 42 | github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg= 43 | github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= 44 | github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= 45 | github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= 46 | github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= 47 | github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 48 | github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 49 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= 50 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= 51 | github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= 52 | github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= 53 | github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ= 54 | github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= 55 | github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= 56 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 57 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 58 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 59 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 60 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 61 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 62 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 63 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 64 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 65 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 66 | github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 67 | github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY= 68 | github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 69 | github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= 70 | github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= 71 | github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU= 72 | github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= 73 | go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= 74 | go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= 75 | go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= 76 | go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= 77 | go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= 78 | go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= 79 | go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= 80 | golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= 81 | golang.org/x/arch v0.4.0 h1:A8WCeEWhLwPBKNbFi5Wv5UTCBx5zzubnXDlMOFAzFMc= 82 | golang.org/x/arch v0.4.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= 83 | golang.org/x/crypto v0.10.0 h1:LKqV2xt9+kDzSTfOhx4FrkEBcMrAgHSYgzywV9zcGmM= 84 | golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I= 85 | golang.org/x/net v0.11.0 h1:Gi2tvZIJyBtO9SDr1q9h5hEQCp/4L2RQ+ar0qjx2oNU= 86 | golang.org/x/net v0.11.0/go.mod h1:2L/ixqYpgIVXmeoSA/4Lu7BzTG4KIyPIryS4IsOd1oQ= 87 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 88 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 89 | golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= 90 | golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 91 | golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= 92 | golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= 93 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= 94 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 95 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= 96 | google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= 97 | google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= 98 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 99 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 100 | gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= 101 | gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= 102 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 103 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 104 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 105 | gorm.io/driver/mysql v1.5.1 h1:WUEH5VF9obL/lTtzjmML/5e6VfFR/788coz2uaVCAZw= 106 | gorm.io/driver/mysql v1.5.1/go.mod h1:Jo3Xu7mMhCyj8dlrb3WoCaRd1FhsVh+yMXb1jUInf5o= 107 | gorm.io/gorm v1.25.1/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= 108 | gorm.io/gorm v1.25.2 h1:gs1o6Vsa+oVKG/a9ElL3XgyGfghFfkKA2SInQaCyMho= 109 | gorm.io/gorm v1.25.2/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= 110 | rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= 111 | -------------------------------------------------------------------------------- /log/gorm_logger.go: -------------------------------------------------------------------------------- 1 | package log 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "go.uber.org/zap" 7 | "time" 8 | 9 | gl "gorm.io/gorm/logger" 10 | "gorm.io/gorm/utils" 11 | ) 12 | 13 | type gormLogger struct { 14 | gl.Config 15 | infoStr, warnStr, errStr string 16 | traceStr, traceErrStr, traceWarnStr string 17 | } 18 | 19 | // NewGormLogger 包含traceId信息的sql日志 20 | func NewGormLogger(config gl.Config) gl.Interface { 21 | var ( 22 | infoStr = "%s [info] " 23 | warnStr = "%s [warn] " 24 | errStr = "%s [error] " 25 | traceStr = "%s [%.3fms] [rows:%v] %s" 26 | traceWarnStr = "%s %s [%.3fms] [rows:%v] %s" 27 | traceErrStr = "%s %s [%.3fms] [rows:%v] %s" 28 | ) 29 | return &gormLogger{ 30 | Config: config, 31 | infoStr: infoStr, 32 | warnStr: warnStr, 33 | errStr: errStr, 34 | traceStr: traceStr, 35 | traceWarnStr: traceWarnStr, 36 | traceErrStr: traceErrStr, 37 | } 38 | } 39 | 40 | // LogMode log mode 41 | func (l gormLogger) LogMode(level gl.LogLevel) gl.Interface { 42 | newLogger := l 43 | newLogger.LogLevel = level 44 | return &newLogger 45 | } 46 | 47 | // Info print info 48 | func (l gormLogger) Info(ctx context.Context, msg string, data ...interface{}) { 49 | if l.LogLevel >= gl.Info { 50 | WithCtx(ctx).Info(fmt.Sprintf(l.infoStr+msg, append([]interface{}{utils.FileWithLineNum()}, data...)...)) 51 | } 52 | } 53 | 54 | // Warn print warn messages 55 | func (l gormLogger) Warn(ctx context.Context, msg string, data ...interface{}) { 56 | if l.LogLevel >= gl.Warn { 57 | WithCtx(ctx).Warn(fmt.Sprintf(l.warnStr+msg, append([]interface{}{utils.FileWithLineNum()}, data...)...)) 58 | } 59 | } 60 | 61 | // Error print error messages 62 | func (l gormLogger) Error(ctx context.Context, msg string, data ...interface{}) { 63 | if l.LogLevel >= gl.Error { 64 | WithCtx(ctx).Error(fmt.Sprintf(l.errStr+msg, append([]interface{}{utils.FileWithLineNum()}, data...)...)) 65 | } 66 | } 67 | 68 | // Trace print sql message 69 | func (l gormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) { 70 | if l.LogLevel <= gl.Silent { 71 | return 72 | } 73 | elapsed := time.Since(begin) 74 | sql, rows := fc() 75 | fields := []zap.Field{ 76 | zap.String("sql", sql), 77 | zap.String("sql_line", utils.FileWithLineNum()), 78 | zap.Duration("sql_cost", elapsed), 79 | zap.Int64("affected_rows", rows), 80 | zap.Any("err", err), 81 | } 82 | WithCtx(ctx).Info("sql_log", fields...) 83 | } 84 | -------------------------------------------------------------------------------- /log/logger.go: -------------------------------------------------------------------------------- 1 | package log 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "go.uber.org/zap" 7 | "go.uber.org/zap/zapcore" 8 | "os" 9 | 10 | "gen/config" 11 | ) 12 | 13 | var zapLogger *zap.Logger 14 | 15 | type Logger struct { 16 | context.Context 17 | *zap.Logger 18 | } 19 | 20 | // WithCtx 带请求上下文的Logger,可以记录一些额外信息,比如traceId 21 | func WithCtx(ctx context.Context) *Logger { 22 | return &Logger{ctx, zapLogger} 23 | } 24 | 25 | func Close() { 26 | zapLogger.Sync() 27 | } 28 | 29 | // Init 初始化配置日志模块 30 | func Init(cfg *config.App) error { 31 | var level zapcore.Level 32 | if level.UnmarshalText([]byte(cfg.LogLevel)) != nil { 33 | level = zapcore.InfoLevel 34 | } 35 | encoderConfig := zapcore.EncoderConfig{ 36 | LevelKey: "level", 37 | NameKey: "name", 38 | TimeKey: "time", 39 | MessageKey: "msg", 40 | StacktraceKey: "stack", 41 | CallerKey: "location", 42 | LineEnding: zapcore.DefaultLineEnding, 43 | EncodeLevel: zapcore.LowercaseLevelEncoder, 44 | EncodeTime: zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05"), 45 | EncodeDuration: zapcore.StringDurationEncoder, 46 | EncodeCaller: zapcore.ShortCallerEncoder, 47 | } 48 | var cores []zapcore.Core 49 | if cfg.LogFile != "" { 50 | fileWriter, err := os.OpenFile(cfg.LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) 51 | if err != nil { 52 | return err 53 | } 54 | cores = append(cores, zapcore.NewCore(zapcore.NewJSONEncoder(encoderConfig), zapcore.AddSync(fileWriter), level)) 55 | } 56 | if cfg.LogConsole { 57 | cores = append(cores, zapcore.NewCore(zapcore.NewConsoleEncoder(encoderConfig), zapcore.AddSync(os.Stdout), level)) 58 | } 59 | zapLogger = zap.New(zapcore.NewTee(cores...), zap.AddCaller(), zap.AddCallerSkip(1)) 60 | return nil 61 | } 62 | 63 | func Debug(format string, args ...interface{}) { 64 | zapLogger.Debug(fmt.Sprintf(format, args...)) 65 | } 66 | 67 | func Println(args ...interface{}) { 68 | zapLogger.Debug(fmt.Sprintln(args...)) 69 | } 70 | 71 | func Info(format string, args ...interface{}) { 72 | zapLogger.Info(fmt.Sprintf(format, args...)) 73 | } 74 | 75 | func Warn(format string, args ...interface{}) { 76 | zapLogger.Warn(fmt.Sprintf(format, args...)) 77 | } 78 | 79 | func Error(format string, args ...interface{}) { 80 | zapLogger.Error(fmt.Sprintf(format, args...)) 81 | } 82 | 83 | func Panic(format string, args ...interface{}) { 84 | zapLogger.Panic(fmt.Sprintf(format, args...)) 85 | } 86 | 87 | func (r Logger) Debug(msg string, fields ...zap.Field) { 88 | traceId, _ := r.Value("trace_id").(string) 89 | r.Logger.With(append(fields, zap.String("trace_id", traceId))...).Debug(msg) 90 | } 91 | 92 | func (r Logger) Info(msg string, fields ...zap.Field) { 93 | traceId, _ := r.Value("trace_id").(string) 94 | r.Logger.With(append(fields, zap.String("trace_id", traceId))...).Info(msg) 95 | } 96 | 97 | func (r Logger) Warn(msg string, fields ...zap.Field) { 98 | traceId, _ := r.Value("trace_id").(string) 99 | r.Logger.With(append(fields, zap.String("trace_id", traceId))...).Warn(msg) 100 | } 101 | 102 | func (r Logger) Error(msg string, fields ...zap.Field) { 103 | traceId, _ := r.Value("trace_id").(string) 104 | r.Logger.With(append(fields, zap.String("trace_id", traceId))...).Error(msg) 105 | } 106 | 107 | func (r Logger) Panic(msg string, fields ...zap.Field) { 108 | traceId, _ := r.Value("trace_id").(string) 109 | r.Logger.With(append(fields, zap.String("trace_id", traceId))...).Panic(msg) 110 | } 111 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "flag" 7 | "fmt" 8 | "gen/config" 9 | "gen/log" 10 | "gen/middleware" 11 | "gen/model" 12 | "gen/router" 13 | "github.com/gin-gonic/gin" 14 | "net/http" 15 | "os" 16 | "os/signal" 17 | "syscall" 18 | ) 19 | 20 | func main() { 21 | var configFile string 22 | flag.StringVar(&configFile, "conf", "app.ini", "config file path") 23 | flag.Parse() 24 | 25 | // 加载配置 26 | cfg, err := config.Init(configFile) 27 | if err != nil { 28 | panic(fmt.Sprintf("load config failed, file: %s, error: %s", configFile, err)) 29 | } 30 | 31 | // 初始化日志 32 | err = log.Init(cfg) 33 | if err != nil { 34 | log.Panic("Init log failed, error: %s", err) 35 | } 36 | defer log.Close() 37 | 38 | // 初始化数据库 39 | err = model.Init(cfg) 40 | if err != nil { 41 | log.Panic("Init db failed, error: %s", err) 42 | } 43 | 44 | // 启动Web服务 45 | log.Info("Server starting...") 46 | err = startServer(cfg) 47 | if err != nil { 48 | log.Panic("Server started failed: %s", err) 49 | } 50 | } 51 | 52 | func startServer(cfg *config.App) error { 53 | server := &http.Server{ 54 | Addr: ":" + cfg.HttpPort, 55 | Handler: getEngine(cfg), 56 | } 57 | ctx, cancel := context.WithCancel(context.Background()) 58 | go func(ctxFunc context.CancelFunc) { 59 | signalChan := make(chan os.Signal, 1) 60 | signal.Notify(signalChan, os.Interrupt, syscall.SIGTERM) 61 | for { 62 | select { 63 | case <-signalChan: 64 | ctxFunc() 65 | return 66 | } 67 | } 68 | }(cancel) 69 | go func() { 70 | <-ctx.Done() 71 | if err := server.Shutdown(context.Background()); err != nil { 72 | log.Error("Failed to shutdown server: %s", err) 73 | } 74 | }() 75 | log.Debug("Server started success") 76 | err := server.ListenAndServe() 77 | if errors.Is(err, http.ErrServerClosed) { 78 | log.Debug("Server was shutdown gracefully") 79 | return nil 80 | } 81 | return err 82 | } 83 | 84 | func getEngine(cfg *config.App) *gin.Engine { 85 | gin.SetMode(func() string { 86 | if cfg.IsDevEnv() { 87 | return gin.DebugMode 88 | } 89 | return gin.ReleaseMode 90 | }()) 91 | engine := gin.New() 92 | engine.Use(gin.CustomRecovery(func(c *gin.Context, err interface{}) { 93 | log.WithCtx(c).Error(fmt.Sprintf("server panic: %s", err)) 94 | c.AbortWithStatusJSON(http.StatusOK, gin.H{ 95 | "code": 500, 96 | "msg": "服务器内部错误,请稍后再试!", 97 | }) 98 | })) 99 | //添加全局的traceId和访问日志 100 | engine.Use(middleware.AddTrace()) 101 | engine.Use(middleware.AccessLog()) 102 | router.RegisterRoutes(engine) 103 | return engine 104 | } 105 | -------------------------------------------------------------------------------- /middleware/access_log.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "bytes" 5 | "gen/log" 6 | "github.com/gin-gonic/gin" 7 | "go.uber.org/zap" 8 | "io" 9 | "time" 10 | ) 11 | 12 | func AccessLog() gin.HandlerFunc { 13 | return func(ctx *gin.Context) { 14 | start := time.Now() 15 | path := ctx.Request.URL.Path 16 | raw := ctx.Request.URL.RawQuery 17 | var reqBody []byte 18 | if ctx.Request.Body != nil { 19 | reqBody, _ = io.ReadAll(ctx.Request.Body) 20 | ctx.Request.Body = io.NopCloser(bytes.NewBuffer(reqBody)) 21 | } 22 | if len(reqBody) > 1000 { 23 | reqBody = reqBody[:1000] 24 | } 25 | 26 | ctx.Next() 27 | 28 | latency := time.Now().Sub(start) 29 | clientIP := ctx.ClientIP() 30 | method := ctx.Request.Method 31 | statusCode := ctx.Writer.Status() 32 | bodySize := ctx.Writer.Size() 33 | if raw != "" { 34 | path = path + "?" + raw 35 | } 36 | log.WithCtx(ctx).Info("access_log", 37 | zap.String("path", path), 38 | zap.String("method", method), 39 | zap.String("http_host", ctx.Request.Host), 40 | zap.String("ua", ctx.Request.UserAgent()), 41 | zap.String("remote_addr", ctx.Request.RemoteAddr), 42 | zap.ByteString("request_body", reqBody), 43 | zap.Int("status_code", statusCode), 44 | zap.Int("error_code", ctx.GetInt("error_code")), 45 | zap.String("error_msg", ctx.GetString("error_code")), 46 | zap.Int("body_size", bodySize), 47 | zap.String("client_ip", clientIP), 48 | zap.Duration("latency", latency), 49 | ) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /middleware/add_trace.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/google/uuid" 6 | ) 7 | 8 | func AddTrace() gin.HandlerFunc { 9 | return func(context *gin.Context) { 10 | traceId := context.Request.Header.Get("trace_id") 11 | if traceId == "" { 12 | traceId = uuid.NewString() 13 | } 14 | context.Set("trace_id", traceId) 15 | context.Next() 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /model/article.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "context" 5 | "gorm.io/gorm" 6 | "time" 7 | ) 8 | 9 | var ArticleModel = Article{} 10 | 11 | type Article struct { 12 | Id int `json:"id" gorm:"primaryKey"` 13 | Title string `json:"title" binding:"min=1,max=100"` 14 | Content string `json:"content" binding:"required"` 15 | ViewNum int `json:"view_num"` 16 | CreatedAt time.Time `json:"created_at"` 17 | UpdatedAt time.Time `json:"updated_at"` 18 | DeletedAt *time.Time `json:"deleted_at"` 19 | } 20 | 21 | func (Article) TableName() string { 22 | return "articles" 23 | } 24 | 25 | type CreateArticleCommand struct { 26 | Id int 27 | Title string `form:"title" json:"title" binding:"gt=1,lt=100"` 28 | Content string `form:"content" json:"content" binding:"gt=1,lt=2000"` 29 | } 30 | 31 | type UpdateArticleCommand struct { 32 | Id int 33 | Title string `form:"title" json:"title" binding:"gt=1,lt=100"` 34 | Content string `form:"content" json:"content" binding:"gt=1,lt=2000"` 35 | } 36 | 37 | type CreateArticleCommentCommand struct { 38 | Id int `form:"id" json:"id"` 39 | Content string `form:"content" json:"content" binding:"gt=1,lt=2000"` 40 | } 41 | 42 | func (Article) GetAll(ctx context.Context, page, pageSize int) ([]*Article, int64, error) { 43 | var totalCount int64 44 | var articles []*Article 45 | err := NewOrm(ctx).Model(Article{}).Count(&totalCount). 46 | Limit(pageSize).Offset((page - 1) * pageSize).Order("id desc").Find(&articles).Error 47 | if err != nil { 48 | return nil, 0, err 49 | } 50 | return articles, totalCount, nil 51 | } 52 | 53 | func (Article) GetById(ctx context.Context, id int) (*Article, error) { 54 | var article Article 55 | err := NewOrm(ctx).Where("id = ?", id).First(&article).Error 56 | if err != nil { 57 | return nil, err 58 | } 59 | return &article, nil 60 | } 61 | 62 | func (Article) Create(ctx context.Context, param *CreateArticleCommand) (*Article, error) { 63 | article := Article{ 64 | Title: param.Title, 65 | Content: param.Content, 66 | CreatedAt: time.Now(), 67 | UpdatedAt: time.Now(), 68 | } 69 | err := NewOrm(ctx).Create(&article).Error 70 | if err != nil { 71 | return nil, err 72 | } 73 | return &article, nil 74 | } 75 | 76 | func (Article) Delete(ctx context.Context, id int) error { 77 | article := Article{ 78 | Id: id, 79 | } 80 | return NewOrm(ctx).Delete(&article).Error 81 | } 82 | 83 | func (Article) Update(ctx context.Context, param *UpdateArticleCommand) error { 84 | article := Article{ 85 | Id: param.Id, 86 | Title: param.Title, 87 | Content: param.Content, 88 | UpdatedAt: time.Now(), 89 | } 90 | return NewOrm(ctx).Updates(&article).Error 91 | } 92 | 93 | func (Article) CreateComment(ctx context.Context, param *CreateArticleCommentCommand) error { 94 | comment := Comment{ 95 | ArticleId: param.Id, 96 | Content: param.Content, 97 | CreatedAt: time.Now(), 98 | UpdatedAt: time.Now(), 99 | } 100 | return NewOrm(ctx).Create(&comment).Error 101 | } 102 | 103 | func (Article) AddViewNum(ctx context.Context, id int) error { 104 | return NewOrm(ctx).Model(Article{}).Where("id = ?", id). 105 | UpdateColumn("view_num", gorm.Expr("view_num + 1")).Error 106 | } 107 | -------------------------------------------------------------------------------- /model/comment.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import "time" 4 | 5 | type Comment struct { 6 | Id int `json:"id" gorm:"primaryKey"` 7 | ArticleId int `json:"article_id"` 8 | Content string `json:"content"` 9 | CreatedAt time.Time `json:"created_at"` 10 | UpdatedAt time.Time `json:"updated_at"` 11 | DeletedAt *time.Time `json:"deleted_at"` 12 | } 13 | 14 | func (Comment) TableName() string { 15 | return "comments" 16 | } 17 | -------------------------------------------------------------------------------- /model/db.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "gen/config" 7 | "gen/log" 8 | "gorm.io/driver/mysql" 9 | "gorm.io/gorm" 10 | "gorm.io/gorm/logger" 11 | "strings" 12 | ) 13 | 14 | var ( 15 | connPool = make(map[string]*gorm.DB) 16 | ) 17 | 18 | // NewOrm 默认返回default数据库连接 19 | func NewOrm(ctx context.Context, dbName ...string) *gorm.DB { 20 | conn := connPool["default"] 21 | if len(dbName) > 0 { 22 | if cn, ok := connPool[dbName[0]]; ok { 23 | conn = cn 24 | } 25 | } 26 | return conn.WithContext(ctx) 27 | } 28 | 29 | // Init 初始化数据库连接 30 | func Init(cfg *config.App) error { 31 | sections := cfg.Section("db").ChildSections() 32 | for _, v := range sections { 33 | var ( 34 | name = strings.TrimPrefix(v.Name(), "db.") 35 | dsn = v.Key("dsn").String() 36 | maxIdleConn = v.Key("max_idle_conn").MustInt(10) 37 | maxOpenConn = v.Key("max_open_conn").MustInt(30) 38 | ) 39 | conn, err := openConn(dsn, maxIdleConn, maxOpenConn) 40 | if err != nil { 41 | return fmt.Errorf("open db conn failed, error: %s", err.Error()) 42 | } 43 | connPool[name] = conn 44 | } 45 | return nil 46 | } 47 | 48 | func openConn(dsn string, idle, open int) (*gorm.DB, error) { 49 | newLogger := log.NewGormLogger(logger.Config{ 50 | LogLevel: logger.Info, 51 | }) 52 | openDB, err := gorm.Open(mysql.New(mysql.Config{DSN: dsn}), &gorm.Config{Logger: newLogger}) 53 | if err != nil { 54 | return nil, err 55 | } 56 | db, err := openDB.DB() 57 | if err != nil { 58 | return nil, err 59 | } 60 | db.SetMaxIdleConns(idle) 61 | db.SetMaxOpenConns(open) 62 | return openDB, nil 63 | } 64 | -------------------------------------------------------------------------------- /router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "gen/controller" 5 | "github.com/gin-gonic/gin" 6 | ) 7 | 8 | func RegisterRoutes(server *gin.Engine) { 9 | server.GET("/", controller.BaseController.Index) 10 | 11 | v1 := server.Group("/v1") 12 | articleCtrl := controller.ArticleController 13 | { 14 | v1.GET("/articles", articleCtrl.GetAll) //所有文章 15 | v1.POST("/articles", articleCtrl.Create) //添加文章 16 | v1.GET("/articles/:id", articleCtrl.GetById) //文章详情 17 | v1.PUT("/articles/:id", articleCtrl.Update) //修改文章 18 | v1.DELETE("/articles/:id", articleCtrl.Delete) //删除文章 19 | 20 | v1.GET("/articles/:id/comments", articleCtrl.AddComment) //获取文章评论 21 | v1.POST("/articles/:id/comments", articleCtrl.AddComment) //给文章添加评论 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /service/article_service.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "gen/log" 7 | . "gen/model" 8 | ) 9 | 10 | type ArticleService struct{} 11 | 12 | func NewArticleService() *ArticleService { 13 | return &ArticleService{} 14 | } 15 | 16 | func (r ArticleService) GetAll(ctx context.Context, page, pageSize int) ([]*Article, int64, error) { 17 | articles, totalCount, err := ArticleModel.GetAll(ctx, page, pageSize) 18 | if err != nil { 19 | return nil, 0, err 20 | } 21 | return articles, totalCount, nil 22 | } 23 | 24 | func (r ArticleService) GetById(ctx context.Context, id int) (*Article, error) { 25 | article, err := ArticleModel.GetById(ctx, id) 26 | if err != nil { 27 | return nil, err 28 | } 29 | go func() { 30 | err = ArticleModel.AddViewNum(ctx, id) 31 | if err != nil { 32 | log.WithCtx(ctx).Error(fmt.Sprintf("AddViewNum failed: %d", id)) 33 | } 34 | }() 35 | return article, nil 36 | } 37 | 38 | func (r ArticleService) Create(ctx context.Context, param *CreateArticleCommand) (*Article, error) { 39 | article, err := ArticleModel.Create(ctx, param) 40 | if err != nil { 41 | return nil, err 42 | } 43 | return article, nil 44 | } 45 | 46 | func (r ArticleService) Update(ctx context.Context, param *UpdateArticleCommand) error { 47 | _, err := ArticleModel.GetById(ctx, param.Id) 48 | if err != nil { 49 | return err 50 | } 51 | if err := ArticleModel.Update(ctx, param); err != nil { 52 | return err 53 | } 54 | return nil 55 | } 56 | 57 | func (r ArticleService) Delete(ctx context.Context, id int) error { 58 | _, err := ArticleModel.GetById(ctx, id) 59 | if err != nil { 60 | return err 61 | } 62 | if err = ArticleModel.Delete(ctx, id); err != nil { 63 | return err 64 | } 65 | return nil 66 | } 67 | 68 | func (r ArticleService) AddComment(ctx context.Context, param *CreateArticleCommentCommand) error { 69 | _, err := ArticleModel.GetById(ctx, param.Id) 70 | if err != nil { 71 | return err 72 | } 73 | if err := ArticleModel.CreateComment(ctx, param); err != nil { 74 | return err 75 | } 76 | return nil 77 | } 78 | -------------------------------------------------------------------------------- /storage/databases/blog.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `articles` 2 | ( 3 | `id` int(11) unsigned NOT NULL AUTO_INCREMENT, 4 | `title` varchar(100) NOT NULL COMMENT '标题', 5 | `content` varchar(2000) NOT NULL COMMENT '内容', 6 | `view_num` int(11) NOT NULL COMMENT '浏览次数', 7 | `created_at` datetime default NULL COMMENT '创建时间', 8 | `updated_at` datetime default NULL COMMENT '更新时间', 9 | `deleted_at` datetime default NULL COMMENT '删除时间', 10 | PRIMARY KEY (`id`) 11 | ) ENGINE = InnoDB 12 | DEFAULT CHARSET = utf8mb4 13 | COLLATE = utf8mb4_unicode_ci; 14 | 15 | CREATE TABLE `comments` 16 | ( 17 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 18 | `article_id` int(10) unsigned NOT NULL COMMENT '文字id', 19 | `content` varchar(500) NOT NULL COMMENT '评论内容', 20 | `created_at` datetime default NULL COMMENT '创建时间', 21 | `updated_at` datetime default NULL COMMENT '更新时间', 22 | `deleted_at` datetime default NULL COMMENT '删除时间', 23 | PRIMARY KEY (`id`) 24 | ) ENGINE = InnoDB 25 | DEFAULT CHARSET = utf8mb4 26 | COLLATE = utf8mb4_unicode_ci; -------------------------------------------------------------------------------- /util/const.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | const ( 4 | TimeFormatYmd = "2006-01-02" 5 | TimeFormatYmdHis = "2006-01-02 15:04:05" 6 | ) 7 | -------------------------------------------------------------------------------- /util/func.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "crypto/md5" 5 | "crypto/sha1" 6 | "encoding/hex" 7 | "fmt" 8 | "github.com/google/uuid" 9 | "hash" 10 | "io" 11 | ) 12 | 13 | func MD5(str []byte) string { 14 | h := md5.New() 15 | h.Write(str) 16 | return hex.EncodeToString(h.Sum(nil)) 17 | } 18 | 19 | func Sha1(str []byte) string { 20 | h := sha1.New() 21 | h.Write(str) 22 | return hex.EncodeToString(h.Sum(nil)) 23 | } 24 | 25 | // FileHash 计算文件hash 26 | func FileHash(reader io.Reader, tp string) string { 27 | var result []byte 28 | var h hash.Hash 29 | if tp == "md5" { 30 | h = md5.New() 31 | } else { 32 | h = sha1.New() 33 | } 34 | if _, err := io.Copy(h, reader); err != nil { 35 | return "" 36 | } 37 | return fmt.Sprintf("%x", h.Sum(result)) 38 | } 39 | 40 | // GetUuid 生成uuid 41 | func GetUuid() string { 42 | var u uuid.UUID 43 | var err error 44 | for i := 0; i < 3; i++ { 45 | u, err = uuid.NewUUID() 46 | if err == nil { 47 | return u.String() 48 | } 49 | } 50 | return "" 51 | } 52 | 53 | // GetUuidV4 生成uuid v4 54 | func GetUuidV4() string { 55 | var u uuid.UUID 56 | var err error 57 | for i := 0; i < 3; i++ { 58 | u, err = uuid.NewRandom() 59 | if err == nil { 60 | return u.String() 61 | } 62 | } 63 | return "" 64 | } 65 | --------------------------------------------------------------------------------