├── a.go ├── demo02 ├── README.md ├── conf │ └── config.yaml ├── router │ └── router.go └── config │ └── config.go ├── demo05 ├── README.md ├── pkg │ └── errno │ │ └── code.go ├── conf │ └── config.yaml ├── router │ └── router.go └── handler │ └── user │ └── create.go ├── demo09 ├── README.md ├── pkg │ ├── constvar │ │ └── constvar.go │ ├── auth │ │ └── auth.go │ └── errno │ │ ├── code.go │ │ └── errno.go ├── util │ └── util.go ├── router │ ├── middleware │ │ ├── auth.go │ │ └── requestid.go │ └── router.go ├── handler │ ├── user │ │ ├── delete.go │ │ ├── get.go │ │ ├── user.go │ │ ├── list.go │ │ ├── login.go │ │ ├── create.go │ │ └── update.go │ └── handler.go ├── conf │ └── config.yaml └── model │ └── model.go ├── demo16 ├── README.md ├── pkg │ ├── version │ │ ├── doc.go │ │ ├── base.go │ │ └── version.go │ ├── constvar │ │ └── constvar.go │ ├── auth │ │ └── auth.go │ └── errno │ │ ├── code.go │ │ └── errno.go ├── util │ ├── util.go │ └── util_test.go ├── router │ ├── middleware │ │ ├── auth.go │ │ └── requestid.go │ └── router.go ├── handler │ ├── user │ │ ├── delete.go │ │ ├── get.go │ │ ├── user.go │ │ ├── list.go │ │ ├── login.go │ │ ├── create.go │ │ └── update.go │ └── handler.go ├── conf │ └── config.yaml ├── model │ └── model.go ├── admin.sh └── Makefile ├── demo03 ├── README.md ├── conf │ └── config.yaml └── router │ └── router.go ├── demo06 ├── README.md ├── handler │ ├── user │ │ ├── user.go │ │ └── create.go │ └── handler.go ├── pkg │ └── errno │ │ └── code.go ├── conf │ └── config.yaml └── router │ └── router.go ├── demo07 ├── README.md ├── pkg │ ├── constvar │ │ └── constvar.go │ ├── auth │ │ └── auth.go │ └── errno │ │ ├── code.go │ │ └── errno.go ├── util │ └── util.go ├── handler │ ├── user │ │ ├── delete.go │ │ ├── get.go │ │ ├── user.go │ │ ├── list.go │ │ ├── create.go │ │ └── update.go │ └── handler.go ├── conf │ └── config.yaml ├── model │ └── model.go └── router │ └── router.go ├── demo10 ├── README.md ├── pkg │ ├── constvar │ │ └── constvar.go │ ├── auth │ │ └── auth.go │ └── errno │ │ ├── code.go │ │ └── errno.go ├── util │ └── util.go ├── router │ ├── middleware │ │ ├── auth.go │ │ └── requestid.go │ └── router.go ├── handler │ ├── user │ │ ├── delete.go │ │ ├── get.go │ │ ├── user.go │ │ ├── list.go │ │ ├── login.go │ │ ├── create.go │ │ └── update.go │ └── handler.go ├── conf │ ├── config.yaml │ └── server.crt └── model │ └── model.go ├── demo12 ├── README.md ├── pkg │ ├── version │ │ ├── doc.go │ │ ├── base.go │ │ └── version.go │ ├── constvar │ │ └── constvar.go │ ├── auth │ │ └── auth.go │ └── errno │ │ ├── code.go │ │ └── errno.go ├── util │ └── util.go ├── router │ ├── middleware │ │ ├── auth.go │ │ └── requestid.go │ └── router.go ├── handler │ ├── user │ │ ├── delete.go │ │ ├── get.go │ │ ├── user.go │ │ ├── list.go │ │ ├── login.go │ │ ├── create.go │ │ └── update.go │ └── handler.go ├── conf │ ├── config.yaml │ └── server.crt ├── model │ └── model.go └── Makefile ├── demo13 ├── README.md ├── pkg │ ├── version │ │ ├── doc.go │ │ ├── base.go │ │ └── version.go │ ├── constvar │ │ └── constvar.go │ ├── auth │ │ └── auth.go │ └── errno │ │ ├── code.go │ │ └── errno.go ├── util │ └── util.go ├── router │ ├── middleware │ │ ├── auth.go │ │ └── requestid.go │ └── router.go ├── handler │ ├── user │ │ ├── delete.go │ │ ├── get.go │ │ ├── user.go │ │ ├── list.go │ │ ├── login.go │ │ ├── create.go │ │ └── update.go │ └── handler.go ├── conf │ └── config.yaml ├── model │ └── model.go ├── admin.sh └── Makefile ├── demo15 ├── README.md ├── pkg │ ├── version │ │ ├── doc.go │ │ ├── base.go │ │ └── version.go │ ├── constvar │ │ └── constvar.go │ ├── auth │ │ └── auth.go │ └── errno │ │ ├── code.go │ │ └── errno.go ├── util │ ├── util.go │ └── util_test.go ├── router │ ├── middleware │ │ ├── auth.go │ │ └── requestid.go │ └── router.go ├── handler │ ├── user │ │ ├── delete.go │ │ ├── get.go │ │ ├── user.go │ │ ├── list.go │ │ ├── login.go │ │ ├── create.go │ │ └── update.go │ └── handler.go ├── conf │ └── config.yaml ├── model │ └── model.go ├── admin.sh └── Makefile ├── demo17 ├── README.md ├── pkg │ ├── version │ │ ├── doc.go │ │ ├── base.go │ │ └── version.go │ ├── constvar │ │ └── constvar.go │ ├── auth │ │ └── auth.go │ └── errno │ │ ├── code.go │ │ └── errno.go ├── util │ ├── util.go │ └── util_test.go ├── router │ └── middleware │ │ ├── auth.go │ │ └── requestid.go ├── handler │ ├── handler.go │ └── user │ │ ├── user.go │ │ ├── delete.go │ │ ├── get.go │ │ └── list.go ├── conf │ └── config.yaml ├── model │ └── model.go ├── admin.sh └── Makefile ├── demo04 ├── README.md ├── conf │ └── config.yaml └── router │ └── router.go ├── demo08 ├── README.md ├── pkg │ ├── constvar │ │ └── constvar.go │ ├── auth │ │ └── auth.go │ └── errno │ │ ├── code.go │ │ └── errno.go ├── util │ └── util.go ├── handler │ ├── user │ │ ├── delete.go │ │ ├── get.go │ │ ├── user.go │ │ ├── list.go │ │ ├── create.go │ │ └── update.go │ └── handler.go ├── router │ ├── middleware │ │ └── requestid.go │ └── router.go ├── conf │ └── config.yaml └── model │ └── model.go ├── demo11 ├── README.md ├── pkg │ ├── constvar │ │ └── constvar.go │ ├── auth │ │ └── auth.go │ └── errno │ │ ├── code.go │ │ └── errno.go ├── util │ └── util.go ├── router │ ├── middleware │ │ ├── auth.go │ │ └── requestid.go │ └── router.go ├── handler │ ├── user │ │ ├── delete.go │ │ ├── get.go │ │ ├── user.go │ │ ├── list.go │ │ ├── login.go │ │ ├── create.go │ │ └── update.go │ └── handler.go ├── Makefile ├── conf │ ├── config.yaml │ └── server.crt └── model │ └── model.go ├── demo14 ├── README.md ├── pkg │ ├── version │ │ ├── doc.go │ │ ├── base.go │ │ └── version.go │ ├── constvar │ │ └── constvar.go │ ├── auth │ │ └── auth.go │ └── errno │ │ ├── code.go │ │ └── errno.go ├── util │ └── util.go ├── router │ ├── middleware │ │ ├── auth.go │ │ └── requestid.go │ └── router.go ├── handler │ ├── user │ │ ├── delete.go │ │ ├── get.go │ │ ├── user.go │ │ ├── list.go │ │ ├── login.go │ │ ├── create.go │ │ └── update.go │ └── handler.go ├── conf │ └── config.yaml ├── model │ └── model.go ├── admin.sh └── Makefile ├── demo01 ├── README.md ├── router │ └── router.go └── main.go ├── docs └── 技术雷达.png ├── Makefile └── README.md /a.go: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /demo02/README.md: -------------------------------------------------------------------------------- 1 | 实战:配置文件读取 2 | -------------------------------------------------------------------------------- /demo05/README.md: -------------------------------------------------------------------------------- 1 | 实战:自定义业务错误信息 2 | -------------------------------------------------------------------------------- /demo09/README.md: -------------------------------------------------------------------------------- 1 | 实战:API身份验证 2 | -------------------------------------------------------------------------------- /demo16/README.md: -------------------------------------------------------------------------------- 1 | 进阶:API性能分析 2 | -------------------------------------------------------------------------------- /demo03/README.md: -------------------------------------------------------------------------------- 1 | 实战:记录和管理API日志 2 | -------------------------------------------------------------------------------- /demo06/README.md: -------------------------------------------------------------------------------- 1 | 实战:读取和返回HTTP请求 2 | -------------------------------------------------------------------------------- /demo07/README.md: -------------------------------------------------------------------------------- 1 | 实战:用户业务逻辑处理(业务处理) 2 | -------------------------------------------------------------------------------- /demo10/README.md: -------------------------------------------------------------------------------- 1 | 进阶:用HTTPS加密API请求 2 | -------------------------------------------------------------------------------- /demo12/README.md: -------------------------------------------------------------------------------- 1 | 进阶:给API命令增加版本功能 2 | -------------------------------------------------------------------------------- /demo13/README.md: -------------------------------------------------------------------------------- 1 | 进阶:给API增加启动脚本 2 | -------------------------------------------------------------------------------- /demo15/README.md: -------------------------------------------------------------------------------- 1 | 进阶:go test测试你的代码 2 | -------------------------------------------------------------------------------- /demo17/README.md: -------------------------------------------------------------------------------- 1 | 进阶:生成Swagger在线文档 2 | -------------------------------------------------------------------------------- /demo04/README.md: -------------------------------------------------------------------------------- 1 | 实战:初始化Mysql数据库并建立连接 2 | -------------------------------------------------------------------------------- /demo08/README.md: -------------------------------------------------------------------------------- 1 | 实战:HTTP调用添加自定义处理逻辑 2 | -------------------------------------------------------------------------------- /demo11/README.md: -------------------------------------------------------------------------------- 1 | 进阶:用Makefile管理API项目 2 | -------------------------------------------------------------------------------- /demo14/README.md: -------------------------------------------------------------------------------- 1 | 进阶:基于Nginx的API部署方案 2 | -------------------------------------------------------------------------------- /demo01/README.md: -------------------------------------------------------------------------------- 1 | 实战:启动一个最简单的RESTful API服务器 2 | -------------------------------------------------------------------------------- /demo12/pkg/version/doc.go: -------------------------------------------------------------------------------- 1 | package version 2 | -------------------------------------------------------------------------------- /demo13/pkg/version/doc.go: -------------------------------------------------------------------------------- 1 | package version 2 | -------------------------------------------------------------------------------- /demo14/pkg/version/doc.go: -------------------------------------------------------------------------------- 1 | package version 2 | -------------------------------------------------------------------------------- /demo15/pkg/version/doc.go: -------------------------------------------------------------------------------- 1 | package version 2 | -------------------------------------------------------------------------------- /demo16/pkg/version/doc.go: -------------------------------------------------------------------------------- 1 | package version 2 | -------------------------------------------------------------------------------- /demo17/pkg/version/doc.go: -------------------------------------------------------------------------------- 1 | package version 2 | -------------------------------------------------------------------------------- /docs/技术雷达.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lexkong/apiserver_demos/HEAD/docs/技术雷达.png -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | clean: 2 | find . -name "[._]*.s[a-w][a-z]" | xargs -i rm -f {} 3 | .PHONY: clean 4 | -------------------------------------------------------------------------------- /demo07/pkg/constvar/constvar.go: -------------------------------------------------------------------------------- 1 | package constvar 2 | 3 | const ( 4 | DefaultLimit = 50 5 | ) 6 | -------------------------------------------------------------------------------- /demo08/pkg/constvar/constvar.go: -------------------------------------------------------------------------------- 1 | package constvar 2 | 3 | const ( 4 | DefaultLimit = 50 5 | ) 6 | -------------------------------------------------------------------------------- /demo09/pkg/constvar/constvar.go: -------------------------------------------------------------------------------- 1 | package constvar 2 | 3 | const ( 4 | DefaultLimit = 50 5 | ) 6 | -------------------------------------------------------------------------------- /demo10/pkg/constvar/constvar.go: -------------------------------------------------------------------------------- 1 | package constvar 2 | 3 | const ( 4 | DefaultLimit = 50 5 | ) 6 | -------------------------------------------------------------------------------- /demo11/pkg/constvar/constvar.go: -------------------------------------------------------------------------------- 1 | package constvar 2 | 3 | const ( 4 | DefaultLimit = 50 5 | ) 6 | -------------------------------------------------------------------------------- /demo12/pkg/constvar/constvar.go: -------------------------------------------------------------------------------- 1 | package constvar 2 | 3 | const ( 4 | DefaultLimit = 50 5 | ) 6 | -------------------------------------------------------------------------------- /demo13/pkg/constvar/constvar.go: -------------------------------------------------------------------------------- 1 | package constvar 2 | 3 | const ( 4 | DefaultLimit = 50 5 | ) 6 | -------------------------------------------------------------------------------- /demo14/pkg/constvar/constvar.go: -------------------------------------------------------------------------------- 1 | package constvar 2 | 3 | const ( 4 | DefaultLimit = 50 5 | ) 6 | -------------------------------------------------------------------------------- /demo15/pkg/constvar/constvar.go: -------------------------------------------------------------------------------- 1 | package constvar 2 | 3 | const ( 4 | DefaultLimit = 50 5 | ) 6 | -------------------------------------------------------------------------------- /demo16/pkg/constvar/constvar.go: -------------------------------------------------------------------------------- 1 | package constvar 2 | 3 | const ( 4 | DefaultLimit = 50 5 | ) 6 | -------------------------------------------------------------------------------- /demo17/pkg/constvar/constvar.go: -------------------------------------------------------------------------------- 1 | package constvar 2 | 3 | const ( 4 | DefaultLimit = 50 5 | ) 6 | -------------------------------------------------------------------------------- /demo06/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | type CreateRequest struct { 4 | Username string `json:"username"` 5 | Password string `json:"password"` 6 | } 7 | 8 | type CreateResponse struct { 9 | Username string `json:"username"` 10 | } 11 | -------------------------------------------------------------------------------- /demo02/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | -------------------------------------------------------------------------------- /demo12/pkg/version/base.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | var ( 4 | gitTag string = "" 5 | gitCommit string = "$Format:%H$" // sha1 from git, output of $(git rev-parse HEAD) 6 | gitTreeState string = "not a git tree" // state of git tree, either "clean" or "dirty" 7 | buildDate string = "1970-01-01T00:00:00Z" // build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ') 8 | ) 9 | -------------------------------------------------------------------------------- /demo13/pkg/version/base.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | var ( 4 | gitTag string = "" 5 | gitCommit string = "$Format:%H$" // sha1 from git, output of $(git rev-parse HEAD) 6 | gitTreeState string = "not a git tree" // state of git tree, either "clean" or "dirty" 7 | buildDate string = "1970-01-01T00:00:00Z" // build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ') 8 | ) 9 | -------------------------------------------------------------------------------- /demo14/pkg/version/base.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | var ( 4 | gitTag string = "" 5 | gitCommit string = "$Format:%H$" // sha1 from git, output of $(git rev-parse HEAD) 6 | gitTreeState string = "not a git tree" // state of git tree, either "clean" or "dirty" 7 | buildDate string = "1970-01-01T00:00:00Z" // build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ') 8 | ) 9 | -------------------------------------------------------------------------------- /demo15/pkg/version/base.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | var ( 4 | gitTag string = "" 5 | gitCommit string = "$Format:%H$" // sha1 from git, output of $(git rev-parse HEAD) 6 | gitTreeState string = "not a git tree" // state of git tree, either "clean" or "dirty" 7 | buildDate string = "1970-01-01T00:00:00Z" // build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ') 8 | ) 9 | -------------------------------------------------------------------------------- /demo16/pkg/version/base.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | var ( 4 | gitTag string = "" 5 | gitCommit string = "$Format:%H$" // sha1 from git, output of $(git rev-parse HEAD) 6 | gitTreeState string = "not a git tree" // state of git tree, either "clean" or "dirty" 7 | buildDate string = "1970-01-01T00:00:00Z" // build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ') 8 | ) 9 | -------------------------------------------------------------------------------- /demo17/pkg/version/base.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | var ( 4 | gitTag string = "" 5 | gitCommit string = "$Format:%H$" // sha1 from git, output of $(git rev-parse HEAD) 6 | gitTreeState string = "not a git tree" // state of git tree, either "clean" or "dirty" 7 | buildDate string = "1970-01-01T00:00:00Z" // build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ') 8 | ) 9 | -------------------------------------------------------------------------------- /demo07/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/teris-io/shortid" 6 | ) 7 | 8 | func GenShortId() (string, error) { 9 | return shortid.Generate() 10 | } 11 | 12 | func GetReqID(c *gin.Context) string { 13 | v, ok := c.Get("X-Request-Id") 14 | if !ok { 15 | return "" 16 | } 17 | if requestId, ok := v.(string); ok { 18 | return requestId 19 | } 20 | return "" 21 | } 22 | -------------------------------------------------------------------------------- /demo08/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/teris-io/shortid" 6 | ) 7 | 8 | func GenShortId() (string, error) { 9 | return shortid.Generate() 10 | } 11 | 12 | func GetReqID(c *gin.Context) string { 13 | v, ok := c.Get("X-Request-Id") 14 | if !ok { 15 | return "" 16 | } 17 | if requestId, ok := v.(string); ok { 18 | return requestId 19 | } 20 | return "" 21 | } 22 | -------------------------------------------------------------------------------- /demo09/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/teris-io/shortid" 6 | ) 7 | 8 | func GenShortId() (string, error) { 9 | return shortid.Generate() 10 | } 11 | 12 | func GetReqID(c *gin.Context) string { 13 | v, ok := c.Get("X-Request-Id") 14 | if !ok { 15 | return "" 16 | } 17 | if requestId, ok := v.(string); ok { 18 | return requestId 19 | } 20 | return "" 21 | } 22 | -------------------------------------------------------------------------------- /demo10/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/teris-io/shortid" 6 | ) 7 | 8 | func GenShortId() (string, error) { 9 | return shortid.Generate() 10 | } 11 | 12 | func GetReqID(c *gin.Context) string { 13 | v, ok := c.Get("X-Request-Id") 14 | if !ok { 15 | return "" 16 | } 17 | if requestId, ok := v.(string); ok { 18 | return requestId 19 | } 20 | return "" 21 | } 22 | -------------------------------------------------------------------------------- /demo11/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/teris-io/shortid" 6 | ) 7 | 8 | func GenShortId() (string, error) { 9 | return shortid.Generate() 10 | } 11 | 12 | func GetReqID(c *gin.Context) string { 13 | v, ok := c.Get("X-Request-Id") 14 | if !ok { 15 | return "" 16 | } 17 | if requestId, ok := v.(string); ok { 18 | return requestId 19 | } 20 | return "" 21 | } 22 | -------------------------------------------------------------------------------- /demo12/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/teris-io/shortid" 6 | ) 7 | 8 | func GenShortId() (string, error) { 9 | return shortid.Generate() 10 | } 11 | 12 | func GetReqID(c *gin.Context) string { 13 | v, ok := c.Get("X-Request-Id") 14 | if !ok { 15 | return "" 16 | } 17 | if requestId, ok := v.(string); ok { 18 | return requestId 19 | } 20 | return "" 21 | } 22 | -------------------------------------------------------------------------------- /demo13/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/teris-io/shortid" 6 | ) 7 | 8 | func GenShortId() (string, error) { 9 | return shortid.Generate() 10 | } 11 | 12 | func GetReqID(c *gin.Context) string { 13 | v, ok := c.Get("X-Request-Id") 14 | if !ok { 15 | return "" 16 | } 17 | if requestId, ok := v.(string); ok { 18 | return requestId 19 | } 20 | return "" 21 | } 22 | -------------------------------------------------------------------------------- /demo14/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/teris-io/shortid" 6 | ) 7 | 8 | func GenShortId() (string, error) { 9 | return shortid.Generate() 10 | } 11 | 12 | func GetReqID(c *gin.Context) string { 13 | v, ok := c.Get("X-Request-Id") 14 | if !ok { 15 | return "" 16 | } 17 | if requestId, ok := v.(string); ok { 18 | return requestId 19 | } 20 | return "" 21 | } 22 | -------------------------------------------------------------------------------- /demo15/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/teris-io/shortid" 6 | ) 7 | 8 | func GenShortId() (string, error) { 9 | return shortid.Generate() 10 | } 11 | 12 | func GetReqID(c *gin.Context) string { 13 | v, ok := c.Get("X-Request-Id") 14 | if !ok { 15 | return "" 16 | } 17 | if requestId, ok := v.(string); ok { 18 | return requestId 19 | } 20 | return "" 21 | } 22 | -------------------------------------------------------------------------------- /demo16/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/teris-io/shortid" 6 | ) 7 | 8 | func GenShortId() (string, error) { 9 | return shortid.Generate() 10 | } 11 | 12 | func GetReqID(c *gin.Context) string { 13 | v, ok := c.Get("X-Request-Id") 14 | if !ok { 15 | return "" 16 | } 17 | if requestId, ok := v.(string); ok { 18 | return requestId 19 | } 20 | return "" 21 | } 22 | -------------------------------------------------------------------------------- /demo17/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/teris-io/shortid" 6 | ) 7 | 8 | func GenShortId() (string, error) { 9 | return shortid.Generate() 10 | } 11 | 12 | func GetReqID(c *gin.Context) string { 13 | v, ok := c.Get("X-Request-Id") 14 | if !ok { 15 | return "" 16 | } 17 | if requestId, ok := v.(string); ok { 18 | return requestId 19 | } 20 | return "" 21 | } 22 | -------------------------------------------------------------------------------- /demo05/pkg/errno/code.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | var ( 4 | // Common errors 5 | OK = &Errno{Code: 0, Message: "OK"} 6 | InternalServerError = &Errno{Code: 10001, Message: "Internal server error."} 7 | ErrBind = &Errno{Code: 10002, Message: "Error occurred while binding the request body to the struct."} 8 | 9 | // user errors 10 | ErrUserNotFound = &Errno{Code: 20102, Message: "The user was not found."} 11 | ) 12 | -------------------------------------------------------------------------------- /demo06/pkg/errno/code.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | var ( 4 | // Common errors 5 | OK = &Errno{Code: 0, Message: "OK"} 6 | InternalServerError = &Errno{Code: 10001, Message: "Internal server error."} 7 | ErrBind = &Errno{Code: 10002, Message: "Error occurred while binding the request body to the struct."} 8 | 9 | // user errors 10 | ErrUserNotFound = &Errno{Code: 20102, Message: "The user was not found."} 11 | ) 12 | -------------------------------------------------------------------------------- /demo09/router/middleware/auth.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/pkg/token" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | func AuthMiddleware() gin.HandlerFunc { 12 | return func(c *gin.Context) { 13 | // Parse the json web token. 14 | if _, err := token.ParseRequest(c); err != nil { 15 | handler.SendResponse(c, errno.ErrTokenInvalid, nil) 16 | c.Abort() 17 | return 18 | } 19 | 20 | c.Next() 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /demo10/router/middleware/auth.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/pkg/token" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | func AuthMiddleware() gin.HandlerFunc { 12 | return func(c *gin.Context) { 13 | // Parse the json web token. 14 | if _, err := token.ParseRequest(c); err != nil { 15 | handler.SendResponse(c, errno.ErrTokenInvalid, nil) 16 | c.Abort() 17 | return 18 | } 19 | 20 | c.Next() 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /demo11/router/middleware/auth.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/pkg/token" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | func AuthMiddleware() gin.HandlerFunc { 12 | return func(c *gin.Context) { 13 | // Parse the json web token. 14 | if _, err := token.ParseRequest(c); err != nil { 15 | handler.SendResponse(c, errno.ErrTokenInvalid, nil) 16 | c.Abort() 17 | return 18 | } 19 | 20 | c.Next() 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /demo12/router/middleware/auth.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/pkg/token" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | func AuthMiddleware() gin.HandlerFunc { 12 | return func(c *gin.Context) { 13 | // Parse the json web token. 14 | if _, err := token.ParseRequest(c); err != nil { 15 | handler.SendResponse(c, errno.ErrTokenInvalid, nil) 16 | c.Abort() 17 | return 18 | } 19 | 20 | c.Next() 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /demo13/router/middleware/auth.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/pkg/token" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | func AuthMiddleware() gin.HandlerFunc { 12 | return func(c *gin.Context) { 13 | // Parse the json web token. 14 | if _, err := token.ParseRequest(c); err != nil { 15 | handler.SendResponse(c, errno.ErrTokenInvalid, nil) 16 | c.Abort() 17 | return 18 | } 19 | 20 | c.Next() 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /demo14/router/middleware/auth.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/pkg/token" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | func AuthMiddleware() gin.HandlerFunc { 12 | return func(c *gin.Context) { 13 | // Parse the json web token. 14 | if _, err := token.ParseRequest(c); err != nil { 15 | handler.SendResponse(c, errno.ErrTokenInvalid, nil) 16 | c.Abort() 17 | return 18 | } 19 | 20 | c.Next() 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /demo15/router/middleware/auth.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/pkg/token" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | func AuthMiddleware() gin.HandlerFunc { 12 | return func(c *gin.Context) { 13 | // Parse the json web token. 14 | if _, err := token.ParseRequest(c); err != nil { 15 | handler.SendResponse(c, errno.ErrTokenInvalid, nil) 16 | c.Abort() 17 | return 18 | } 19 | 20 | c.Next() 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /demo16/router/middleware/auth.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/pkg/token" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | func AuthMiddleware() gin.HandlerFunc { 12 | return func(c *gin.Context) { 13 | // Parse the json web token. 14 | if _, err := token.ParseRequest(c); err != nil { 15 | handler.SendResponse(c, errno.ErrTokenInvalid, nil) 16 | c.Abort() 17 | return 18 | } 19 | 20 | c.Next() 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /demo17/router/middleware/auth.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/pkg/token" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | func AuthMiddleware() gin.HandlerFunc { 12 | return func(c *gin.Context) { 13 | // Parse the json web token. 14 | if _, err := token.ParseRequest(c); err != nil { 15 | handler.SendResponse(c, errno.ErrTokenInvalid, nil) 16 | c.Abort() 17 | return 18 | } 19 | 20 | c.Next() 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /demo07/handler/user/delete.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Delete delete an user by the user identifier. 14 | func Delete(c *gin.Context) { 15 | userId, _ := strconv.Atoi(c.Param("id")) 16 | if err := model.DeleteUser(uint64(userId)); err != nil { 17 | SendResponse(c, errno.ErrDatabase, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, nil) 22 | } 23 | -------------------------------------------------------------------------------- /demo08/handler/user/delete.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Delete delete an user by the user identifier. 14 | func Delete(c *gin.Context) { 15 | userId, _ := strconv.Atoi(c.Param("id")) 16 | if err := model.DeleteUser(uint64(userId)); err != nil { 17 | SendResponse(c, errno.ErrDatabase, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, nil) 22 | } 23 | -------------------------------------------------------------------------------- /demo09/handler/user/delete.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Delete delete an user by the user identifier. 14 | func Delete(c *gin.Context) { 15 | userId, _ := strconv.Atoi(c.Param("id")) 16 | if err := model.DeleteUser(uint64(userId)); err != nil { 17 | SendResponse(c, errno.ErrDatabase, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, nil) 22 | } 23 | -------------------------------------------------------------------------------- /demo10/handler/user/delete.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Delete delete an user by the user identifier. 14 | func Delete(c *gin.Context) { 15 | userId, _ := strconv.Atoi(c.Param("id")) 16 | if err := model.DeleteUser(uint64(userId)); err != nil { 17 | SendResponse(c, errno.ErrDatabase, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, nil) 22 | } 23 | -------------------------------------------------------------------------------- /demo11/handler/user/delete.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Delete delete an user by the user identifier. 14 | func Delete(c *gin.Context) { 15 | userId, _ := strconv.Atoi(c.Param("id")) 16 | if err := model.DeleteUser(uint64(userId)); err != nil { 17 | SendResponse(c, errno.ErrDatabase, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, nil) 22 | } 23 | -------------------------------------------------------------------------------- /demo12/handler/user/delete.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Delete delete an user by the user identifier. 14 | func Delete(c *gin.Context) { 15 | userId, _ := strconv.Atoi(c.Param("id")) 16 | if err := model.DeleteUser(uint64(userId)); err != nil { 17 | SendResponse(c, errno.ErrDatabase, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, nil) 22 | } 23 | -------------------------------------------------------------------------------- /demo13/handler/user/delete.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Delete delete an user by the user identifier. 14 | func Delete(c *gin.Context) { 15 | userId, _ := strconv.Atoi(c.Param("id")) 16 | if err := model.DeleteUser(uint64(userId)); err != nil { 17 | SendResponse(c, errno.ErrDatabase, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, nil) 22 | } 23 | -------------------------------------------------------------------------------- /demo14/handler/user/delete.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Delete delete an user by the user identifier. 14 | func Delete(c *gin.Context) { 15 | userId, _ := strconv.Atoi(c.Param("id")) 16 | if err := model.DeleteUser(uint64(userId)); err != nil { 17 | SendResponse(c, errno.ErrDatabase, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, nil) 22 | } 23 | -------------------------------------------------------------------------------- /demo15/handler/user/delete.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Delete delete an user by the user identifier. 14 | func Delete(c *gin.Context) { 15 | userId, _ := strconv.Atoi(c.Param("id")) 16 | if err := model.DeleteUser(uint64(userId)); err != nil { 17 | SendResponse(c, errno.ErrDatabase, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, nil) 22 | } 23 | -------------------------------------------------------------------------------- /demo16/handler/user/delete.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Delete delete an user by the user identifier. 14 | func Delete(c *gin.Context) { 15 | userId, _ := strconv.Atoi(c.Param("id")) 16 | if err := model.DeleteUser(uint64(userId)); err != nil { 17 | SendResponse(c, errno.ErrDatabase, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, nil) 22 | } 23 | -------------------------------------------------------------------------------- /demo03/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | log: 7 | writers: file,stdout 8 | logger_level: DEBUG 9 | logger_file: log/apiserver.log 10 | log_format_text: false 11 | rollingPolicy: size 12 | log_rotate_date: 1 13 | log_rotate_size: 1 14 | log_backup_count: 7 15 | -------------------------------------------------------------------------------- /demo04/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | log: 7 | writers: file,stdout 8 | logger_level: DEBUG 9 | logger_file: log/apiserver.log 10 | log_format_text: false 11 | rollingPolicy: size 12 | log_rotate_date: 1 13 | log_rotate_size: 1 14 | log_backup_count: 7 15 | -------------------------------------------------------------------------------- /demo05/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | log: 7 | writers: file,stdout 8 | logger_level: DEBUG 9 | logger_file: log/apiserver.log 10 | log_format_text: false 11 | rollingPolicy: size 12 | log_rotate_date: 1 13 | log_rotate_size: 1 14 | log_backup_count: 7 15 | -------------------------------------------------------------------------------- /demo06/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | log: 7 | writers: file,stdout 8 | logger_level: DEBUG 9 | logger_file: log/apiserver.log 10 | log_format_text: false 11 | rollingPolicy: size 12 | log_rotate_date: 1 13 | log_rotate_size: 1 14 | log_backup_count: 7 15 | -------------------------------------------------------------------------------- /demo07/handler/user/get.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // Get gets an user by the user identifier. 12 | func Get(c *gin.Context) { 13 | username := c.Param("username") 14 | // Get the user by the `username` from the database. 15 | user, err := model.GetUser(username) 16 | if err != nil { 17 | SendResponse(c, errno.ErrUserNotFound, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, user) 22 | } 23 | -------------------------------------------------------------------------------- /demo08/handler/user/get.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // Get gets an user by the user identifier. 12 | func Get(c *gin.Context) { 13 | username := c.Param("username") 14 | // Get the user by the `username` from the database. 15 | user, err := model.GetUser(username) 16 | if err != nil { 17 | SendResponse(c, errno.ErrUserNotFound, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, user) 22 | } 23 | -------------------------------------------------------------------------------- /demo09/handler/user/get.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // Get gets an user by the user identifier. 12 | func Get(c *gin.Context) { 13 | username := c.Param("username") 14 | // Get the user by the `username` from the database. 15 | user, err := model.GetUser(username) 16 | if err != nil { 17 | SendResponse(c, errno.ErrUserNotFound, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, user) 22 | } 23 | -------------------------------------------------------------------------------- /demo10/handler/user/get.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // Get gets an user by the user identifier. 12 | func Get(c *gin.Context) { 13 | username := c.Param("username") 14 | // Get the user by the `username` from the database. 15 | user, err := model.GetUser(username) 16 | if err != nil { 17 | SendResponse(c, errno.ErrUserNotFound, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, user) 22 | } 23 | -------------------------------------------------------------------------------- /demo11/handler/user/get.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // Get gets an user by the user identifier. 12 | func Get(c *gin.Context) { 13 | username := c.Param("username") 14 | // Get the user by the `username` from the database. 15 | user, err := model.GetUser(username) 16 | if err != nil { 17 | SendResponse(c, errno.ErrUserNotFound, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, user) 22 | } 23 | -------------------------------------------------------------------------------- /demo12/handler/user/get.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // Get gets an user by the user identifier. 12 | func Get(c *gin.Context) { 13 | username := c.Param("username") 14 | // Get the user by the `username` from the database. 15 | user, err := model.GetUser(username) 16 | if err != nil { 17 | SendResponse(c, errno.ErrUserNotFound, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, user) 22 | } 23 | -------------------------------------------------------------------------------- /demo13/handler/user/get.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // Get gets an user by the user identifier. 12 | func Get(c *gin.Context) { 13 | username := c.Param("username") 14 | // Get the user by the `username` from the database. 15 | user, err := model.GetUser(username) 16 | if err != nil { 17 | SendResponse(c, errno.ErrUserNotFound, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, user) 22 | } 23 | -------------------------------------------------------------------------------- /demo14/handler/user/get.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // Get gets an user by the user identifier. 12 | func Get(c *gin.Context) { 13 | username := c.Param("username") 14 | // Get the user by the `username` from the database. 15 | user, err := model.GetUser(username) 16 | if err != nil { 17 | SendResponse(c, errno.ErrUserNotFound, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, user) 22 | } 23 | -------------------------------------------------------------------------------- /demo15/handler/user/get.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // Get gets an user by the user identifier. 12 | func Get(c *gin.Context) { 13 | username := c.Param("username") 14 | // Get the user by the `username` from the database. 15 | user, err := model.GetUser(username) 16 | if err != nil { 17 | SendResponse(c, errno.ErrUserNotFound, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, user) 22 | } 23 | -------------------------------------------------------------------------------- /demo16/handler/user/get.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // Get gets an user by the user identifier. 12 | func Get(c *gin.Context) { 13 | username := c.Param("username") 14 | // Get the user by the `username` from the database. 15 | user, err := model.GetUser(username) 16 | if err != nil { 17 | SendResponse(c, errno.ErrUserNotFound, nil) 18 | return 19 | } 20 | 21 | SendResponse(c, nil, user) 22 | } 23 | -------------------------------------------------------------------------------- /demo07/pkg/auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import "golang.org/x/crypto/bcrypt" 4 | 5 | // Encrypt encrypts the plain text with bcrypt. 6 | func Encrypt(source string) (string, error) { 7 | hashedBytes, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost) 8 | return string(hashedBytes), err 9 | } 10 | 11 | // Compare compares the encrypted text with the plain text if it's the same. 12 | func Compare(hashedPassword, password string) error { 13 | return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) 14 | } 15 | -------------------------------------------------------------------------------- /demo08/pkg/auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import "golang.org/x/crypto/bcrypt" 4 | 5 | // Encrypt encrypts the plain text with bcrypt. 6 | func Encrypt(source string) (string, error) { 7 | hashedBytes, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost) 8 | return string(hashedBytes), err 9 | } 10 | 11 | // Compare compares the encrypted text with the plain text if it's the same. 12 | func Compare(hashedPassword, password string) error { 13 | return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) 14 | } 15 | -------------------------------------------------------------------------------- /demo09/pkg/auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import "golang.org/x/crypto/bcrypt" 4 | 5 | // Encrypt encrypts the plain text with bcrypt. 6 | func Encrypt(source string) (string, error) { 7 | hashedBytes, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost) 8 | return string(hashedBytes), err 9 | } 10 | 11 | // Compare compares the encrypted text with the plain text if it's the same. 12 | func Compare(hashedPassword, password string) error { 13 | return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) 14 | } 15 | -------------------------------------------------------------------------------- /demo10/pkg/auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import "golang.org/x/crypto/bcrypt" 4 | 5 | // Encrypt encrypts the plain text with bcrypt. 6 | func Encrypt(source string) (string, error) { 7 | hashedBytes, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost) 8 | return string(hashedBytes), err 9 | } 10 | 11 | // Compare compares the encrypted text with the plain text if it's the same. 12 | func Compare(hashedPassword, password string) error { 13 | return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) 14 | } 15 | -------------------------------------------------------------------------------- /demo11/pkg/auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import "golang.org/x/crypto/bcrypt" 4 | 5 | // Encrypt encrypts the plain text with bcrypt. 6 | func Encrypt(source string) (string, error) { 7 | hashedBytes, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost) 8 | return string(hashedBytes), err 9 | } 10 | 11 | // Compare compares the encrypted text with the plain text if it's the same. 12 | func Compare(hashedPassword, password string) error { 13 | return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) 14 | } 15 | -------------------------------------------------------------------------------- /demo12/pkg/auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import "golang.org/x/crypto/bcrypt" 4 | 5 | // Encrypt encrypts the plain text with bcrypt. 6 | func Encrypt(source string) (string, error) { 7 | hashedBytes, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost) 8 | return string(hashedBytes), err 9 | } 10 | 11 | // Compare compares the encrypted text with the plain text if it's the same. 12 | func Compare(hashedPassword, password string) error { 13 | return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) 14 | } 15 | -------------------------------------------------------------------------------- /demo13/pkg/auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import "golang.org/x/crypto/bcrypt" 4 | 5 | // Encrypt encrypts the plain text with bcrypt. 6 | func Encrypt(source string) (string, error) { 7 | hashedBytes, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost) 8 | return string(hashedBytes), err 9 | } 10 | 11 | // Compare compares the encrypted text with the plain text if it's the same. 12 | func Compare(hashedPassword, password string) error { 13 | return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) 14 | } 15 | -------------------------------------------------------------------------------- /demo14/pkg/auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import "golang.org/x/crypto/bcrypt" 4 | 5 | // Encrypt encrypts the plain text with bcrypt. 6 | func Encrypt(source string) (string, error) { 7 | hashedBytes, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost) 8 | return string(hashedBytes), err 9 | } 10 | 11 | // Compare compares the encrypted text with the plain text if it's the same. 12 | func Compare(hashedPassword, password string) error { 13 | return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) 14 | } 15 | -------------------------------------------------------------------------------- /demo15/pkg/auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import "golang.org/x/crypto/bcrypt" 4 | 5 | // Encrypt encrypts the plain text with bcrypt. 6 | func Encrypt(source string) (string, error) { 7 | hashedBytes, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost) 8 | return string(hashedBytes), err 9 | } 10 | 11 | // Compare compares the encrypted text with the plain text if it's the same. 12 | func Compare(hashedPassword, password string) error { 13 | return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) 14 | } 15 | -------------------------------------------------------------------------------- /demo16/pkg/auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import "golang.org/x/crypto/bcrypt" 4 | 5 | // Encrypt encrypts the plain text with bcrypt. 6 | func Encrypt(source string) (string, error) { 7 | hashedBytes, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost) 8 | return string(hashedBytes), err 9 | } 10 | 11 | // Compare compares the encrypted text with the plain text if it's the same. 12 | func Compare(hashedPassword, password string) error { 13 | return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) 14 | } 15 | -------------------------------------------------------------------------------- /demo17/pkg/auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import "golang.org/x/crypto/bcrypt" 4 | 5 | // Encrypt encrypts the plain text with bcrypt. 6 | func Encrypt(source string) (string, error) { 7 | hashedBytes, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost) 8 | return string(hashedBytes), err 9 | } 10 | 11 | // Compare compares the encrypted text with the plain text if it's the same. 12 | func Compare(hashedPassword, password string) error { 13 | return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) 14 | } 15 | -------------------------------------------------------------------------------- /demo06/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | type Response struct { 12 | Code int `json:"code"` 13 | Message string `json:"message"` 14 | Data interface{} `json:"data"` 15 | } 16 | 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /demo07/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | type Response struct { 12 | Code int `json:"code"` 13 | Message string `json:"message"` 14 | Data interface{} `json:"data"` 15 | } 16 | 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /demo08/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | type Response struct { 12 | Code int `json:"code"` 13 | Message string `json:"message"` 14 | Data interface{} `json:"data"` 15 | } 16 | 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /demo09/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | type Response struct { 12 | Code int `json:"code"` 13 | Message string `json:"message"` 14 | Data interface{} `json:"data"` 15 | } 16 | 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /demo10/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | type Response struct { 12 | Code int `json:"code"` 13 | Message string `json:"message"` 14 | Data interface{} `json:"data"` 15 | } 16 | 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /demo11/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | type Response struct { 12 | Code int `json:"code"` 13 | Message string `json:"message"` 14 | Data interface{} `json:"data"` 15 | } 16 | 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /demo12/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | type Response struct { 12 | Code int `json:"code"` 13 | Message string `json:"message"` 14 | Data interface{} `json:"data"` 15 | } 16 | 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /demo13/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | type Response struct { 12 | Code int `json:"code"` 13 | Message string `json:"message"` 14 | Data interface{} `json:"data"` 15 | } 16 | 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /demo14/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | type Response struct { 12 | Code int `json:"code"` 13 | Message string `json:"message"` 14 | Data interface{} `json:"data"` 15 | } 16 | 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /demo15/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | type Response struct { 12 | Code int `json:"code"` 13 | Message string `json:"message"` 14 | Data interface{} `json:"data"` 15 | } 16 | 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /demo16/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | type Response struct { 12 | Code int `json:"code"` 13 | Message string `json:"message"` 14 | Data interface{} `json:"data"` 15 | } 16 | 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /demo17/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | type Response struct { 12 | Code int `json:"code"` 13 | Message string `json:"message"` 14 | Data interface{} `json:"data"` 15 | } 16 | 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /demo07/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "apiserver/model" 5 | ) 6 | 7 | type CreateRequest struct { 8 | Username string `json:"username"` 9 | Password string `json:"password"` 10 | } 11 | 12 | type CreateResponse struct { 13 | Username string `json:"username"` 14 | } 15 | 16 | type ListRequest struct { 17 | Username string `json:"username"` 18 | Offset int `json:"offset"` 19 | Limit int `json:"limit"` 20 | } 21 | 22 | type ListResponse struct { 23 | TotalCount uint64 `json:"totalCount"` 24 | UserList []*model.UserInfo `json:"userList"` 25 | } 26 | -------------------------------------------------------------------------------- /demo08/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "apiserver/model" 5 | ) 6 | 7 | type CreateRequest struct { 8 | Username string `json:"username"` 9 | Password string `json:"password"` 10 | } 11 | 12 | type CreateResponse struct { 13 | Username string `json:"username"` 14 | } 15 | 16 | type ListRequest struct { 17 | Username string `json:"username"` 18 | Offset int `json:"offset"` 19 | Limit int `json:"limit"` 20 | } 21 | 22 | type ListResponse struct { 23 | TotalCount uint64 `json:"totalCount"` 24 | UserList []*model.UserInfo `json:"userList"` 25 | } 26 | -------------------------------------------------------------------------------- /demo09/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "apiserver/model" 5 | ) 6 | 7 | type CreateRequest struct { 8 | Username string `json:"username"` 9 | Password string `json:"password"` 10 | } 11 | 12 | type CreateResponse struct { 13 | Username string `json:"username"` 14 | } 15 | 16 | type ListRequest struct { 17 | Username string `json:"username"` 18 | Offset int `json:"offset"` 19 | Limit int `json:"limit"` 20 | } 21 | 22 | type ListResponse struct { 23 | TotalCount uint64 `json:"totalCount"` 24 | UserList []*model.UserInfo `json:"userList"` 25 | } 26 | -------------------------------------------------------------------------------- /demo10/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "apiserver/model" 5 | ) 6 | 7 | type CreateRequest struct { 8 | Username string `json:"username"` 9 | Password string `json:"password"` 10 | } 11 | 12 | type CreateResponse struct { 13 | Username string `json:"username"` 14 | } 15 | 16 | type ListRequest struct { 17 | Username string `json:"username"` 18 | Offset int `json:"offset"` 19 | Limit int `json:"limit"` 20 | } 21 | 22 | type ListResponse struct { 23 | TotalCount uint64 `json:"totalCount"` 24 | UserList []*model.UserInfo `json:"userList"` 25 | } 26 | -------------------------------------------------------------------------------- /demo11/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "apiserver/model" 5 | ) 6 | 7 | type CreateRequest struct { 8 | Username string `json:"username"` 9 | Password string `json:"password"` 10 | } 11 | 12 | type CreateResponse struct { 13 | Username string `json:"username"` 14 | } 15 | 16 | type ListRequest struct { 17 | Username string `json:"username"` 18 | Offset int `json:"offset"` 19 | Limit int `json:"limit"` 20 | } 21 | 22 | type ListResponse struct { 23 | TotalCount uint64 `json:"totalCount"` 24 | UserList []*model.UserInfo `json:"userList"` 25 | } 26 | -------------------------------------------------------------------------------- /demo12/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "apiserver/model" 5 | ) 6 | 7 | type CreateRequest struct { 8 | Username string `json:"username"` 9 | Password string `json:"password"` 10 | } 11 | 12 | type CreateResponse struct { 13 | Username string `json:"username"` 14 | } 15 | 16 | type ListRequest struct { 17 | Username string `json:"username"` 18 | Offset int `json:"offset"` 19 | Limit int `json:"limit"` 20 | } 21 | 22 | type ListResponse struct { 23 | TotalCount uint64 `json:"totalCount"` 24 | UserList []*model.UserInfo `json:"userList"` 25 | } 26 | -------------------------------------------------------------------------------- /demo13/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "apiserver/model" 5 | ) 6 | 7 | type CreateRequest struct { 8 | Username string `json:"username"` 9 | Password string `json:"password"` 10 | } 11 | 12 | type CreateResponse struct { 13 | Username string `json:"username"` 14 | } 15 | 16 | type ListRequest struct { 17 | Username string `json:"username"` 18 | Offset int `json:"offset"` 19 | Limit int `json:"limit"` 20 | } 21 | 22 | type ListResponse struct { 23 | TotalCount uint64 `json:"totalCount"` 24 | UserList []*model.UserInfo `json:"userList"` 25 | } 26 | -------------------------------------------------------------------------------- /demo14/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "apiserver/model" 5 | ) 6 | 7 | type CreateRequest struct { 8 | Username string `json:"username"` 9 | Password string `json:"password"` 10 | } 11 | 12 | type CreateResponse struct { 13 | Username string `json:"username"` 14 | } 15 | 16 | type ListRequest struct { 17 | Username string `json:"username"` 18 | Offset int `json:"offset"` 19 | Limit int `json:"limit"` 20 | } 21 | 22 | type ListResponse struct { 23 | TotalCount uint64 `json:"totalCount"` 24 | UserList []*model.UserInfo `json:"userList"` 25 | } 26 | -------------------------------------------------------------------------------- /demo15/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "apiserver/model" 5 | ) 6 | 7 | type CreateRequest struct { 8 | Username string `json:"username"` 9 | Password string `json:"password"` 10 | } 11 | 12 | type CreateResponse struct { 13 | Username string `json:"username"` 14 | } 15 | 16 | type ListRequest struct { 17 | Username string `json:"username"` 18 | Offset int `json:"offset"` 19 | Limit int `json:"limit"` 20 | } 21 | 22 | type ListResponse struct { 23 | TotalCount uint64 `json:"totalCount"` 24 | UserList []*model.UserInfo `json:"userList"` 25 | } 26 | -------------------------------------------------------------------------------- /demo16/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "apiserver/model" 5 | ) 6 | 7 | type CreateRequest struct { 8 | Username string `json:"username"` 9 | Password string `json:"password"` 10 | } 11 | 12 | type CreateResponse struct { 13 | Username string `json:"username"` 14 | } 15 | 16 | type ListRequest struct { 17 | Username string `json:"username"` 18 | Offset int `json:"offset"` 19 | Limit int `json:"limit"` 20 | } 21 | 22 | type ListResponse struct { 23 | TotalCount uint64 `json:"totalCount"` 24 | UserList []*model.UserInfo `json:"userList"` 25 | } 26 | -------------------------------------------------------------------------------- /demo07/handler/user/list.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/service" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // List list the users in the database. 12 | func List(c *gin.Context) { 13 | var r ListRequest 14 | if err := c.Bind(&r); err != nil { 15 | SendResponse(c, errno.ErrBind, nil) 16 | return 17 | } 18 | 19 | infos, count, err := service.ListUser(r.Username, r.Offset, r.Limit) 20 | if err != nil { 21 | SendResponse(c, err, nil) 22 | return 23 | } 24 | 25 | SendResponse(c, nil, ListResponse{ 26 | TotalCount: count, 27 | UserList: infos, 28 | }) 29 | } 30 | -------------------------------------------------------------------------------- /demo08/handler/user/list.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/service" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // List list the users in the database. 12 | func List(c *gin.Context) { 13 | var r ListRequest 14 | if err := c.Bind(&r); err != nil { 15 | SendResponse(c, errno.ErrBind, nil) 16 | return 17 | } 18 | 19 | infos, count, err := service.ListUser(r.Username, r.Offset, r.Limit) 20 | if err != nil { 21 | SendResponse(c, err, nil) 22 | return 23 | } 24 | 25 | SendResponse(c, nil, ListResponse{ 26 | TotalCount: count, 27 | UserList: infos, 28 | }) 29 | } 30 | -------------------------------------------------------------------------------- /demo09/handler/user/list.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/service" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // List list the users in the database. 12 | func List(c *gin.Context) { 13 | var r ListRequest 14 | if err := c.Bind(&r); err != nil { 15 | SendResponse(c, errno.ErrBind, nil) 16 | return 17 | } 18 | 19 | infos, count, err := service.ListUser(r.Username, r.Offset, r.Limit) 20 | if err != nil { 21 | SendResponse(c, err, nil) 22 | return 23 | } 24 | 25 | SendResponse(c, nil, ListResponse{ 26 | TotalCount: count, 27 | UserList: infos, 28 | }) 29 | } 30 | -------------------------------------------------------------------------------- /demo10/handler/user/list.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/service" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // List list the users in the database. 12 | func List(c *gin.Context) { 13 | var r ListRequest 14 | if err := c.Bind(&r); err != nil { 15 | SendResponse(c, errno.ErrBind, nil) 16 | return 17 | } 18 | 19 | infos, count, err := service.ListUser(r.Username, r.Offset, r.Limit) 20 | if err != nil { 21 | SendResponse(c, err, nil) 22 | return 23 | } 24 | 25 | SendResponse(c, nil, ListResponse{ 26 | TotalCount: count, 27 | UserList: infos, 28 | }) 29 | } 30 | -------------------------------------------------------------------------------- /demo11/handler/user/list.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/service" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // List list the users in the database. 12 | func List(c *gin.Context) { 13 | var r ListRequest 14 | if err := c.Bind(&r); err != nil { 15 | SendResponse(c, errno.ErrBind, nil) 16 | return 17 | } 18 | 19 | infos, count, err := service.ListUser(r.Username, r.Offset, r.Limit) 20 | if err != nil { 21 | SendResponse(c, err, nil) 22 | return 23 | } 24 | 25 | SendResponse(c, nil, ListResponse{ 26 | TotalCount: count, 27 | UserList: infos, 28 | }) 29 | } 30 | -------------------------------------------------------------------------------- /demo12/handler/user/list.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/service" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // List list the users in the database. 12 | func List(c *gin.Context) { 13 | var r ListRequest 14 | if err := c.Bind(&r); err != nil { 15 | SendResponse(c, errno.ErrBind, nil) 16 | return 17 | } 18 | 19 | infos, count, err := service.ListUser(r.Username, r.Offset, r.Limit) 20 | if err != nil { 21 | SendResponse(c, err, nil) 22 | return 23 | } 24 | 25 | SendResponse(c, nil, ListResponse{ 26 | TotalCount: count, 27 | UserList: infos, 28 | }) 29 | } 30 | -------------------------------------------------------------------------------- /demo13/handler/user/list.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/service" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // List list the users in the database. 12 | func List(c *gin.Context) { 13 | var r ListRequest 14 | if err := c.Bind(&r); err != nil { 15 | SendResponse(c, errno.ErrBind, nil) 16 | return 17 | } 18 | 19 | infos, count, err := service.ListUser(r.Username, r.Offset, r.Limit) 20 | if err != nil { 21 | SendResponse(c, err, nil) 22 | return 23 | } 24 | 25 | SendResponse(c, nil, ListResponse{ 26 | TotalCount: count, 27 | UserList: infos, 28 | }) 29 | } 30 | -------------------------------------------------------------------------------- /demo11/Makefile: -------------------------------------------------------------------------------- 1 | all: gotool 2 | @go build -v . 3 | clean: 4 | rm -f apiserver 5 | find . -name "[._]*.s[a-w][a-z]" | xargs -i rm -f {} 6 | gotool: 7 | gofmt -w . 8 | go tool vet . |& grep -v vendor;true 9 | ca: 10 | openssl req -new -nodes -x509 -out conf/server.crt -keyout conf/server.key -days 3650 -subj "/C=DE/ST=NRW/L=Earth/O=Random Company/OU=IT/CN=127.0.0.1/emailAddress=xxxxx@qq.com" 11 | 12 | help: 13 | @echo "make - compile the source code" 14 | @echo "make clean - remove binary file and vim swp files" 15 | @echo "make gotool - run go tool 'fmt' and 'vet'" 16 | @echo "make ca - generate ca files" 17 | 18 | .PHONY: clean gotool ca help 19 | 20 | 21 | -------------------------------------------------------------------------------- /demo08/router/middleware/requestid.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/satori/go.uuid" 6 | ) 7 | 8 | func RequestId() gin.HandlerFunc { 9 | return func(c *gin.Context) { 10 | // Check for incoming header, use it if exists 11 | requestId := c.Request.Header.Get("X-Request-Id") 12 | 13 | // Create request id with UUID4 14 | if requestId == "" { 15 | u4, _ := uuid.NewV4() 16 | requestId = u4.String() 17 | } 18 | 19 | // Expose it for use in the application 20 | c.Set("X-Request-Id", requestId) 21 | 22 | // Set X-Request-Id header 23 | c.Writer.Header().Set("X-Request-Id", requestId) 24 | c.Next() 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /demo09/router/middleware/requestid.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/satori/go.uuid" 6 | ) 7 | 8 | func RequestId() gin.HandlerFunc { 9 | return func(c *gin.Context) { 10 | // Check for incoming header, use it if exists 11 | requestId := c.Request.Header.Get("X-Request-Id") 12 | 13 | // Create request id with UUID4 14 | if requestId == "" { 15 | u4, _ := uuid.NewV4() 16 | requestId = u4.String() 17 | } 18 | 19 | // Expose it for use in the application 20 | c.Set("X-Request-Id", requestId) 21 | 22 | // Set X-Request-Id header 23 | c.Writer.Header().Set("X-Request-Id", requestId) 24 | c.Next() 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /demo10/router/middleware/requestid.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/satori/go.uuid" 6 | ) 7 | 8 | func RequestId() gin.HandlerFunc { 9 | return func(c *gin.Context) { 10 | // Check for incoming header, use it if exists 11 | requestId := c.Request.Header.Get("X-Request-Id") 12 | 13 | // Create request id with UUID4 14 | if requestId == "" { 15 | u4, _ := uuid.NewV4() 16 | requestId = u4.String() 17 | } 18 | 19 | // Expose it for use in the application 20 | c.Set("X-Request-Id", requestId) 21 | 22 | // Set X-Request-Id header 23 | c.Writer.Header().Set("X-Request-Id", requestId) 24 | c.Next() 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /demo11/router/middleware/requestid.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/satori/go.uuid" 6 | ) 7 | 8 | func RequestId() gin.HandlerFunc { 9 | return func(c *gin.Context) { 10 | // Check for incoming header, use it if exists 11 | requestId := c.Request.Header.Get("X-Request-Id") 12 | 13 | // Create request id with UUID4 14 | if requestId == "" { 15 | u4, _ := uuid.NewV4() 16 | requestId = u4.String() 17 | } 18 | 19 | // Expose it for use in the application 20 | c.Set("X-Request-Id", requestId) 21 | 22 | // Set X-Request-Id header 23 | c.Writer.Header().Set("X-Request-Id", requestId) 24 | c.Next() 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /demo12/router/middleware/requestid.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/satori/go.uuid" 6 | ) 7 | 8 | func RequestId() gin.HandlerFunc { 9 | return func(c *gin.Context) { 10 | // Check for incoming header, use it if exists 11 | requestId := c.Request.Header.Get("X-Request-Id") 12 | 13 | // Create request id with UUID4 14 | if requestId == "" { 15 | u4, _ := uuid.NewV4() 16 | requestId = u4.String() 17 | } 18 | 19 | // Expose it for use in the application 20 | c.Set("X-Request-Id", requestId) 21 | 22 | // Set X-Request-Id header 23 | c.Writer.Header().Set("X-Request-Id", requestId) 24 | c.Next() 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /demo13/router/middleware/requestid.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/satori/go.uuid" 6 | ) 7 | 8 | func RequestId() gin.HandlerFunc { 9 | return func(c *gin.Context) { 10 | // Check for incoming header, use it if exists 11 | requestId := c.Request.Header.Get("X-Request-Id") 12 | 13 | // Create request id with UUID4 14 | if requestId == "" { 15 | u4, _ := uuid.NewV4() 16 | requestId = u4.String() 17 | } 18 | 19 | // Expose it for use in the application 20 | c.Set("X-Request-Id", requestId) 21 | 22 | // Set X-Request-Id header 23 | c.Writer.Header().Set("X-Request-Id", requestId) 24 | c.Next() 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /demo14/router/middleware/requestid.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/satori/go.uuid" 6 | ) 7 | 8 | func RequestId() gin.HandlerFunc { 9 | return func(c *gin.Context) { 10 | // Check for incoming header, use it if exists 11 | requestId := c.Request.Header.Get("X-Request-Id") 12 | 13 | // Create request id with UUID4 14 | if requestId == "" { 15 | u4, _ := uuid.NewV4() 16 | requestId = u4.String() 17 | } 18 | 19 | // Expose it for use in the application 20 | c.Set("X-Request-Id", requestId) 21 | 22 | // Set X-Request-Id header 23 | c.Writer.Header().Set("X-Request-Id", requestId) 24 | c.Next() 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /demo15/router/middleware/requestid.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/satori/go.uuid" 6 | ) 7 | 8 | func RequestId() gin.HandlerFunc { 9 | return func(c *gin.Context) { 10 | // Check for incoming header, use it if exists 11 | requestId := c.Request.Header.Get("X-Request-Id") 12 | 13 | // Create request id with UUID4 14 | if requestId == "" { 15 | u4, _ := uuid.NewV4() 16 | requestId = u4.String() 17 | } 18 | 19 | // Expose it for use in the application 20 | c.Set("X-Request-Id", requestId) 21 | 22 | // Set X-Request-Id header 23 | c.Writer.Header().Set("X-Request-Id", requestId) 24 | c.Next() 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /demo16/router/middleware/requestid.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/satori/go.uuid" 6 | ) 7 | 8 | func RequestId() gin.HandlerFunc { 9 | return func(c *gin.Context) { 10 | // Check for incoming header, use it if exists 11 | requestId := c.Request.Header.Get("X-Request-Id") 12 | 13 | // Create request id with UUID4 14 | if requestId == "" { 15 | u4, _ := uuid.NewV4() 16 | requestId = u4.String() 17 | } 18 | 19 | // Expose it for use in the application 20 | c.Set("X-Request-Id", requestId) 21 | 22 | // Set X-Request-Id header 23 | c.Writer.Header().Set("X-Request-Id", requestId) 24 | c.Next() 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /demo17/router/middleware/requestid.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/satori/go.uuid" 6 | ) 7 | 8 | func RequestId() gin.HandlerFunc { 9 | return func(c *gin.Context) { 10 | // Check for incoming header, use it if exists 11 | requestId := c.Request.Header.Get("X-Request-Id") 12 | 13 | // Create request id with UUID4 14 | if requestId == "" { 15 | u4, _ := uuid.NewV4() 16 | requestId = u4.String() 17 | } 18 | 19 | // Expose it for use in the application 20 | c.Set("X-Request-Id", requestId) 21 | 22 | // Set X-Request-Id header 23 | c.Writer.Header().Set("X-Request-Id", requestId) 24 | c.Next() 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /demo15/util/util_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestGenShortId(t *testing.T) { 8 | shortId, err := GenShortId() 9 | if shortId == "" || err != nil { 10 | t.Error("GenShortId failed!") 11 | } 12 | 13 | t.Log("GenShortId test pass") 14 | } 15 | 16 | func BenchmarkGenShortId(b *testing.B) { 17 | for i := 0; i < b.N; i++ { 18 | GenShortId() 19 | } 20 | } 21 | 22 | func BenchmarkGenShortIdTimeConsuming(b *testing.B) { 23 | b.StopTimer() //调用该函数停止压力测试的时间计数 24 | 25 | shortId, err := GenShortId() 26 | if shortId == "" || err != nil { 27 | b.Error(err) 28 | } 29 | 30 | b.StartTimer() //重新开始时间 31 | 32 | for i := 0; i < b.N; i++ { 33 | GenShortId() 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /demo16/util/util_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestGenShortId(t *testing.T) { 8 | shortId, err := GenShortId() 9 | if shortId == "" || err != nil { 10 | t.Error("GenShortId failed!") 11 | } 12 | 13 | t.Log("GenShortId test pass") 14 | } 15 | 16 | func BenchmarkGenShortId(b *testing.B) { 17 | for i := 0; i < b.N; i++ { 18 | GenShortId() 19 | } 20 | } 21 | 22 | func BenchmarkGenShortIdTimeConsuming(b *testing.B) { 23 | b.StopTimer() //调用该函数停止压力测试的时间计数 24 | 25 | shortId, err := GenShortId() 26 | if shortId == "" || err != nil { 27 | b.Error(err) 28 | } 29 | 30 | b.StartTimer() //重新开始时间 31 | 32 | for i := 0; i < b.N; i++ { 33 | GenShortId() 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /demo17/util/util_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestGenShortId(t *testing.T) { 8 | shortId, err := GenShortId() 9 | if shortId == "" || err != nil { 10 | t.Error("GenShortId failed!") 11 | } 12 | 13 | t.Log("GenShortId test pass") 14 | } 15 | 16 | func BenchmarkGenShortId(b *testing.B) { 17 | for i := 0; i < b.N; i++ { 18 | GenShortId() 19 | } 20 | } 21 | 22 | func BenchmarkGenShortIdTimeConsuming(b *testing.B) { 23 | b.StopTimer() //调用该函数停止压力测试的时间计数 24 | 25 | shortId, err := GenShortId() 26 | if shortId == "" || err != nil { 27 | b.Error(err) 28 | } 29 | 30 | b.StartTimer() //重新开始时间 31 | 32 | for i := 0; i < b.N; i++ { 33 | GenShortId() 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /demo14/handler/user/list.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/service" 7 | 8 | "github.com/gin-gonic/gin" 9 | "github.com/lexkong/log" 10 | ) 11 | 12 | // List list the users in the database. 13 | func List(c *gin.Context) { 14 | log.Info("List function called.") 15 | var r ListRequest 16 | if err := c.Bind(&r); err != nil { 17 | SendResponse(c, errno.ErrBind, nil) 18 | return 19 | } 20 | 21 | infos, count, err := service.ListUser(r.Username, r.Offset, r.Limit) 22 | if err != nil { 23 | SendResponse(c, err, nil) 24 | return 25 | } 26 | 27 | SendResponse(c, nil, ListResponse{ 28 | TotalCount: count, 29 | UserList: infos, 30 | }) 31 | } 32 | -------------------------------------------------------------------------------- /demo15/handler/user/list.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/service" 7 | 8 | "github.com/gin-gonic/gin" 9 | "github.com/lexkong/log" 10 | ) 11 | 12 | // List list the users in the database. 13 | func List(c *gin.Context) { 14 | log.Info("List function called.") 15 | var r ListRequest 16 | if err := c.Bind(&r); err != nil { 17 | SendResponse(c, errno.ErrBind, nil) 18 | return 19 | } 20 | 21 | infos, count, err := service.ListUser(r.Username, r.Offset, r.Limit) 22 | if err != nil { 23 | SendResponse(c, err, nil) 24 | return 25 | } 26 | 27 | SendResponse(c, nil, ListResponse{ 28 | TotalCount: count, 29 | UserList: infos, 30 | }) 31 | } 32 | -------------------------------------------------------------------------------- /demo16/handler/user/list.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/service" 7 | 8 | "github.com/gin-gonic/gin" 9 | "github.com/lexkong/log" 10 | ) 11 | 12 | // List list the users in the database. 13 | func List(c *gin.Context) { 14 | log.Info("List function called.") 15 | var r ListRequest 16 | if err := c.Bind(&r); err != nil { 17 | SendResponse(c, errno.ErrBind, nil) 18 | return 19 | } 20 | 21 | infos, count, err := service.ListUser(r.Username, r.Offset, r.Limit) 22 | if err != nil { 23 | SendResponse(c, err, nil) 24 | return 25 | } 26 | 27 | SendResponse(c, nil, ListResponse{ 28 | TotalCount: count, 29 | UserList: infos, 30 | }) 31 | } 32 | -------------------------------------------------------------------------------- /demo07/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | log: 7 | writers: file,stdout 8 | logger_level: DEBUG 9 | logger_file: log/apiserver.log 10 | log_format_text: false 11 | rollingPolicy: size 12 | log_rotate_date: 1 13 | log_rotate_size: 1 14 | log_backup_count: 7 15 | db: 16 | name: db_apiserver 17 | addr: 127.0.0.1:3306 18 | username: root 19 | password: root 20 | docker_db: 21 | name: db_apiserver 22 | addr: 127.0.0.1:3306 23 | username: root 24 | password: root 25 | -------------------------------------------------------------------------------- /demo08/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | log: 7 | writers: file,stdout 8 | logger_level: DEBUG 9 | logger_file: log/apiserver.log 10 | log_format_text: false 11 | rollingPolicy: size 12 | log_rotate_date: 1 13 | log_rotate_size: 1 14 | log_backup_count: 7 15 | db: 16 | name: db_apiserver 17 | addr: 127.0.0.1:3306 18 | username: root 19 | password: root 20 | docker_db: 21 | name: db_apiserver 22 | addr: 127.0.0.1:3306 23 | username: root 24 | password: root 25 | -------------------------------------------------------------------------------- /demo17/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "apiserver/model" 5 | ) 6 | 7 | type CreateRequest struct { 8 | Username string `json:"username"` 9 | Password string `json:"password"` 10 | } 11 | 12 | type CreateResponse struct { 13 | Username string `json:"username"` 14 | } 15 | 16 | type ListRequest struct { 17 | Username string `json:"username"` 18 | Offset int `json:"offset"` 19 | Limit int `json:"limit"` 20 | } 21 | 22 | type ListResponse struct { 23 | TotalCount uint64 `json:"totalCount"` 24 | UserList []*model.UserInfo `json:"userList"` 25 | } 26 | 27 | type SwaggerListResponse struct { 28 | TotalCount uint64 `json:"totalCount"` 29 | UserList []model.UserInfo `json:"userList"` 30 | } 31 | -------------------------------------------------------------------------------- /demo09/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | jwt_secret: Rtg8BPKNEf2mB4mgvKONGPZZQSaJWNLijxR42qRgq0iBb5 7 | log: 8 | writers: file,stdout 9 | logger_level: DEBUG 10 | logger_file: log/apiserver.log 11 | log_format_text: false 12 | rollingPolicy: size 13 | log_rotate_date: 1 14 | log_rotate_size: 1 15 | log_backup_count: 7 16 | db: 17 | name: db_apiserver 18 | addr: 127.0.0.1:3306 19 | username: root 20 | password: root 21 | docker_db: 22 | name: db_apiserver 23 | addr: 127.0.0.1:3306 24 | username: root 25 | password: root 26 | -------------------------------------------------------------------------------- /demo17/handler/user/delete.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // @Summary Delete an user by the user identifier 14 | // @Description Delete user by ID 15 | // @Tags user 16 | // @Accept json 17 | // @Produce json 18 | // @Param id path uint64 true "The user's database id index num" 19 | // @Success 200 {object} handler.Response "{"code":0,"message":"OK","data":null}" 20 | // @Router /user/{id} [delete] 21 | func Delete(c *gin.Context) { 22 | userId, _ := strconv.Atoi(c.Param("id")) 23 | if err := model.DeleteUser(uint64(userId)); err != nil { 24 | SendResponse(c, errno.ErrDatabase, nil) 25 | return 26 | } 27 | 28 | SendResponse(c, nil, nil) 29 | } 30 | -------------------------------------------------------------------------------- /demo01/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/router/middleware" 8 | 9 | "github.com/gin-gonic/gin" 10 | ) 11 | 12 | // Load loads the middlewares, routes, handlers. 13 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 14 | // Middlewares. 15 | g.Use(gin.Recovery()) 16 | g.Use(middleware.NoCache) 17 | g.Use(middleware.Options) 18 | g.Use(middleware.Secure) 19 | g.Use(mw...) 20 | // 404 Handler. 21 | g.NoRoute(func(c *gin.Context) { 22 | c.String(http.StatusNotFound, "The incorrect API route.") 23 | }) 24 | 25 | // The health check handlers 26 | svcd := g.Group("/sd") 27 | { 28 | svcd.GET("/health", sd.HealthCheck) 29 | svcd.GET("/disk", sd.DiskCheck) 30 | svcd.GET("/cpu", sd.CPUCheck) 31 | svcd.GET("/ram", sd.RAMCheck) 32 | } 33 | 34 | return g 35 | } 36 | -------------------------------------------------------------------------------- /demo02/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/router/middleware" 8 | 9 | "github.com/gin-gonic/gin" 10 | ) 11 | 12 | // Load loads the middlewares, routes, handlers. 13 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 14 | // Middlewares. 15 | g.Use(gin.Recovery()) 16 | g.Use(middleware.NoCache) 17 | g.Use(middleware.Options) 18 | g.Use(middleware.Secure) 19 | g.Use(mw...) 20 | // 404 Handler. 21 | g.NoRoute(func(c *gin.Context) { 22 | c.String(http.StatusNotFound, "The incorrect API route.") 23 | }) 24 | 25 | // The health check handlers 26 | svcd := g.Group("/sd") 27 | { 28 | svcd.GET("/health", sd.HealthCheck) 29 | svcd.GET("/disk", sd.DiskCheck) 30 | svcd.GET("/cpu", sd.CPUCheck) 31 | svcd.GET("/ram", sd.RAMCheck) 32 | } 33 | 34 | return g 35 | } 36 | -------------------------------------------------------------------------------- /demo03/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/router/middleware" 8 | 9 | "github.com/gin-gonic/gin" 10 | ) 11 | 12 | // Load loads the middlewares, routes, handlers. 13 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 14 | // Middlewares. 15 | g.Use(gin.Recovery()) 16 | g.Use(middleware.NoCache) 17 | g.Use(middleware.Options) 18 | g.Use(middleware.Secure) 19 | g.Use(mw...) 20 | // 404 Handler. 21 | g.NoRoute(func(c *gin.Context) { 22 | c.String(http.StatusNotFound, "The incorrect API route.") 23 | }) 24 | 25 | // The health check handlers 26 | svcd := g.Group("/sd") 27 | { 28 | svcd.GET("/health", sd.HealthCheck) 29 | svcd.GET("/disk", sd.DiskCheck) 30 | svcd.GET("/cpu", sd.CPUCheck) 31 | svcd.GET("/ram", sd.RAMCheck) 32 | } 33 | 34 | return g 35 | } 36 | -------------------------------------------------------------------------------- /demo04/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/router/middleware" 8 | 9 | "github.com/gin-gonic/gin" 10 | ) 11 | 12 | // Load loads the middlewares, routes, handlers. 13 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 14 | // Middlewares. 15 | g.Use(gin.Recovery()) 16 | g.Use(middleware.NoCache) 17 | g.Use(middleware.Options) 18 | g.Use(middleware.Secure) 19 | g.Use(mw...) 20 | // 404 Handler. 21 | g.NoRoute(func(c *gin.Context) { 22 | c.String(http.StatusNotFound, "The incorrect API route.") 23 | }) 24 | 25 | // The health check handlers 26 | svcd := g.Group("/sd") 27 | { 28 | svcd.GET("/health", sd.HealthCheck) 29 | svcd.GET("/disk", sd.DiskCheck) 30 | svcd.GET("/cpu", sd.CPUCheck) 31 | svcd.GET("/ram", sd.RAMCheck) 32 | } 33 | 34 | return g 35 | } 36 | -------------------------------------------------------------------------------- /demo07/model/model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | ) 7 | 8 | type BaseModel struct { 9 | Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"-"` 10 | CreatedAt time.Time `gorm:"column:createdAt" json:"-"` 11 | UpdatedAt time.Time `gorm:"column:updatedAt" json:"-"` 12 | DeletedAt *time.Time `gorm:"column:deletedAt" sql:"index" json:"-"` 13 | } 14 | 15 | type UserInfo struct { 16 | Id uint64 `json:"id"` 17 | Username string `json:"username"` 18 | SayHello string `json:"sayHello"` 19 | Password string `json:"password"` 20 | CreatedAt string `json:"createdAt"` 21 | UpdatedAt string `json:"updatedAt"` 22 | } 23 | 24 | type UserList struct { 25 | Lock *sync.Mutex 26 | IdMap map[uint64]*UserInfo 27 | } 28 | 29 | // Token represents a JSON web token. 30 | type Token struct { 31 | Token string `json:"token"` 32 | } 33 | -------------------------------------------------------------------------------- /demo08/model/model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | ) 7 | 8 | type BaseModel struct { 9 | Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"-"` 10 | CreatedAt time.Time `gorm:"column:createdAt" json:"-"` 11 | UpdatedAt time.Time `gorm:"column:updatedAt" json:"-"` 12 | DeletedAt *time.Time `gorm:"column:deletedAt" sql:"index" json:"-"` 13 | } 14 | 15 | type UserInfo struct { 16 | Id uint64 `json:"id"` 17 | Username string `json:"username"` 18 | SayHello string `json:"sayHello"` 19 | Password string `json:"password"` 20 | CreatedAt string `json:"createdAt"` 21 | UpdatedAt string `json:"updatedAt"` 22 | } 23 | 24 | type UserList struct { 25 | Lock *sync.Mutex 26 | IdMap map[uint64]*UserInfo 27 | } 28 | 29 | // Token represents a JSON web token. 30 | type Token struct { 31 | Token string `json:"token"` 32 | } 33 | -------------------------------------------------------------------------------- /demo09/model/model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | ) 7 | 8 | type BaseModel struct { 9 | Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"-"` 10 | CreatedAt time.Time `gorm:"column:createdAt" json:"-"` 11 | UpdatedAt time.Time `gorm:"column:updatedAt" json:"-"` 12 | DeletedAt *time.Time `gorm:"column:deletedAt" sql:"index" json:"-"` 13 | } 14 | 15 | type UserInfo struct { 16 | Id uint64 `json:"id"` 17 | Username string `json:"username"` 18 | SayHello string `json:"sayHello"` 19 | Password string `json:"password"` 20 | CreatedAt string `json:"createdAt"` 21 | UpdatedAt string `json:"updatedAt"` 22 | } 23 | 24 | type UserList struct { 25 | Lock *sync.Mutex 26 | IdMap map[uint64]*UserInfo 27 | } 28 | 29 | // Token represents a JSON web token. 30 | type Token struct { 31 | Token string `json:"token"` 32 | } 33 | -------------------------------------------------------------------------------- /demo10/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | jwt_secret: Rtg8BPKNEf2mB4mgvKONGPZZQSaJWNLijxR42qRgq0iBb5 7 | tls: 8 | addr: :8081 9 | cert: conf/server.crt 10 | key: conf/server.key 11 | log: 12 | writers: stdout 13 | logger_level: DEBUG 14 | logger_file: log/apiserver.log 15 | log_format_text: true 16 | rollingPolicy: size 17 | log_rotate_date: 1 18 | log_rotate_size: 1 19 | log_backup_count: 7 20 | db: 21 | name: db_apiserver 22 | addr: 127.0.0.1:3306 23 | username: root 24 | password: root 25 | docker_db: 26 | name: db_apiserver 27 | addr: 127.0.0.1:3306 28 | username: root 29 | password: root 30 | -------------------------------------------------------------------------------- /demo10/model/model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | ) 7 | 8 | type BaseModel struct { 9 | Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"-"` 10 | CreatedAt time.Time `gorm:"column:createdAt" json:"-"` 11 | UpdatedAt time.Time `gorm:"column:updatedAt" json:"-"` 12 | DeletedAt *time.Time `gorm:"column:deletedAt" sql:"index" json:"-"` 13 | } 14 | 15 | type UserInfo struct { 16 | Id uint64 `json:"id"` 17 | Username string `json:"username"` 18 | SayHello string `json:"sayHello"` 19 | Password string `json:"password"` 20 | CreatedAt string `json:"createdAt"` 21 | UpdatedAt string `json:"updatedAt"` 22 | } 23 | 24 | type UserList struct { 25 | Lock *sync.Mutex 26 | IdMap map[uint64]*UserInfo 27 | } 28 | 29 | // Token represents a JSON web token. 30 | type Token struct { 31 | Token string `json:"token"` 32 | } 33 | -------------------------------------------------------------------------------- /demo11/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | jwt_secret: Rtg8BPKNEf2mB4mgvKONGPZZQSaJWNLijxR42qRgq0iBb5 7 | tls: 8 | addr: :8081 9 | cert: conf/server.crt 10 | key: conf/server.key 11 | log: 12 | writers: stdout 13 | logger_level: DEBUG 14 | logger_file: log/apiserver.log 15 | log_format_text: true 16 | rollingPolicy: size 17 | log_rotate_date: 1 18 | log_rotate_size: 1 19 | log_backup_count: 7 20 | db: 21 | name: db_apiserver 22 | addr: 127.0.0.1:3306 23 | username: root 24 | password: root 25 | docker_db: 26 | name: db_apiserver 27 | addr: 127.0.0.1:3306 28 | username: root 29 | password: root 30 | -------------------------------------------------------------------------------- /demo11/model/model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | ) 7 | 8 | type BaseModel struct { 9 | Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"-"` 10 | CreatedAt time.Time `gorm:"column:createdAt" json:"-"` 11 | UpdatedAt time.Time `gorm:"column:updatedAt" json:"-"` 12 | DeletedAt *time.Time `gorm:"column:deletedAt" sql:"index" json:"-"` 13 | } 14 | 15 | type UserInfo struct { 16 | Id uint64 `json:"id"` 17 | Username string `json:"username"` 18 | SayHello string `json:"sayHello"` 19 | Password string `json:"password"` 20 | CreatedAt string `json:"createdAt"` 21 | UpdatedAt string `json:"updatedAt"` 22 | } 23 | 24 | type UserList struct { 25 | Lock *sync.Mutex 26 | IdMap map[uint64]*UserInfo 27 | } 28 | 29 | // Token represents a JSON web token. 30 | type Token struct { 31 | Token string `json:"token"` 32 | } 33 | -------------------------------------------------------------------------------- /demo12/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | jwt_secret: Rtg8BPKNEf2mB4mgvKONGPZZQSaJWNLijxR42qRgq0iBb5 7 | tls: 8 | addr: :8081 9 | cert: conf/server.crt 10 | key: conf/server.key 11 | log: 12 | writers: stdout 13 | logger_level: DEBUG 14 | logger_file: log/apiserver.log 15 | log_format_text: true 16 | rollingPolicy: size 17 | log_rotate_date: 1 18 | log_rotate_size: 1 19 | log_backup_count: 7 20 | db: 21 | name: db_apiserver 22 | addr: 127.0.0.1:3306 23 | username: root 24 | password: root 25 | docker_db: 26 | name: db_apiserver 27 | addr: 127.0.0.1:3306 28 | username: root 29 | password: root 30 | -------------------------------------------------------------------------------- /demo12/model/model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | ) 7 | 8 | type BaseModel struct { 9 | Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"-"` 10 | CreatedAt time.Time `gorm:"column:createdAt" json:"-"` 11 | UpdatedAt time.Time `gorm:"column:updatedAt" json:"-"` 12 | DeletedAt *time.Time `gorm:"column:deletedAt" sql:"index" json:"-"` 13 | } 14 | 15 | type UserInfo struct { 16 | Id uint64 `json:"id"` 17 | Username string `json:"username"` 18 | SayHello string `json:"sayHello"` 19 | Password string `json:"password"` 20 | CreatedAt string `json:"createdAt"` 21 | UpdatedAt string `json:"updatedAt"` 22 | } 23 | 24 | type UserList struct { 25 | Lock *sync.Mutex 26 | IdMap map[uint64]*UserInfo 27 | } 28 | 29 | // Token represents a JSON web token. 30 | type Token struct { 31 | Token string `json:"token"` 32 | } 33 | -------------------------------------------------------------------------------- /demo13/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | jwt_secret: Rtg8BPKNEf2mB4mgvKONGPZZQSaJWNLijxR42qRgq0iBb5 7 | tls: 8 | addr: :8081 9 | cert: conf/server.crt 10 | key: conf/server.key 11 | log: 12 | writers: stdout 13 | logger_level: DEBUG 14 | logger_file: log/apiserver.log 15 | log_format_text: true 16 | rollingPolicy: size 17 | log_rotate_date: 1 18 | log_rotate_size: 1 19 | log_backup_count: 7 20 | db: 21 | name: db_apiserver 22 | addr: 127.0.0.1:3306 23 | username: root 24 | password: root 25 | docker_db: 26 | name: db_apiserver 27 | addr: 127.0.0.1:3306 28 | username: root 29 | password: root 30 | -------------------------------------------------------------------------------- /demo13/model/model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | ) 7 | 8 | type BaseModel struct { 9 | Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"-"` 10 | CreatedAt time.Time `gorm:"column:createdAt" json:"-"` 11 | UpdatedAt time.Time `gorm:"column:updatedAt" json:"-"` 12 | DeletedAt *time.Time `gorm:"column:deletedAt" sql:"index" json:"-"` 13 | } 14 | 15 | type UserInfo struct { 16 | Id uint64 `json:"id"` 17 | Username string `json:"username"` 18 | SayHello string `json:"sayHello"` 19 | Password string `json:"password"` 20 | CreatedAt string `json:"createdAt"` 21 | UpdatedAt string `json:"updatedAt"` 22 | } 23 | 24 | type UserList struct { 25 | Lock *sync.Mutex 26 | IdMap map[uint64]*UserInfo 27 | } 28 | 29 | // Token represents a JSON web token. 30 | type Token struct { 31 | Token string `json:"token"` 32 | } 33 | -------------------------------------------------------------------------------- /demo14/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | jwt_secret: Rtg8BPKNEf2mB4mgvKONGPZZQSaJWNLijxR42qRgq0iBb5 7 | tls: 8 | addr: :8081 9 | cert: conf/server.crt 10 | key: conf/server.key 11 | log: 12 | writers: stdout 13 | logger_level: DEBUG 14 | logger_file: log/apiserver.log 15 | log_format_text: true 16 | rollingPolicy: size 17 | log_rotate_date: 1 18 | log_rotate_size: 1 19 | log_backup_count: 7 20 | db: 21 | name: db_apiserver 22 | addr: 127.0.0.1:3306 23 | username: root 24 | password: root 25 | docker_db: 26 | name: db_apiserver 27 | addr: 127.0.0.1:3306 28 | username: root 29 | password: root 30 | -------------------------------------------------------------------------------- /demo14/model/model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | ) 7 | 8 | type BaseModel struct { 9 | Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"-"` 10 | CreatedAt time.Time `gorm:"column:createdAt" json:"-"` 11 | UpdatedAt time.Time `gorm:"column:updatedAt" json:"-"` 12 | DeletedAt *time.Time `gorm:"column:deletedAt" sql:"index" json:"-"` 13 | } 14 | 15 | type UserInfo struct { 16 | Id uint64 `json:"id"` 17 | Username string `json:"username"` 18 | SayHello string `json:"sayHello"` 19 | Password string `json:"password"` 20 | CreatedAt string `json:"createdAt"` 21 | UpdatedAt string `json:"updatedAt"` 22 | } 23 | 24 | type UserList struct { 25 | Lock *sync.Mutex 26 | IdMap map[uint64]*UserInfo 27 | } 28 | 29 | // Token represents a JSON web token. 30 | type Token struct { 31 | Token string `json:"token"` 32 | } 33 | -------------------------------------------------------------------------------- /demo15/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | jwt_secret: Rtg8BPKNEf2mB4mgvKONGPZZQSaJWNLijxR42qRgq0iBb5 7 | tls: 8 | addr: :8081 9 | cert: conf/server.crt 10 | key: conf/server.key 11 | log: 12 | writers: stdout 13 | logger_level: DEBUG 14 | logger_file: log/apiserver.log 15 | log_format_text: true 16 | rollingPolicy: size 17 | log_rotate_date: 1 18 | log_rotate_size: 1 19 | log_backup_count: 7 20 | db: 21 | name: db_apiserver 22 | addr: 127.0.0.1:3306 23 | username: root 24 | password: root 25 | docker_db: 26 | name: db_apiserver 27 | addr: 127.0.0.1:3306 28 | username: root 29 | password: root 30 | -------------------------------------------------------------------------------- /demo15/model/model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | ) 7 | 8 | type BaseModel struct { 9 | Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"-"` 10 | CreatedAt time.Time `gorm:"column:createdAt" json:"-"` 11 | UpdatedAt time.Time `gorm:"column:updatedAt" json:"-"` 12 | DeletedAt *time.Time `gorm:"column:deletedAt" sql:"index" json:"-"` 13 | } 14 | 15 | type UserInfo struct { 16 | Id uint64 `json:"id"` 17 | Username string `json:"username"` 18 | SayHello string `json:"sayHello"` 19 | Password string `json:"password"` 20 | CreatedAt string `json:"createdAt"` 21 | UpdatedAt string `json:"updatedAt"` 22 | } 23 | 24 | type UserList struct { 25 | Lock *sync.Mutex 26 | IdMap map[uint64]*UserInfo 27 | } 28 | 29 | // Token represents a JSON web token. 30 | type Token struct { 31 | Token string `json:"token"` 32 | } 33 | -------------------------------------------------------------------------------- /demo16/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | jwt_secret: Rtg8BPKNEf2mB4mgvKONGPZZQSaJWNLijxR42qRgq0iBb5 7 | tls: 8 | addr: :8081 9 | cert: conf/server.crt 10 | key: conf/server.key 11 | log: 12 | writers: stdout 13 | logger_level: DEBUG 14 | logger_file: log/apiserver.log 15 | log_format_text: true 16 | rollingPolicy: size 17 | log_rotate_date: 1 18 | log_rotate_size: 1 19 | log_backup_count: 7 20 | db: 21 | name: db_apiserver 22 | addr: 127.0.0.1:3306 23 | username: root 24 | password: root 25 | docker_db: 26 | name: db_apiserver 27 | addr: 127.0.0.1:3306 28 | username: root 29 | password: root 30 | -------------------------------------------------------------------------------- /demo16/model/model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | ) 7 | 8 | type BaseModel struct { 9 | Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"-"` 10 | CreatedAt time.Time `gorm:"column:createdAt" json:"-"` 11 | UpdatedAt time.Time `gorm:"column:updatedAt" json:"-"` 12 | DeletedAt *time.Time `gorm:"column:deletedAt" sql:"index" json:"-"` 13 | } 14 | 15 | type UserInfo struct { 16 | Id uint64 `json:"id"` 17 | Username string `json:"username"` 18 | SayHello string `json:"sayHello"` 19 | Password string `json:"password"` 20 | CreatedAt string `json:"createdAt"` 21 | UpdatedAt string `json:"updatedAt"` 22 | } 23 | 24 | type UserList struct { 25 | Lock *sync.Mutex 26 | IdMap map[uint64]*UserInfo 27 | } 28 | 29 | // Token represents a JSON web token. 30 | type Token struct { 31 | Token string `json:"token"` 32 | } 33 | -------------------------------------------------------------------------------- /demo17/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | jwt_secret: Rtg8BPKNEf2mB4mgvKONGPZZQSaJWNLijxR42qRgq0iBb5 7 | tls: 8 | addr: :8081 9 | cert: conf/server.crt 10 | key: conf/server.key 11 | log: 12 | writers: stdout 13 | logger_level: DEBUG 14 | logger_file: log/apiserver.log 15 | log_format_text: true 16 | rollingPolicy: size 17 | log_rotate_date: 1 18 | log_rotate_size: 1 19 | log_backup_count: 7 20 | db: 21 | name: db_apiserver 22 | addr: 127.0.0.1:3306 23 | username: root 24 | password: root 25 | docker_db: 26 | name: db_apiserver 27 | addr: 127.0.0.1:3306 28 | username: root 29 | password: root 30 | -------------------------------------------------------------------------------- /demo17/model/model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | ) 7 | 8 | type BaseModel struct { 9 | Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"-"` 10 | CreatedAt time.Time `gorm:"column:createdAt" json:"-"` 11 | UpdatedAt time.Time `gorm:"column:updatedAt" json:"-"` 12 | DeletedAt *time.Time `gorm:"column:deletedAt" sql:"index" json:"-"` 13 | } 14 | 15 | type UserInfo struct { 16 | Id uint64 `json:"id"` 17 | Username string `json:"username"` 18 | SayHello string `json:"sayHello"` 19 | Password string `json:"password"` 20 | CreatedAt string `json:"createdAt"` 21 | UpdatedAt string `json:"updatedAt"` 22 | } 23 | 24 | type UserList struct { 25 | Lock *sync.Mutex 26 | IdMap map[uint64]*UserInfo 27 | } 28 | 29 | // Token represents a JSON web token. 30 | type Token struct { 31 | Token string `json:"token"` 32 | } 33 | -------------------------------------------------------------------------------- /demo17/handler/user/get.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | 8 | "github.com/gin-gonic/gin" 9 | ) 10 | 11 | // @Summary Get an user by the user identifier 12 | // @Description Get an user by username 13 | // @Tags user 14 | // @Accept json 15 | // @Produce json 16 | // @Param username path string true "Username" 17 | // @Success 200 {object} model.UserModel "{"code":0,"message":"OK","data":{"username":"kong","password":"$2a$10$E0kwtmtLZbwW/bDQ8qI8e.eHPqhQOW9tvjwpyo/p05f/f4Qvr3OmS"}}" 18 | // @Router /user/{username} [get] 19 | func Get(c *gin.Context) { 20 | username := c.Param("username") 21 | // Get the user by the `username` from the database. 22 | user, err := model.GetUser(username) 23 | if err != nil { 24 | SendResponse(c, errno.ErrUserNotFound, nil) 25 | return 26 | } 27 | 28 | SendResponse(c, nil, user) 29 | } 30 | -------------------------------------------------------------------------------- /demo12/pkg/version/version.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | ) 7 | 8 | // Info contains versioning information. 9 | type Info struct { 10 | GitTag string `json:"gitTag"` 11 | GitCommit string `json:"gitCommit"` 12 | GitTreeState string `json:"gitTreeState"` 13 | BuildDate string `json:"buildDate"` 14 | GoVersion string `json:"goVersion"` 15 | Compiler string `json:"compiler"` 16 | Platform string `json:"platform"` 17 | } 18 | 19 | // String returns info as a human-friendly version string. 20 | func (info Info) String() string { 21 | return info.GitTag 22 | } 23 | 24 | func Get() Info { 25 | return Info{ 26 | GitTag: gitTag, 27 | GitCommit: gitCommit, 28 | GitTreeState: gitTreeState, 29 | BuildDate: buildDate, 30 | GoVersion: runtime.Version(), 31 | Compiler: runtime.Compiler, 32 | Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH), 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /demo13/pkg/version/version.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | ) 7 | 8 | // Info contains versioning information. 9 | type Info struct { 10 | GitTag string `json:"gitTag"` 11 | GitCommit string `json:"gitCommit"` 12 | GitTreeState string `json:"gitTreeState"` 13 | BuildDate string `json:"buildDate"` 14 | GoVersion string `json:"goVersion"` 15 | Compiler string `json:"compiler"` 16 | Platform string `json:"platform"` 17 | } 18 | 19 | // String returns info as a human-friendly version string. 20 | func (info Info) String() string { 21 | return info.GitTag 22 | } 23 | 24 | func Get() Info { 25 | return Info{ 26 | GitTag: gitTag, 27 | GitCommit: gitCommit, 28 | GitTreeState: gitTreeState, 29 | BuildDate: buildDate, 30 | GoVersion: runtime.Version(), 31 | Compiler: runtime.Compiler, 32 | Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH), 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /demo14/pkg/version/version.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | ) 7 | 8 | // Info contains versioning information. 9 | type Info struct { 10 | GitTag string `json:"gitTag"` 11 | GitCommit string `json:"gitCommit"` 12 | GitTreeState string `json:"gitTreeState"` 13 | BuildDate string `json:"buildDate"` 14 | GoVersion string `json:"goVersion"` 15 | Compiler string `json:"compiler"` 16 | Platform string `json:"platform"` 17 | } 18 | 19 | // String returns info as a human-friendly version string. 20 | func (info Info) String() string { 21 | return info.GitTag 22 | } 23 | 24 | func Get() Info { 25 | return Info{ 26 | GitTag: gitTag, 27 | GitCommit: gitCommit, 28 | GitTreeState: gitTreeState, 29 | BuildDate: buildDate, 30 | GoVersion: runtime.Version(), 31 | Compiler: runtime.Compiler, 32 | Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH), 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /demo15/pkg/version/version.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | ) 7 | 8 | // Info contains versioning information. 9 | type Info struct { 10 | GitTag string `json:"gitTag"` 11 | GitCommit string `json:"gitCommit"` 12 | GitTreeState string `json:"gitTreeState"` 13 | BuildDate string `json:"buildDate"` 14 | GoVersion string `json:"goVersion"` 15 | Compiler string `json:"compiler"` 16 | Platform string `json:"platform"` 17 | } 18 | 19 | // String returns info as a human-friendly version string. 20 | func (info Info) String() string { 21 | return info.GitTag 22 | } 23 | 24 | func Get() Info { 25 | return Info{ 26 | GitTag: gitTag, 27 | GitCommit: gitCommit, 28 | GitTreeState: gitTreeState, 29 | BuildDate: buildDate, 30 | GoVersion: runtime.Version(), 31 | Compiler: runtime.Compiler, 32 | Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH), 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /demo16/pkg/version/version.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | ) 7 | 8 | // Info contains versioning information. 9 | type Info struct { 10 | GitTag string `json:"gitTag"` 11 | GitCommit string `json:"gitCommit"` 12 | GitTreeState string `json:"gitTreeState"` 13 | BuildDate string `json:"buildDate"` 14 | GoVersion string `json:"goVersion"` 15 | Compiler string `json:"compiler"` 16 | Platform string `json:"platform"` 17 | } 18 | 19 | // String returns info as a human-friendly version string. 20 | func (info Info) String() string { 21 | return info.GitTag 22 | } 23 | 24 | func Get() Info { 25 | return Info{ 26 | GitTag: gitTag, 27 | GitCommit: gitCommit, 28 | GitTreeState: gitTreeState, 29 | BuildDate: buildDate, 30 | GoVersion: runtime.Version(), 31 | Compiler: runtime.Compiler, 32 | Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH), 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /demo17/pkg/version/version.go: -------------------------------------------------------------------------------- 1 | package version 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | ) 7 | 8 | // Info contains versioning information. 9 | type Info struct { 10 | GitTag string `json:"gitTag"` 11 | GitCommit string `json:"gitCommit"` 12 | GitTreeState string `json:"gitTreeState"` 13 | BuildDate string `json:"buildDate"` 14 | GoVersion string `json:"goVersion"` 15 | Compiler string `json:"compiler"` 16 | Platform string `json:"platform"` 17 | } 18 | 19 | // String returns info as a human-friendly version string. 20 | func (info Info) String() string { 21 | return info.GitTag 22 | } 23 | 24 | func Get() Info { 25 | return Info{ 26 | GitTag: gitTag, 27 | GitCommit: gitCommit, 28 | GitTreeState: gitTreeState, 29 | BuildDate: buildDate, 30 | GoVersion: runtime.Version(), 31 | Compiler: runtime.Compiler, 32 | Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH), 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /demo07/pkg/errno/code.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | var ( 4 | // Common errors 5 | OK = &Errno{Code: 0, Message: "OK"} 6 | InternalServerError = &Errno{Code: 10001, Message: "Internal server error"} 7 | ErrBind = &Errno{Code: 10002, Message: "Error occurred while binding the request body to the struct."} 8 | 9 | ErrValidation = &Errno{Code: 20001, Message: "Validation failed."} 10 | ErrDatabase = &Errno{Code: 20002, Message: "Database error."} 11 | ErrToken = &Errno{Code: 20003, Message: "Error occurred while signing the JSON web token."} 12 | 13 | // user errors 14 | ErrEncrypt = &Errno{Code: 20101, Message: "Error occurred while encrypting the user password."} 15 | ErrUserNotFound = &Errno{Code: 20102, Message: "The user was not found."} 16 | ErrTokenInvalid = &Errno{Code: 20103, Message: "The token was invalid."} 17 | ErrPasswordIncorrect = &Errno{Code: 20104, Message: "The password was incorrect."} 18 | ) 19 | -------------------------------------------------------------------------------- /demo08/pkg/errno/code.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | var ( 4 | // Common errors 5 | OK = &Errno{Code: 0, Message: "OK"} 6 | InternalServerError = &Errno{Code: 10001, Message: "Internal server error"} 7 | ErrBind = &Errno{Code: 10002, Message: "Error occurred while binding the request body to the struct."} 8 | 9 | ErrValidation = &Errno{Code: 20001, Message: "Validation failed."} 10 | ErrDatabase = &Errno{Code: 20002, Message: "Database error."} 11 | ErrToken = &Errno{Code: 20003, Message: "Error occurred while signing the JSON web token."} 12 | 13 | // user errors 14 | ErrEncrypt = &Errno{Code: 20101, Message: "Error occurred while encrypting the user password."} 15 | ErrUserNotFound = &Errno{Code: 20102, Message: "The user was not found."} 16 | ErrTokenInvalid = &Errno{Code: 20103, Message: "The token was invalid."} 17 | ErrPasswordIncorrect = &Errno{Code: 20104, Message: "The password was incorrect."} 18 | ) 19 | -------------------------------------------------------------------------------- /demo09/pkg/errno/code.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | var ( 4 | // Common errors 5 | OK = &Errno{Code: 0, Message: "OK"} 6 | InternalServerError = &Errno{Code: 10001, Message: "Internal server error"} 7 | ErrBind = &Errno{Code: 10002, Message: "Error occurred while binding the request body to the struct."} 8 | 9 | ErrValidation = &Errno{Code: 20001, Message: "Validation failed."} 10 | ErrDatabase = &Errno{Code: 20002, Message: "Database error."} 11 | ErrToken = &Errno{Code: 20003, Message: "Error occurred while signing the JSON web token."} 12 | 13 | // user errors 14 | ErrEncrypt = &Errno{Code: 20101, Message: "Error occurred while encrypting the user password."} 15 | ErrUserNotFound = &Errno{Code: 20102, Message: "The user was not found."} 16 | ErrTokenInvalid = &Errno{Code: 20103, Message: "The token was invalid."} 17 | ErrPasswordIncorrect = &Errno{Code: 20104, Message: "The password was incorrect."} 18 | ) 19 | -------------------------------------------------------------------------------- /demo10/pkg/errno/code.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | var ( 4 | // Common errors 5 | OK = &Errno{Code: 0, Message: "OK"} 6 | InternalServerError = &Errno{Code: 10001, Message: "Internal server error"} 7 | ErrBind = &Errno{Code: 10002, Message: "Error occurred while binding the request body to the struct."} 8 | 9 | ErrValidation = &Errno{Code: 20001, Message: "Validation failed."} 10 | ErrDatabase = &Errno{Code: 20002, Message: "Database error."} 11 | ErrToken = &Errno{Code: 20003, Message: "Error occurred while signing the JSON web token."} 12 | 13 | // user errors 14 | ErrEncrypt = &Errno{Code: 20101, Message: "Error occurred while encrypting the user password."} 15 | ErrUserNotFound = &Errno{Code: 20102, Message: "The user was not found."} 16 | ErrTokenInvalid = &Errno{Code: 20103, Message: "The token was invalid."} 17 | ErrPasswordIncorrect = &Errno{Code: 20104, Message: "The password was incorrect."} 18 | ) 19 | -------------------------------------------------------------------------------- /demo11/pkg/errno/code.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | var ( 4 | // Common errors 5 | OK = &Errno{Code: 0, Message: "OK"} 6 | InternalServerError = &Errno{Code: 10001, Message: "Internal server error"} 7 | ErrBind = &Errno{Code: 10002, Message: "Error occurred while binding the request body to the struct."} 8 | 9 | ErrValidation = &Errno{Code: 20001, Message: "Validation failed."} 10 | ErrDatabase = &Errno{Code: 20002, Message: "Database error."} 11 | ErrToken = &Errno{Code: 20003, Message: "Error occurred while signing the JSON web token."} 12 | 13 | // user errors 14 | ErrEncrypt = &Errno{Code: 20101, Message: "Error occurred while encrypting the user password."} 15 | ErrUserNotFound = &Errno{Code: 20102, Message: "The user was not found."} 16 | ErrTokenInvalid = &Errno{Code: 20103, Message: "The token was invalid."} 17 | ErrPasswordIncorrect = &Errno{Code: 20104, Message: "The password was incorrect."} 18 | ) 19 | -------------------------------------------------------------------------------- /demo12/pkg/errno/code.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | var ( 4 | // Common errors 5 | OK = &Errno{Code: 0, Message: "OK"} 6 | InternalServerError = &Errno{Code: 10001, Message: "Internal server error"} 7 | ErrBind = &Errno{Code: 10002, Message: "Error occurred while binding the request body to the struct."} 8 | 9 | ErrValidation = &Errno{Code: 20001, Message: "Validation failed."} 10 | ErrDatabase = &Errno{Code: 20002, Message: "Database error."} 11 | ErrToken = &Errno{Code: 20003, Message: "Error occurred while signing the JSON web token."} 12 | 13 | // user errors 14 | ErrEncrypt = &Errno{Code: 20101, Message: "Error occurred while encrypting the user password."} 15 | ErrUserNotFound = &Errno{Code: 20102, Message: "The user was not found."} 16 | ErrTokenInvalid = &Errno{Code: 20103, Message: "The token was invalid."} 17 | ErrPasswordIncorrect = &Errno{Code: 20104, Message: "The password was incorrect."} 18 | ) 19 | -------------------------------------------------------------------------------- /demo13/pkg/errno/code.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | var ( 4 | // Common errors 5 | OK = &Errno{Code: 0, Message: "OK"} 6 | InternalServerError = &Errno{Code: 10001, Message: "Internal server error"} 7 | ErrBind = &Errno{Code: 10002, Message: "Error occurred while binding the request body to the struct."} 8 | 9 | ErrValidation = &Errno{Code: 20001, Message: "Validation failed."} 10 | ErrDatabase = &Errno{Code: 20002, Message: "Database error."} 11 | ErrToken = &Errno{Code: 20003, Message: "Error occurred while signing the JSON web token."} 12 | 13 | // user errors 14 | ErrEncrypt = &Errno{Code: 20101, Message: "Error occurred while encrypting the user password."} 15 | ErrUserNotFound = &Errno{Code: 20102, Message: "The user was not found."} 16 | ErrTokenInvalid = &Errno{Code: 20103, Message: "The token was invalid."} 17 | ErrPasswordIncorrect = &Errno{Code: 20104, Message: "The password was incorrect."} 18 | ) 19 | -------------------------------------------------------------------------------- /demo14/pkg/errno/code.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | var ( 4 | // Common errors 5 | OK = &Errno{Code: 0, Message: "OK"} 6 | InternalServerError = &Errno{Code: 10001, Message: "Internal server error"} 7 | ErrBind = &Errno{Code: 10002, Message: "Error occurred while binding the request body to the struct."} 8 | 9 | ErrValidation = &Errno{Code: 20001, Message: "Validation failed."} 10 | ErrDatabase = &Errno{Code: 20002, Message: "Database error."} 11 | ErrToken = &Errno{Code: 20003, Message: "Error occurred while signing the JSON web token."} 12 | 13 | // user errors 14 | ErrEncrypt = &Errno{Code: 20101, Message: "Error occurred while encrypting the user password."} 15 | ErrUserNotFound = &Errno{Code: 20102, Message: "The user was not found."} 16 | ErrTokenInvalid = &Errno{Code: 20103, Message: "The token was invalid."} 17 | ErrPasswordIncorrect = &Errno{Code: 20104, Message: "The password was incorrect."} 18 | ) 19 | -------------------------------------------------------------------------------- /demo15/pkg/errno/code.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | var ( 4 | // Common errors 5 | OK = &Errno{Code: 0, Message: "OK"} 6 | InternalServerError = &Errno{Code: 10001, Message: "Internal server error"} 7 | ErrBind = &Errno{Code: 10002, Message: "Error occurred while binding the request body to the struct."} 8 | 9 | ErrValidation = &Errno{Code: 20001, Message: "Validation failed."} 10 | ErrDatabase = &Errno{Code: 20002, Message: "Database error."} 11 | ErrToken = &Errno{Code: 20003, Message: "Error occurred while signing the JSON web token."} 12 | 13 | // user errors 14 | ErrEncrypt = &Errno{Code: 20101, Message: "Error occurred while encrypting the user password."} 15 | ErrUserNotFound = &Errno{Code: 20102, Message: "The user was not found."} 16 | ErrTokenInvalid = &Errno{Code: 20103, Message: "The token was invalid."} 17 | ErrPasswordIncorrect = &Errno{Code: 20104, Message: "The password was incorrect."} 18 | ) 19 | -------------------------------------------------------------------------------- /demo16/pkg/errno/code.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | var ( 4 | // Common errors 5 | OK = &Errno{Code: 0, Message: "OK"} 6 | InternalServerError = &Errno{Code: 10001, Message: "Internal server error"} 7 | ErrBind = &Errno{Code: 10002, Message: "Error occurred while binding the request body to the struct."} 8 | 9 | ErrValidation = &Errno{Code: 20001, Message: "Validation failed."} 10 | ErrDatabase = &Errno{Code: 20002, Message: "Database error."} 11 | ErrToken = &Errno{Code: 20003, Message: "Error occurred while signing the JSON web token."} 12 | 13 | // user errors 14 | ErrEncrypt = &Errno{Code: 20101, Message: "Error occurred while encrypting the user password."} 15 | ErrUserNotFound = &Errno{Code: 20102, Message: "The user was not found."} 16 | ErrTokenInvalid = &Errno{Code: 20103, Message: "The token was invalid."} 17 | ErrPasswordIncorrect = &Errno{Code: 20104, Message: "The password was incorrect."} 18 | ) 19 | -------------------------------------------------------------------------------- /demo17/pkg/errno/code.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | var ( 4 | // Common errors 5 | OK = &Errno{Code: 0, Message: "OK"} 6 | InternalServerError = &Errno{Code: 10001, Message: "Internal server error"} 7 | ErrBind = &Errno{Code: 10002, Message: "Error occurred while binding the request body to the struct."} 8 | 9 | ErrValidation = &Errno{Code: 20001, Message: "Validation failed."} 10 | ErrDatabase = &Errno{Code: 20002, Message: "Database error."} 11 | ErrToken = &Errno{Code: 20003, Message: "Error occurred while signing the JSON web token."} 12 | 13 | // user errors 14 | ErrEncrypt = &Errno{Code: 20101, Message: "Error occurred while encrypting the user password."} 15 | ErrUserNotFound = &Errno{Code: 20102, Message: "The user was not found."} 16 | ErrTokenInvalid = &Errno{Code: 20103, Message: "The token was invalid."} 17 | ErrPasswordIncorrect = &Errno{Code: 20104, Message: "The password was incorrect."} 18 | ) 19 | -------------------------------------------------------------------------------- /demo05/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/handler/user" 8 | "apiserver/router/middleware" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Load loads the middlewares, routes, handlers. 14 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 15 | // Middlewares. 16 | g.Use(gin.Recovery()) 17 | g.Use(middleware.NoCache) 18 | g.Use(middleware.Options) 19 | g.Use(middleware.Secure) 20 | g.Use(mw...) 21 | // 404 Handler. 22 | g.NoRoute(func(c *gin.Context) { 23 | c.String(http.StatusNotFound, "The incorrect API route.") 24 | }) 25 | 26 | u := g.Group("/v1/user") 27 | { 28 | u.POST("", user.Create) 29 | } 30 | 31 | // The health check handlers 32 | svcd := g.Group("/sd") 33 | { 34 | svcd.GET("/health", sd.HealthCheck) 35 | svcd.GET("/disk", sd.DiskCheck) 36 | svcd.GET("/cpu", sd.CPUCheck) 37 | svcd.GET("/ram", sd.RAMCheck) 38 | } 39 | 40 | return g 41 | } 42 | -------------------------------------------------------------------------------- /demo06/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/handler/user" 8 | "apiserver/router/middleware" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Load loads the middlewares, routes, handlers. 14 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 15 | // Middlewares. 16 | g.Use(gin.Recovery()) 17 | g.Use(middleware.NoCache) 18 | g.Use(middleware.Options) 19 | g.Use(middleware.Secure) 20 | g.Use(mw...) 21 | // 404 Handler. 22 | g.NoRoute(func(c *gin.Context) { 23 | c.String(http.StatusNotFound, "The incorrect API route.") 24 | }) 25 | 26 | u := g.Group("/v1/user") 27 | { 28 | u.POST("/:username", user.Create) 29 | } 30 | 31 | // The health check handlers 32 | svcd := g.Group("/sd") 33 | { 34 | svcd.GET("/health", sd.HealthCheck) 35 | svcd.GET("/disk", sd.DiskCheck) 36 | svcd.GET("/cpu", sd.CPUCheck) 37 | svcd.GET("/ram", sd.RAMCheck) 38 | } 39 | 40 | return g 41 | } 42 | -------------------------------------------------------------------------------- /demo07/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/handler/user" 8 | "apiserver/router/middleware" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Load loads the middlewares, routes, handlers. 14 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 15 | // Middlewares. 16 | g.Use(gin.Recovery()) 17 | g.Use(middleware.NoCache) 18 | g.Use(middleware.Options) 19 | g.Use(middleware.Secure) 20 | g.Use(mw...) 21 | // 404 Handler. 22 | g.NoRoute(func(c *gin.Context) { 23 | c.String(http.StatusNotFound, "The incorrect API route.") 24 | }) 25 | 26 | u := g.Group("/v1/user") 27 | { 28 | u.POST("", user.Create) 29 | u.DELETE("/:id", user.Delete) 30 | u.PUT("/:id", user.Update) 31 | u.GET("", user.List) 32 | u.GET("/:username", user.Get) 33 | } 34 | 35 | // The health check handlers 36 | svcd := g.Group("/sd") 37 | { 38 | svcd.GET("/health", sd.HealthCheck) 39 | svcd.GET("/disk", sd.DiskCheck) 40 | svcd.GET("/cpu", sd.CPUCheck) 41 | svcd.GET("/ram", sd.RAMCheck) 42 | } 43 | 44 | return g 45 | } 46 | -------------------------------------------------------------------------------- /demo08/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/handler/user" 8 | "apiserver/router/middleware" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Load loads the middlewares, routes, handlers. 14 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 15 | // Middlewares. 16 | g.Use(gin.Recovery()) 17 | g.Use(middleware.NoCache) 18 | g.Use(middleware.Options) 19 | g.Use(middleware.Secure) 20 | g.Use(mw...) 21 | // 404 Handler. 22 | g.NoRoute(func(c *gin.Context) { 23 | c.String(http.StatusNotFound, "The incorrect API route.") 24 | }) 25 | 26 | u := g.Group("/v1/user") 27 | { 28 | u.POST("", user.Create) 29 | u.DELETE("/:id", user.Delete) 30 | u.PUT("/:id", user.Update) 31 | u.GET("", user.List) 32 | u.GET("/:username", user.Get) 33 | } 34 | 35 | // The health check handlers 36 | svcd := g.Group("/sd") 37 | { 38 | svcd.GET("/health", sd.HealthCheck) 39 | svcd.GET("/disk", sd.DiskCheck) 40 | svcd.GET("/cpu", sd.CPUCheck) 41 | svcd.GET("/ram", sd.RAMCheck) 42 | } 43 | 44 | return g 45 | } 46 | -------------------------------------------------------------------------------- /demo05/handler/user/create.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | 7 | "apiserver/pkg/errno" 8 | 9 | "github.com/gin-gonic/gin" 10 | "github.com/lexkong/log" 11 | ) 12 | 13 | // Create creates a new user account. 14 | func Create(c *gin.Context) { 15 | var r struct { 16 | Username string `json:"username"` 17 | Password string `json:"password"` 18 | } 19 | 20 | var err error 21 | if err := c.Bind(&r); err != nil { 22 | c.JSON(http.StatusOK, gin.H{"error": errno.ErrBind}) 23 | return 24 | } 25 | 26 | log.Debugf("username is: [%s], password is [%s]", r.Username, r.Password) 27 | if r.Username == "" { 28 | err = errno.New(errno.ErrUserNotFound, fmt.Errorf("username can not found in db: xx.xx.xx.xx")).Add("This is add message.") 29 | log.Errorf(err, "Get an error") 30 | } 31 | 32 | if errno.IsErrUserNotFound(err) { 33 | log.Debug("err type is ErrUserNotFound") 34 | } 35 | 36 | if r.Password == "" { 37 | err = fmt.Errorf("password is empty") 38 | } 39 | 40 | code, message := errno.DecodeErr(err) 41 | c.JSON(http.StatusOK, gin.H{"code": code, "message": message}) 42 | } 43 | -------------------------------------------------------------------------------- /demo06/handler/user/create.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "fmt" 5 | 6 | . "apiserver/handler" 7 | "apiserver/pkg/errno" 8 | 9 | "github.com/gin-gonic/gin" 10 | "github.com/lexkong/log" 11 | ) 12 | 13 | // Create creates a new user account. 14 | func Create(c *gin.Context) { 15 | var r CreateRequest 16 | if err := c.Bind(&r); err != nil { 17 | SendResponse(c, errno.ErrBind, nil) 18 | return 19 | } 20 | 21 | admin2 := c.Param("username") 22 | log.Infof("URL username: %s", admin2) 23 | 24 | desc := c.Query("desc") 25 | log.Infof("URL key param desc: %s", desc) 26 | 27 | contentType := c.GetHeader("Content-Type") 28 | log.Infof("Header Content-Type: %s", contentType) 29 | 30 | log.Debugf("username is: [%s], password is [%s]", r.Username, r.Password) 31 | if r.Username == "" { 32 | SendResponse(c, errno.New(errno.ErrUserNotFound, fmt.Errorf("username can not found in db: xx.xx.xx.xx")), nil) 33 | return 34 | } 35 | 36 | if r.Password == "" { 37 | SendResponse(c, fmt.Errorf("password is empty"), nil) 38 | } 39 | 40 | rsp := CreateResponse{ 41 | Username: r.Username, 42 | } 43 | 44 | // Show the user information. 45 | SendResponse(c, nil, rsp) 46 | } 47 | -------------------------------------------------------------------------------- /demo09/handler/user/login.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/auth" 7 | "apiserver/pkg/errno" 8 | "apiserver/pkg/token" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Login generates the authentication token 14 | // if the password was matched with the specified account. 15 | func Login(c *gin.Context) { 16 | // Binding the data with the user struct. 17 | var u model.UserModel 18 | if err := c.Bind(&u); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | // Get the user information by the login username. 24 | d, err := model.GetUser(u.Username) 25 | if err != nil { 26 | SendResponse(c, errno.ErrUserNotFound, nil) 27 | return 28 | } 29 | 30 | // Compare the login password with the user password. 31 | if err := auth.Compare(d.Password, u.Password); err != nil { 32 | SendResponse(c, errno.ErrPasswordIncorrect, nil) 33 | return 34 | } 35 | 36 | // Sign the json web token. 37 | t, err := token.Sign(c, token.Context{ID: d.Id, Username: d.Username}, "") 38 | if err != nil { 39 | SendResponse(c, errno.ErrToken, nil) 40 | return 41 | } 42 | 43 | SendResponse(c, nil, model.Token{Token: t}) 44 | } 45 | -------------------------------------------------------------------------------- /demo10/handler/user/login.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/auth" 7 | "apiserver/pkg/errno" 8 | "apiserver/pkg/token" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Login generates the authentication token 14 | // if the password was matched with the specified account. 15 | func Login(c *gin.Context) { 16 | // Binding the data with the user struct. 17 | var u model.UserModel 18 | if err := c.Bind(&u); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | // Get the user information by the login username. 24 | d, err := model.GetUser(u.Username) 25 | if err != nil { 26 | SendResponse(c, errno.ErrUserNotFound, nil) 27 | return 28 | } 29 | 30 | // Compare the login password with the user password. 31 | if err := auth.Compare(d.Password, u.Password); err != nil { 32 | SendResponse(c, errno.ErrPasswordIncorrect, nil) 33 | return 34 | } 35 | 36 | // Sign the json web token. 37 | t, err := token.Sign(c, token.Context{ID: d.Id, Username: d.Username}, "") 38 | if err != nil { 39 | SendResponse(c, errno.ErrToken, nil) 40 | return 41 | } 42 | 43 | SendResponse(c, nil, model.Token{Token: t}) 44 | } 45 | -------------------------------------------------------------------------------- /demo11/handler/user/login.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/auth" 7 | "apiserver/pkg/errno" 8 | "apiserver/pkg/token" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Login generates the authentication token 14 | // if the password was matched with the specified account. 15 | func Login(c *gin.Context) { 16 | // Binding the data with the user struct. 17 | var u model.UserModel 18 | if err := c.Bind(&u); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | // Get the user information by the login username. 24 | d, err := model.GetUser(u.Username) 25 | if err != nil { 26 | SendResponse(c, errno.ErrUserNotFound, nil) 27 | return 28 | } 29 | 30 | // Compare the login password with the user password. 31 | if err := auth.Compare(d.Password, u.Password); err != nil { 32 | SendResponse(c, errno.ErrPasswordIncorrect, nil) 33 | return 34 | } 35 | 36 | // Sign the json web token. 37 | t, err := token.Sign(c, token.Context{ID: d.Id, Username: d.Username}, "") 38 | if err != nil { 39 | SendResponse(c, errno.ErrToken, nil) 40 | return 41 | } 42 | 43 | SendResponse(c, nil, model.Token{Token: t}) 44 | } 45 | -------------------------------------------------------------------------------- /demo12/handler/user/login.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/auth" 7 | "apiserver/pkg/errno" 8 | "apiserver/pkg/token" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Login generates the authentication token 14 | // if the password was matched with the specified account. 15 | func Login(c *gin.Context) { 16 | // Binding the data with the user struct. 17 | var u model.UserModel 18 | if err := c.Bind(&u); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | // Get the user information by the login username. 24 | d, err := model.GetUser(u.Username) 25 | if err != nil { 26 | SendResponse(c, errno.ErrUserNotFound, nil) 27 | return 28 | } 29 | 30 | // Compare the login password with the user password. 31 | if err := auth.Compare(d.Password, u.Password); err != nil { 32 | SendResponse(c, errno.ErrPasswordIncorrect, nil) 33 | return 34 | } 35 | 36 | // Sign the json web token. 37 | t, err := token.Sign(c, token.Context{ID: d.Id, Username: d.Username}, "") 38 | if err != nil { 39 | SendResponse(c, errno.ErrToken, nil) 40 | return 41 | } 42 | 43 | SendResponse(c, nil, model.Token{Token: t}) 44 | } 45 | -------------------------------------------------------------------------------- /demo13/handler/user/login.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/auth" 7 | "apiserver/pkg/errno" 8 | "apiserver/pkg/token" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Login generates the authentication token 14 | // if the password was matched with the specified account. 15 | func Login(c *gin.Context) { 16 | // Binding the data with the user struct. 17 | var u model.UserModel 18 | if err := c.Bind(&u); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | // Get the user information by the login username. 24 | d, err := model.GetUser(u.Username) 25 | if err != nil { 26 | SendResponse(c, errno.ErrUserNotFound, nil) 27 | return 28 | } 29 | 30 | // Compare the login password with the user password. 31 | if err := auth.Compare(d.Password, u.Password); err != nil { 32 | SendResponse(c, errno.ErrPasswordIncorrect, nil) 33 | return 34 | } 35 | 36 | // Sign the json web token. 37 | t, err := token.Sign(c, token.Context{ID: d.Id, Username: d.Username}, "") 38 | if err != nil { 39 | SendResponse(c, errno.ErrToken, nil) 40 | return 41 | } 42 | 43 | SendResponse(c, nil, model.Token{Token: t}) 44 | } 45 | -------------------------------------------------------------------------------- /demo14/handler/user/login.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/auth" 7 | "apiserver/pkg/errno" 8 | "apiserver/pkg/token" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Login generates the authentication token 14 | // if the password was matched with the specified account. 15 | func Login(c *gin.Context) { 16 | // Binding the data with the user struct. 17 | var u model.UserModel 18 | if err := c.Bind(&u); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | // Get the user information by the login username. 24 | d, err := model.GetUser(u.Username) 25 | if err != nil { 26 | SendResponse(c, errno.ErrUserNotFound, nil) 27 | return 28 | } 29 | 30 | // Compare the login password with the user password. 31 | if err := auth.Compare(d.Password, u.Password); err != nil { 32 | SendResponse(c, errno.ErrPasswordIncorrect, nil) 33 | return 34 | } 35 | 36 | // Sign the json web token. 37 | t, err := token.Sign(c, token.Context{ID: d.Id, Username: d.Username}, "") 38 | if err != nil { 39 | SendResponse(c, errno.ErrToken, nil) 40 | return 41 | } 42 | 43 | SendResponse(c, nil, model.Token{Token: t}) 44 | } 45 | -------------------------------------------------------------------------------- /demo15/handler/user/login.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/auth" 7 | "apiserver/pkg/errno" 8 | "apiserver/pkg/token" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Login generates the authentication token 14 | // if the password was matched with the specified account. 15 | func Login(c *gin.Context) { 16 | // Binding the data with the user struct. 17 | var u model.UserModel 18 | if err := c.Bind(&u); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | // Get the user information by the login username. 24 | d, err := model.GetUser(u.Username) 25 | if err != nil { 26 | SendResponse(c, errno.ErrUserNotFound, nil) 27 | return 28 | } 29 | 30 | // Compare the login password with the user password. 31 | if err := auth.Compare(d.Password, u.Password); err != nil { 32 | SendResponse(c, errno.ErrPasswordIncorrect, nil) 33 | return 34 | } 35 | 36 | // Sign the json web token. 37 | t, err := token.Sign(c, token.Context{ID: d.Id, Username: d.Username}, "") 38 | if err != nil { 39 | SendResponse(c, errno.ErrToken, nil) 40 | return 41 | } 42 | 43 | SendResponse(c, nil, model.Token{Token: t}) 44 | } 45 | -------------------------------------------------------------------------------- /demo16/handler/user/login.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/auth" 7 | "apiserver/pkg/errno" 8 | "apiserver/pkg/token" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Login generates the authentication token 14 | // if the password was matched with the specified account. 15 | func Login(c *gin.Context) { 16 | // Binding the data with the user struct. 17 | var u model.UserModel 18 | if err := c.Bind(&u); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | // Get the user information by the login username. 24 | d, err := model.GetUser(u.Username) 25 | if err != nil { 26 | SendResponse(c, errno.ErrUserNotFound, nil) 27 | return 28 | } 29 | 30 | // Compare the login password with the user password. 31 | if err := auth.Compare(d.Password, u.Password); err != nil { 32 | SendResponse(c, errno.ErrPasswordIncorrect, nil) 33 | return 34 | } 35 | 36 | // Sign the json web token. 37 | t, err := token.Sign(c, token.Context{ID: d.Id, Username: d.Username}, "") 38 | if err != nil { 39 | SendResponse(c, errno.ErrToken, nil) 40 | return 41 | } 42 | 43 | SendResponse(c, nil, model.Token{Token: t}) 44 | } 45 | -------------------------------------------------------------------------------- /demo17/handler/user/list.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/pkg/errno" 6 | "apiserver/service" 7 | 8 | "github.com/gin-gonic/gin" 9 | "github.com/lexkong/log" 10 | ) 11 | 12 | // @Summary List the users in the database 13 | // @Description List users 14 | // @Tags user 15 | // @Accept json 16 | // @Produce json 17 | // @Param user body user.ListRequest true "List users" 18 | // @Success 200 {object} user.SwaggerListResponse "{"code":0,"message":"OK","data":{"totalCount":1,"userList":[{"id":0,"username":"admin","random":"user 'admin' get random string 'EnqntiSig'","password":"$2a$10$veGcArz47VGj7l9xN7g2iuT9TF21jLI1YGXarGzvARNdnt4inC9PG","createdAt":"2018-05-28 00:25:33","updatedAt":"2018-05-28 00:25:33"}]}}" 19 | // @Router /user [get] 20 | func List(c *gin.Context) { 21 | log.Info("List function called.") 22 | var r ListRequest 23 | if err := c.Bind(&r); err != nil { 24 | SendResponse(c, errno.ErrBind, nil) 25 | return 26 | } 27 | 28 | infos, count, err := service.ListUser(r.Username, r.Offset, r.Limit) 29 | if err != nil { 30 | SendResponse(c, err, nil) 31 | return 32 | } 33 | 34 | SendResponse(c, nil, ListResponse{ 35 | TotalCount: count, 36 | UserList: infos, 37 | }) 38 | } 39 | -------------------------------------------------------------------------------- /demo07/handler/user/create.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | "apiserver/util" 8 | 9 | "github.com/gin-gonic/gin" 10 | "github.com/lexkong/log" 11 | "github.com/lexkong/log/lager" 12 | ) 13 | 14 | // Create creates a new user account. 15 | func Create(c *gin.Context) { 16 | log.Info("User Create function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 17 | var r CreateRequest 18 | if err := c.Bind(&r); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | u := model.UserModel{ 24 | Username: r.Username, 25 | Password: r.Password, 26 | } 27 | 28 | // Validate the data. 29 | if err := u.Validate(); err != nil { 30 | SendResponse(c, errno.ErrValidation, nil) 31 | return 32 | } 33 | 34 | // Encrypt the user password. 35 | if err := u.Encrypt(); err != nil { 36 | SendResponse(c, errno.ErrEncrypt, nil) 37 | return 38 | } 39 | // Insert the user to the database. 40 | if err := u.Create(); err != nil { 41 | SendResponse(c, errno.ErrDatabase, nil) 42 | return 43 | } 44 | 45 | rsp := CreateResponse{ 46 | Username: r.Username, 47 | } 48 | 49 | // Show the user information. 50 | SendResponse(c, nil, rsp) 51 | } 52 | -------------------------------------------------------------------------------- /demo08/handler/user/create.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | "apiserver/util" 8 | 9 | "github.com/gin-gonic/gin" 10 | "github.com/lexkong/log" 11 | "github.com/lexkong/log/lager" 12 | ) 13 | 14 | // Create creates a new user account. 15 | func Create(c *gin.Context) { 16 | log.Info("User Create function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 17 | var r CreateRequest 18 | if err := c.Bind(&r); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | u := model.UserModel{ 24 | Username: r.Username, 25 | Password: r.Password, 26 | } 27 | 28 | // Validate the data. 29 | if err := u.Validate(); err != nil { 30 | SendResponse(c, errno.ErrValidation, nil) 31 | return 32 | } 33 | 34 | // Encrypt the user password. 35 | if err := u.Encrypt(); err != nil { 36 | SendResponse(c, errno.ErrEncrypt, nil) 37 | return 38 | } 39 | // Insert the user to the database. 40 | if err := u.Create(); err != nil { 41 | SendResponse(c, errno.ErrDatabase, nil) 42 | return 43 | } 44 | 45 | rsp := CreateResponse{ 46 | Username: r.Username, 47 | } 48 | 49 | // Show the user information. 50 | SendResponse(c, nil, rsp) 51 | } 52 | -------------------------------------------------------------------------------- /demo09/handler/user/create.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | "apiserver/util" 8 | 9 | "github.com/gin-gonic/gin" 10 | "github.com/lexkong/log" 11 | "github.com/lexkong/log/lager" 12 | ) 13 | 14 | // Create creates a new user account. 15 | func Create(c *gin.Context) { 16 | log.Info("User Create function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 17 | var r CreateRequest 18 | if err := c.Bind(&r); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | u := model.UserModel{ 24 | Username: r.Username, 25 | Password: r.Password, 26 | } 27 | 28 | // Validate the data. 29 | if err := u.Validate(); err != nil { 30 | SendResponse(c, errno.ErrValidation, nil) 31 | return 32 | } 33 | 34 | // Encrypt the user password. 35 | if err := u.Encrypt(); err != nil { 36 | SendResponse(c, errno.ErrEncrypt, nil) 37 | return 38 | } 39 | // Insert the user to the database. 40 | if err := u.Create(); err != nil { 41 | SendResponse(c, errno.ErrDatabase, nil) 42 | return 43 | } 44 | 45 | rsp := CreateResponse{ 46 | Username: r.Username, 47 | } 48 | 49 | // Show the user information. 50 | SendResponse(c, nil, rsp) 51 | } 52 | -------------------------------------------------------------------------------- /demo10/handler/user/create.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | "apiserver/util" 8 | 9 | "github.com/gin-gonic/gin" 10 | "github.com/lexkong/log" 11 | "github.com/lexkong/log/lager" 12 | ) 13 | 14 | // Create creates a new user account. 15 | func Create(c *gin.Context) { 16 | log.Info("User Create function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 17 | var r CreateRequest 18 | if err := c.Bind(&r); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | u := model.UserModel{ 24 | Username: r.Username, 25 | Password: r.Password, 26 | } 27 | 28 | // Validate the data. 29 | if err := u.Validate(); err != nil { 30 | SendResponse(c, errno.ErrValidation, nil) 31 | return 32 | } 33 | 34 | // Encrypt the user password. 35 | if err := u.Encrypt(); err != nil { 36 | SendResponse(c, errno.ErrEncrypt, nil) 37 | return 38 | } 39 | // Insert the user to the database. 40 | if err := u.Create(); err != nil { 41 | SendResponse(c, errno.ErrDatabase, nil) 42 | return 43 | } 44 | 45 | rsp := CreateResponse{ 46 | Username: r.Username, 47 | } 48 | 49 | // Show the user information. 50 | SendResponse(c, nil, rsp) 51 | } 52 | -------------------------------------------------------------------------------- /demo11/handler/user/create.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | "apiserver/util" 8 | 9 | "github.com/gin-gonic/gin" 10 | "github.com/lexkong/log" 11 | "github.com/lexkong/log/lager" 12 | ) 13 | 14 | // Create creates a new user account. 15 | func Create(c *gin.Context) { 16 | log.Info("User Create function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 17 | var r CreateRequest 18 | if err := c.Bind(&r); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | u := model.UserModel{ 24 | Username: r.Username, 25 | Password: r.Password, 26 | } 27 | 28 | // Validate the data. 29 | if err := u.Validate(); err != nil { 30 | SendResponse(c, errno.ErrValidation, nil) 31 | return 32 | } 33 | 34 | // Encrypt the user password. 35 | if err := u.Encrypt(); err != nil { 36 | SendResponse(c, errno.ErrEncrypt, nil) 37 | return 38 | } 39 | // Insert the user to the database. 40 | if err := u.Create(); err != nil { 41 | SendResponse(c, errno.ErrDatabase, nil) 42 | return 43 | } 44 | 45 | rsp := CreateResponse{ 46 | Username: r.Username, 47 | } 48 | 49 | // Show the user information. 50 | SendResponse(c, nil, rsp) 51 | } 52 | -------------------------------------------------------------------------------- /demo12/handler/user/create.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | "apiserver/util" 8 | 9 | "github.com/gin-gonic/gin" 10 | "github.com/lexkong/log" 11 | "github.com/lexkong/log/lager" 12 | ) 13 | 14 | // Create creates a new user account. 15 | func Create(c *gin.Context) { 16 | log.Info("User Create function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 17 | var r CreateRequest 18 | if err := c.Bind(&r); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | u := model.UserModel{ 24 | Username: r.Username, 25 | Password: r.Password, 26 | } 27 | 28 | // Validate the data. 29 | if err := u.Validate(); err != nil { 30 | SendResponse(c, errno.ErrValidation, nil) 31 | return 32 | } 33 | 34 | // Encrypt the user password. 35 | if err := u.Encrypt(); err != nil { 36 | SendResponse(c, errno.ErrEncrypt, nil) 37 | return 38 | } 39 | // Insert the user to the database. 40 | if err := u.Create(); err != nil { 41 | SendResponse(c, errno.ErrDatabase, nil) 42 | return 43 | } 44 | 45 | rsp := CreateResponse{ 46 | Username: r.Username, 47 | } 48 | 49 | // Show the user information. 50 | SendResponse(c, nil, rsp) 51 | } 52 | -------------------------------------------------------------------------------- /demo13/handler/user/create.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | "apiserver/util" 8 | 9 | "github.com/gin-gonic/gin" 10 | "github.com/lexkong/log" 11 | "github.com/lexkong/log/lager" 12 | ) 13 | 14 | // Create creates a new user account. 15 | func Create(c *gin.Context) { 16 | log.Info("User Create function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 17 | var r CreateRequest 18 | if err := c.Bind(&r); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | u := model.UserModel{ 24 | Username: r.Username, 25 | Password: r.Password, 26 | } 27 | 28 | // Validate the data. 29 | if err := u.Validate(); err != nil { 30 | SendResponse(c, errno.ErrValidation, nil) 31 | return 32 | } 33 | 34 | // Encrypt the user password. 35 | if err := u.Encrypt(); err != nil { 36 | SendResponse(c, errno.ErrEncrypt, nil) 37 | return 38 | } 39 | // Insert the user to the database. 40 | if err := u.Create(); err != nil { 41 | SendResponse(c, errno.ErrDatabase, nil) 42 | return 43 | } 44 | 45 | rsp := CreateResponse{ 46 | Username: r.Username, 47 | } 48 | 49 | // Show the user information. 50 | SendResponse(c, nil, rsp) 51 | } 52 | -------------------------------------------------------------------------------- /demo14/handler/user/create.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | "apiserver/util" 8 | 9 | "github.com/gin-gonic/gin" 10 | "github.com/lexkong/log" 11 | "github.com/lexkong/log/lager" 12 | ) 13 | 14 | // Create creates a new user account. 15 | func Create(c *gin.Context) { 16 | log.Info("User Create function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 17 | var r CreateRequest 18 | if err := c.Bind(&r); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | u := model.UserModel{ 24 | Username: r.Username, 25 | Password: r.Password, 26 | } 27 | 28 | // Validate the data. 29 | if err := u.Validate(); err != nil { 30 | SendResponse(c, errno.ErrValidation, nil) 31 | return 32 | } 33 | 34 | // Encrypt the user password. 35 | if err := u.Encrypt(); err != nil { 36 | SendResponse(c, errno.ErrEncrypt, nil) 37 | return 38 | } 39 | // Insert the user to the database. 40 | if err := u.Create(); err != nil { 41 | SendResponse(c, errno.ErrDatabase, nil) 42 | return 43 | } 44 | 45 | rsp := CreateResponse{ 46 | Username: r.Username, 47 | } 48 | 49 | // Show the user information. 50 | SendResponse(c, nil, rsp) 51 | } 52 | -------------------------------------------------------------------------------- /demo15/handler/user/create.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | "apiserver/util" 8 | 9 | "github.com/gin-gonic/gin" 10 | "github.com/lexkong/log" 11 | "github.com/lexkong/log/lager" 12 | ) 13 | 14 | // Create creates a new user account. 15 | func Create(c *gin.Context) { 16 | log.Info("User Create function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 17 | var r CreateRequest 18 | if err := c.Bind(&r); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | u := model.UserModel{ 24 | Username: r.Username, 25 | Password: r.Password, 26 | } 27 | 28 | // Validate the data. 29 | if err := u.Validate(); err != nil { 30 | SendResponse(c, errno.ErrValidation, nil) 31 | return 32 | } 33 | 34 | // Encrypt the user password. 35 | if err := u.Encrypt(); err != nil { 36 | SendResponse(c, errno.ErrEncrypt, nil) 37 | return 38 | } 39 | // Insert the user to the database. 40 | if err := u.Create(); err != nil { 41 | SendResponse(c, errno.ErrDatabase, nil) 42 | return 43 | } 44 | 45 | rsp := CreateResponse{ 46 | Username: r.Username, 47 | } 48 | 49 | // Show the user information. 50 | SendResponse(c, nil, rsp) 51 | } 52 | -------------------------------------------------------------------------------- /demo16/handler/user/create.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "apiserver/handler" 5 | "apiserver/model" 6 | "apiserver/pkg/errno" 7 | "apiserver/util" 8 | 9 | "github.com/gin-gonic/gin" 10 | "github.com/lexkong/log" 11 | "github.com/lexkong/log/lager" 12 | ) 13 | 14 | // Create creates a new user account. 15 | func Create(c *gin.Context) { 16 | log.Info("User Create function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 17 | var r CreateRequest 18 | if err := c.Bind(&r); err != nil { 19 | SendResponse(c, errno.ErrBind, nil) 20 | return 21 | } 22 | 23 | u := model.UserModel{ 24 | Username: r.Username, 25 | Password: r.Password, 26 | } 27 | 28 | // Validate the data. 29 | if err := u.Validate(); err != nil { 30 | SendResponse(c, errno.ErrValidation, nil) 31 | return 32 | } 33 | 34 | // Encrypt the user password. 35 | if err := u.Encrypt(); err != nil { 36 | SendResponse(c, errno.ErrEncrypt, nil) 37 | return 38 | } 39 | // Insert the user to the database. 40 | if err := u.Create(); err != nil { 41 | SendResponse(c, errno.ErrDatabase, nil) 42 | return 43 | } 44 | 45 | rsp := CreateResponse{ 46 | Username: r.Username, 47 | } 48 | 49 | // Show the user information. 50 | SendResponse(c, nil, rsp) 51 | } 52 | -------------------------------------------------------------------------------- /demo13/admin.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | SERVER="apiserver" 4 | BASE_DIR=$PWD 5 | INTERVAL=2 6 | 7 | # 命令行参数,需要手动指定 8 | ARGS="" 9 | 10 | function start() 11 | { 12 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 13 | echo "$SERVER already running" 14 | exit 1 15 | fi 16 | 17 | nohup $BASE_DIR/$SERVER $ARGS server &>/dev/null & 18 | 19 | echo "sleeping..." && sleep $INTERVAL 20 | 21 | # check status 22 | if [ "`pgrep $SERVER -u $UID`" == "" ];then 23 | echo "$SERVER start failed" 24 | exit 1 25 | fi 26 | } 27 | 28 | function status() 29 | { 30 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 31 | echo $SERVER is running 32 | else 33 | echo $SERVER is not running 34 | fi 35 | } 36 | 37 | function stop() 38 | { 39 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 40 | kill -9 `pgrep $SERVER -u $UID` 41 | fi 42 | 43 | echo "sleeping..." && sleep $INTERVAL 44 | 45 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 46 | echo "$SERVER stop failed" 47 | exit 1 48 | fi 49 | } 50 | 51 | case "$1" in 52 | 'start') 53 | start 54 | ;; 55 | 'stop') 56 | stop 57 | ;; 58 | 'status') 59 | status 60 | ;; 61 | 'restart') 62 | stop && start 63 | ;; 64 | *) 65 | echo "usage: $0 {start|stop|restart|status}" 66 | exit 1 67 | ;; 68 | esac 69 | -------------------------------------------------------------------------------- /demo14/admin.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | SERVER="apiserver" 4 | BASE_DIR=$PWD 5 | INTERVAL=2 6 | 7 | # 命令行参数,需要手动指定 8 | ARGS="" 9 | 10 | function start() 11 | { 12 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 13 | echo "$SERVER already running" 14 | exit 1 15 | fi 16 | 17 | nohup $BASE_DIR/$SERVER $ARGS server &>/dev/null & 18 | 19 | echo "sleeping..." && sleep $INTERVAL 20 | 21 | # check status 22 | if [ "`pgrep $SERVER -u $UID`" == "" ];then 23 | echo "$SERVER start failed" 24 | exit 1 25 | fi 26 | } 27 | 28 | function status() 29 | { 30 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 31 | echo $SERVER is running 32 | else 33 | echo $SERVER is not running 34 | fi 35 | } 36 | 37 | function stop() 38 | { 39 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 40 | kill -9 `pgrep $SERVER -u $UID` 41 | fi 42 | 43 | echo "sleeping..." && sleep $INTERVAL 44 | 45 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 46 | echo "$SERVER stop failed" 47 | exit 1 48 | fi 49 | } 50 | 51 | case "$1" in 52 | 'start') 53 | start 54 | ;; 55 | 'stop') 56 | stop 57 | ;; 58 | 'status') 59 | status 60 | ;; 61 | 'restart') 62 | stop && start 63 | ;; 64 | *) 65 | echo "usage: $0 {start|stop|restart|status}" 66 | exit 1 67 | ;; 68 | esac 69 | -------------------------------------------------------------------------------- /demo15/admin.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | SERVER="apiserver" 4 | BASE_DIR=$PWD 5 | INTERVAL=2 6 | 7 | # 命令行参数,需要手动指定 8 | ARGS="" 9 | 10 | function start() 11 | { 12 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 13 | echo "$SERVER already running" 14 | exit 1 15 | fi 16 | 17 | nohup $BASE_DIR/$SERVER $ARGS server &>/dev/null & 18 | 19 | echo "sleeping..." && sleep $INTERVAL 20 | 21 | # check status 22 | if [ "`pgrep $SERVER -u $UID`" == "" ];then 23 | echo "$SERVER start failed" 24 | exit 1 25 | fi 26 | } 27 | 28 | function status() 29 | { 30 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 31 | echo $SERVER is running 32 | else 33 | echo $SERVER is not running 34 | fi 35 | } 36 | 37 | function stop() 38 | { 39 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 40 | kill -9 `pgrep $SERVER -u $UID` 41 | fi 42 | 43 | echo "sleeping..." && sleep $INTERVAL 44 | 45 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 46 | echo "$SERVER stop failed" 47 | exit 1 48 | fi 49 | } 50 | 51 | case "$1" in 52 | 'start') 53 | start 54 | ;; 55 | 'stop') 56 | stop 57 | ;; 58 | 'status') 59 | status 60 | ;; 61 | 'restart') 62 | stop && start 63 | ;; 64 | *) 65 | echo "usage: $0 {start|stop|restart|status}" 66 | exit 1 67 | ;; 68 | esac 69 | -------------------------------------------------------------------------------- /demo16/admin.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | SERVER="apiserver" 4 | BASE_DIR=$PWD 5 | INTERVAL=2 6 | 7 | # 命令行参数,需要手动指定 8 | ARGS="" 9 | 10 | function start() 11 | { 12 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 13 | echo "$SERVER already running" 14 | exit 1 15 | fi 16 | 17 | nohup $BASE_DIR/$SERVER $ARGS server &>/dev/null & 18 | 19 | echo "sleeping..." && sleep $INTERVAL 20 | 21 | # check status 22 | if [ "`pgrep $SERVER -u $UID`" == "" ];then 23 | echo "$SERVER start failed" 24 | exit 1 25 | fi 26 | } 27 | 28 | function status() 29 | { 30 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 31 | echo $SERVER is running 32 | else 33 | echo $SERVER is not running 34 | fi 35 | } 36 | 37 | function stop() 38 | { 39 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 40 | kill -9 `pgrep $SERVER -u $UID` 41 | fi 42 | 43 | echo "sleeping..." && sleep $INTERVAL 44 | 45 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 46 | echo "$SERVER stop failed" 47 | exit 1 48 | fi 49 | } 50 | 51 | case "$1" in 52 | 'start') 53 | start 54 | ;; 55 | 'stop') 56 | stop 57 | ;; 58 | 'status') 59 | status 60 | ;; 61 | 'restart') 62 | stop && start 63 | ;; 64 | *) 65 | echo "usage: $0 {start|stop|restart|status}" 66 | exit 1 67 | ;; 68 | esac 69 | -------------------------------------------------------------------------------- /demo17/admin.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | SERVER="apiserver" 4 | BASE_DIR=$PWD 5 | INTERVAL=2 6 | 7 | # 命令行参数,需要手动指定 8 | ARGS="" 9 | 10 | function start() 11 | { 12 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 13 | echo "$SERVER already running" 14 | exit 1 15 | fi 16 | 17 | nohup $BASE_DIR/$SERVER $ARGS server &>/dev/null & 18 | 19 | echo "sleeping..." && sleep $INTERVAL 20 | 21 | # check status 22 | if [ "`pgrep $SERVER -u $UID`" == "" ];then 23 | echo "$SERVER start failed" 24 | exit 1 25 | fi 26 | } 27 | 28 | function status() 29 | { 30 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 31 | echo $SERVER is running 32 | else 33 | echo $SERVER is not running 34 | fi 35 | } 36 | 37 | function stop() 38 | { 39 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 40 | kill -9 `pgrep $SERVER -u $UID` 41 | fi 42 | 43 | echo "sleeping..." && sleep $INTERVAL 44 | 45 | if [ "`pgrep $SERVER -u $UID`" != "" ];then 46 | echo "$SERVER stop failed" 47 | exit 1 48 | fi 49 | } 50 | 51 | case "$1" in 52 | 'start') 53 | start 54 | ;; 55 | 'stop') 56 | stop 57 | ;; 58 | 'status') 59 | status 60 | ;; 61 | 'restart') 62 | stop && start 63 | ;; 64 | *) 65 | echo "usage: $0 {start|stop|restart|status}" 66 | exit 1 67 | ;; 68 | esac 69 | -------------------------------------------------------------------------------- /demo09/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/handler/user" 8 | "apiserver/router/middleware" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Load loads the middlewares, routes, handlers. 14 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 15 | // Middlewares. 16 | g.Use(gin.Recovery()) 17 | g.Use(middleware.NoCache) 18 | g.Use(middleware.Options) 19 | g.Use(middleware.Secure) 20 | g.Use(mw...) 21 | // 404 Handler. 22 | g.NoRoute(func(c *gin.Context) { 23 | c.String(http.StatusNotFound, "The incorrect API route.") 24 | }) 25 | 26 | // api for authentication functionalities 27 | g.POST("/login", user.Login) 28 | 29 | // The user handlers, requiring authentication 30 | u := g.Group("/v1/user") 31 | u.Use(middleware.AuthMiddleware()) 32 | { 33 | u.POST("", user.Create) 34 | u.DELETE("/:id", user.Delete) 35 | u.PUT("/:id", user.Update) 36 | u.GET("", user.List) 37 | u.GET("/:username", user.Get) 38 | } 39 | 40 | // The health check handlers 41 | svcd := g.Group("/sd") 42 | { 43 | svcd.GET("/health", sd.HealthCheck) 44 | svcd.GET("/disk", sd.DiskCheck) 45 | svcd.GET("/cpu", sd.CPUCheck) 46 | svcd.GET("/ram", sd.RAMCheck) 47 | } 48 | 49 | return g 50 | } 51 | -------------------------------------------------------------------------------- /demo10/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/handler/user" 8 | "apiserver/router/middleware" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Load loads the middlewares, routes, handlers. 14 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 15 | // Middlewares. 16 | g.Use(gin.Recovery()) 17 | g.Use(middleware.NoCache) 18 | g.Use(middleware.Options) 19 | g.Use(middleware.Secure) 20 | g.Use(mw...) 21 | // 404 Handler. 22 | g.NoRoute(func(c *gin.Context) { 23 | c.String(http.StatusNotFound, "The incorrect API route.") 24 | }) 25 | 26 | // api for authentication functionalities 27 | g.POST("/login", user.Login) 28 | 29 | // The user handlers, requiring authentication 30 | u := g.Group("/v1/user") 31 | u.Use(middleware.AuthMiddleware()) 32 | { 33 | u.POST("", user.Create) 34 | u.DELETE("/:id", user.Delete) 35 | u.PUT("/:id", user.Update) 36 | u.GET("", user.List) 37 | u.GET("/:username", user.Get) 38 | } 39 | 40 | // The health check handlers 41 | svcd := g.Group("/sd") 42 | { 43 | svcd.GET("/health", sd.HealthCheck) 44 | svcd.GET("/disk", sd.DiskCheck) 45 | svcd.GET("/cpu", sd.CPUCheck) 46 | svcd.GET("/ram", sd.RAMCheck) 47 | } 48 | 49 | return g 50 | } 51 | -------------------------------------------------------------------------------- /demo11/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/handler/user" 8 | "apiserver/router/middleware" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Load loads the middlewares, routes, handlers. 14 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 15 | // Middlewares. 16 | g.Use(gin.Recovery()) 17 | g.Use(middleware.NoCache) 18 | g.Use(middleware.Options) 19 | g.Use(middleware.Secure) 20 | g.Use(mw...) 21 | // 404 Handler. 22 | g.NoRoute(func(c *gin.Context) { 23 | c.String(http.StatusNotFound, "The incorrect API route.") 24 | }) 25 | 26 | // api for authentication functionalities 27 | g.POST("/login", user.Login) 28 | 29 | // The user handlers, requiring authentication 30 | u := g.Group("/v1/user") 31 | u.Use(middleware.AuthMiddleware()) 32 | { 33 | u.POST("", user.Create) 34 | u.DELETE("/:id", user.Delete) 35 | u.PUT("/:id", user.Update) 36 | u.GET("", user.List) 37 | u.GET("/:username", user.Get) 38 | } 39 | 40 | // The health check handlers 41 | svcd := g.Group("/sd") 42 | { 43 | svcd.GET("/health", sd.HealthCheck) 44 | svcd.GET("/disk", sd.DiskCheck) 45 | svcd.GET("/cpu", sd.CPUCheck) 46 | svcd.GET("/ram", sd.RAMCheck) 47 | } 48 | 49 | return g 50 | } 51 | -------------------------------------------------------------------------------- /demo12/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/handler/user" 8 | "apiserver/router/middleware" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Load loads the middlewares, routes, handlers. 14 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 15 | // Middlewares. 16 | g.Use(gin.Recovery()) 17 | g.Use(middleware.NoCache) 18 | g.Use(middleware.Options) 19 | g.Use(middleware.Secure) 20 | g.Use(mw...) 21 | // 404 Handler. 22 | g.NoRoute(func(c *gin.Context) { 23 | c.String(http.StatusNotFound, "The incorrect API route.") 24 | }) 25 | 26 | // api for authentication functionalities 27 | g.POST("/login", user.Login) 28 | 29 | // The user handlers, requiring authentication 30 | u := g.Group("/v1/user") 31 | u.Use(middleware.AuthMiddleware()) 32 | { 33 | u.POST("", user.Create) 34 | u.DELETE("/:id", user.Delete) 35 | u.PUT("/:id", user.Update) 36 | u.GET("", user.List) 37 | u.GET("/:username", user.Get) 38 | } 39 | 40 | // The health check handlers 41 | svcd := g.Group("/sd") 42 | { 43 | svcd.GET("/health", sd.HealthCheck) 44 | svcd.GET("/disk", sd.DiskCheck) 45 | svcd.GET("/cpu", sd.CPUCheck) 46 | svcd.GET("/ram", sd.RAMCheck) 47 | } 48 | 49 | return g 50 | } 51 | -------------------------------------------------------------------------------- /demo13/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/handler/user" 8 | "apiserver/router/middleware" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Load loads the middlewares, routes, handlers. 14 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 15 | // Middlewares. 16 | g.Use(gin.Recovery()) 17 | g.Use(middleware.NoCache) 18 | g.Use(middleware.Options) 19 | g.Use(middleware.Secure) 20 | g.Use(mw...) 21 | // 404 Handler. 22 | g.NoRoute(func(c *gin.Context) { 23 | c.String(http.StatusNotFound, "The incorrect API route.") 24 | }) 25 | 26 | // api for authentication functionalities 27 | g.POST("/login", user.Login) 28 | 29 | // The user handlers, requiring authentication 30 | u := g.Group("/v1/user") 31 | u.Use(middleware.AuthMiddleware()) 32 | { 33 | u.POST("", user.Create) 34 | u.DELETE("/:id", user.Delete) 35 | u.PUT("/:id", user.Update) 36 | u.GET("", user.List) 37 | u.GET("/:username", user.Get) 38 | } 39 | 40 | // The health check handlers 41 | svcd := g.Group("/sd") 42 | { 43 | svcd.GET("/health", sd.HealthCheck) 44 | svcd.GET("/disk", sd.DiskCheck) 45 | svcd.GET("/cpu", sd.CPUCheck) 46 | svcd.GET("/ram", sd.RAMCheck) 47 | } 48 | 49 | return g 50 | } 51 | -------------------------------------------------------------------------------- /demo14/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/handler/user" 8 | "apiserver/router/middleware" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Load loads the middlewares, routes, handlers. 14 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 15 | // Middlewares. 16 | g.Use(gin.Recovery()) 17 | g.Use(middleware.NoCache) 18 | g.Use(middleware.Options) 19 | g.Use(middleware.Secure) 20 | g.Use(mw...) 21 | // 404 Handler. 22 | g.NoRoute(func(c *gin.Context) { 23 | c.String(http.StatusNotFound, "The incorrect API route.") 24 | }) 25 | 26 | // api for authentication functionalities 27 | g.POST("/login", user.Login) 28 | 29 | // The user handlers, requiring authentication 30 | u := g.Group("/v1/user") 31 | u.Use(middleware.AuthMiddleware()) 32 | { 33 | u.POST("", user.Create) 34 | u.DELETE("/:id", user.Delete) 35 | u.PUT("/:id", user.Update) 36 | u.GET("", user.List) 37 | u.GET("/:username", user.Get) 38 | } 39 | 40 | // The health check handlers 41 | svcd := g.Group("/sd") 42 | { 43 | svcd.GET("/health", sd.HealthCheck) 44 | svcd.GET("/disk", sd.DiskCheck) 45 | svcd.GET("/cpu", sd.CPUCheck) 46 | svcd.GET("/ram", sd.RAMCheck) 47 | } 48 | 49 | return g 50 | } 51 | -------------------------------------------------------------------------------- /demo15/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/handler/user" 8 | "apiserver/router/middleware" 9 | 10 | "github.com/gin-gonic/gin" 11 | ) 12 | 13 | // Load loads the middlewares, routes, handlers. 14 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 15 | // Middlewares. 16 | g.Use(gin.Recovery()) 17 | g.Use(middleware.NoCache) 18 | g.Use(middleware.Options) 19 | g.Use(middleware.Secure) 20 | g.Use(mw...) 21 | // 404 Handler. 22 | g.NoRoute(func(c *gin.Context) { 23 | c.String(http.StatusNotFound, "The incorrect API route.") 24 | }) 25 | 26 | // api for authentication functionalities 27 | g.POST("/login", user.Login) 28 | 29 | // The user handlers, requiring authentication 30 | u := g.Group("/v1/user") 31 | u.Use(middleware.AuthMiddleware()) 32 | { 33 | u.POST("", user.Create) 34 | u.DELETE("/:id", user.Delete) 35 | u.PUT("/:id", user.Update) 36 | u.GET("", user.List) 37 | u.GET("/:username", user.Get) 38 | } 39 | 40 | // The health check handlers 41 | svcd := g.Group("/sd") 42 | { 43 | svcd.GET("/health", sd.HealthCheck) 44 | svcd.GET("/disk", sd.DiskCheck) 45 | svcd.GET("/cpu", sd.CPUCheck) 46 | svcd.GET("/ram", sd.RAMCheck) 47 | } 48 | 49 | return g 50 | } 51 | -------------------------------------------------------------------------------- /demo07/handler/user/update.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | "apiserver/util" 10 | 11 | "github.com/gin-gonic/gin" 12 | "github.com/lexkong/log" 13 | "github.com/lexkong/log/lager" 14 | ) 15 | 16 | // Update update a exist user account info. 17 | func Update(c *gin.Context) { 18 | log.Info("Update function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 19 | // Get the user id from the url parameter. 20 | userId, _ := strconv.Atoi(c.Param("id")) 21 | 22 | // Binding the user data. 23 | var u model.UserModel 24 | if err := c.Bind(&u); err != nil { 25 | SendResponse(c, errno.ErrBind, nil) 26 | return 27 | } 28 | 29 | // We update the record based on the user id. 30 | u.Id = uint64(userId) 31 | 32 | // Validate the data. 33 | if err := u.Validate(); err != nil { 34 | SendResponse(c, errno.ErrValidation, nil) 35 | return 36 | } 37 | 38 | // Encrypt the user password. 39 | if err := u.Encrypt(); err != nil { 40 | SendResponse(c, errno.ErrEncrypt, nil) 41 | return 42 | } 43 | 44 | // Save changed fields. 45 | if err := u.Update(); err != nil { 46 | SendResponse(c, errno.ErrDatabase, nil) 47 | return 48 | } 49 | 50 | SendResponse(c, nil, nil) 51 | } 52 | -------------------------------------------------------------------------------- /demo08/handler/user/update.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | "apiserver/util" 10 | 11 | "github.com/gin-gonic/gin" 12 | "github.com/lexkong/log" 13 | "github.com/lexkong/log/lager" 14 | ) 15 | 16 | // Update update a exist user account info. 17 | func Update(c *gin.Context) { 18 | log.Info("Update function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 19 | // Get the user id from the url parameter. 20 | userId, _ := strconv.Atoi(c.Param("id")) 21 | 22 | // Binding the user data. 23 | var u model.UserModel 24 | if err := c.Bind(&u); err != nil { 25 | SendResponse(c, errno.ErrBind, nil) 26 | return 27 | } 28 | 29 | // We update the record based on the user id. 30 | u.Id = uint64(userId) 31 | 32 | // Validate the data. 33 | if err := u.Validate(); err != nil { 34 | SendResponse(c, errno.ErrValidation, nil) 35 | return 36 | } 37 | 38 | // Encrypt the user password. 39 | if err := u.Encrypt(); err != nil { 40 | SendResponse(c, errno.ErrEncrypt, nil) 41 | return 42 | } 43 | 44 | // Save changed fields. 45 | if err := u.Update(); err != nil { 46 | SendResponse(c, errno.ErrDatabase, nil) 47 | return 48 | } 49 | 50 | SendResponse(c, nil, nil) 51 | } 52 | -------------------------------------------------------------------------------- /demo09/handler/user/update.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | "apiserver/util" 10 | 11 | "github.com/gin-gonic/gin" 12 | "github.com/lexkong/log" 13 | "github.com/lexkong/log/lager" 14 | ) 15 | 16 | // Update update a exist user account info. 17 | func Update(c *gin.Context) { 18 | log.Info("Update function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 19 | // Get the user id from the url parameter. 20 | userId, _ := strconv.Atoi(c.Param("id")) 21 | 22 | // Binding the user data. 23 | var u model.UserModel 24 | if err := c.Bind(&u); err != nil { 25 | SendResponse(c, errno.ErrBind, nil) 26 | return 27 | } 28 | 29 | // We update the record based on the user id. 30 | u.Id = uint64(userId) 31 | 32 | // Validate the data. 33 | if err := u.Validate(); err != nil { 34 | SendResponse(c, errno.ErrValidation, nil) 35 | return 36 | } 37 | 38 | // Encrypt the user password. 39 | if err := u.Encrypt(); err != nil { 40 | SendResponse(c, errno.ErrEncrypt, nil) 41 | return 42 | } 43 | 44 | // Save changed fields. 45 | if err := u.Update(); err != nil { 46 | SendResponse(c, errno.ErrDatabase, nil) 47 | return 48 | } 49 | 50 | SendResponse(c, nil, nil) 51 | } 52 | -------------------------------------------------------------------------------- /demo10/handler/user/update.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | "apiserver/util" 10 | 11 | "github.com/gin-gonic/gin" 12 | "github.com/lexkong/log" 13 | "github.com/lexkong/log/lager" 14 | ) 15 | 16 | // Update update a exist user account info. 17 | func Update(c *gin.Context) { 18 | log.Info("Update function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 19 | // Get the user id from the url parameter. 20 | userId, _ := strconv.Atoi(c.Param("id")) 21 | 22 | // Binding the user data. 23 | var u model.UserModel 24 | if err := c.Bind(&u); err != nil { 25 | SendResponse(c, errno.ErrBind, nil) 26 | return 27 | } 28 | 29 | // We update the record based on the user id. 30 | u.Id = uint64(userId) 31 | 32 | // Validate the data. 33 | if err := u.Validate(); err != nil { 34 | SendResponse(c, errno.ErrValidation, nil) 35 | return 36 | } 37 | 38 | // Encrypt the user password. 39 | if err := u.Encrypt(); err != nil { 40 | SendResponse(c, errno.ErrEncrypt, nil) 41 | return 42 | } 43 | 44 | // Save changed fields. 45 | if err := u.Update(); err != nil { 46 | SendResponse(c, errno.ErrDatabase, nil) 47 | return 48 | } 49 | 50 | SendResponse(c, nil, nil) 51 | } 52 | -------------------------------------------------------------------------------- /demo11/handler/user/update.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | "apiserver/util" 10 | 11 | "github.com/gin-gonic/gin" 12 | "github.com/lexkong/log" 13 | "github.com/lexkong/log/lager" 14 | ) 15 | 16 | // Update update a exist user account info. 17 | func Update(c *gin.Context) { 18 | log.Info("Update function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 19 | // Get the user id from the url parameter. 20 | userId, _ := strconv.Atoi(c.Param("id")) 21 | 22 | // Binding the user data. 23 | var u model.UserModel 24 | if err := c.Bind(&u); err != nil { 25 | SendResponse(c, errno.ErrBind, nil) 26 | return 27 | } 28 | 29 | // We update the record based on the user id. 30 | u.Id = uint64(userId) 31 | 32 | // Validate the data. 33 | if err := u.Validate(); err != nil { 34 | SendResponse(c, errno.ErrValidation, nil) 35 | return 36 | } 37 | 38 | // Encrypt the user password. 39 | if err := u.Encrypt(); err != nil { 40 | SendResponse(c, errno.ErrEncrypt, nil) 41 | return 42 | } 43 | 44 | // Save changed fields. 45 | if err := u.Update(); err != nil { 46 | SendResponse(c, errno.ErrDatabase, nil) 47 | return 48 | } 49 | 50 | SendResponse(c, nil, nil) 51 | } 52 | -------------------------------------------------------------------------------- /demo12/handler/user/update.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | "apiserver/util" 10 | 11 | "github.com/gin-gonic/gin" 12 | "github.com/lexkong/log" 13 | "github.com/lexkong/log/lager" 14 | ) 15 | 16 | // Update update a exist user account info. 17 | func Update(c *gin.Context) { 18 | log.Info("Update function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 19 | // Get the user id from the url parameter. 20 | userId, _ := strconv.Atoi(c.Param("id")) 21 | 22 | // Binding the user data. 23 | var u model.UserModel 24 | if err := c.Bind(&u); err != nil { 25 | SendResponse(c, errno.ErrBind, nil) 26 | return 27 | } 28 | 29 | // We update the record based on the user id. 30 | u.Id = uint64(userId) 31 | 32 | // Validate the data. 33 | if err := u.Validate(); err != nil { 34 | SendResponse(c, errno.ErrValidation, nil) 35 | return 36 | } 37 | 38 | // Encrypt the user password. 39 | if err := u.Encrypt(); err != nil { 40 | SendResponse(c, errno.ErrEncrypt, nil) 41 | return 42 | } 43 | 44 | // Save changed fields. 45 | if err := u.Update(); err != nil { 46 | SendResponse(c, errno.ErrDatabase, nil) 47 | return 48 | } 49 | 50 | SendResponse(c, nil, nil) 51 | } 52 | -------------------------------------------------------------------------------- /demo13/handler/user/update.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | "apiserver/util" 10 | 11 | "github.com/gin-gonic/gin" 12 | "github.com/lexkong/log" 13 | "github.com/lexkong/log/lager" 14 | ) 15 | 16 | // Update update a exist user account info. 17 | func Update(c *gin.Context) { 18 | log.Info("Update function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 19 | // Get the user id from the url parameter. 20 | userId, _ := strconv.Atoi(c.Param("id")) 21 | 22 | // Binding the user data. 23 | var u model.UserModel 24 | if err := c.Bind(&u); err != nil { 25 | SendResponse(c, errno.ErrBind, nil) 26 | return 27 | } 28 | 29 | // We update the record based on the user id. 30 | u.Id = uint64(userId) 31 | 32 | // Validate the data. 33 | if err := u.Validate(); err != nil { 34 | SendResponse(c, errno.ErrValidation, nil) 35 | return 36 | } 37 | 38 | // Encrypt the user password. 39 | if err := u.Encrypt(); err != nil { 40 | SendResponse(c, errno.ErrEncrypt, nil) 41 | return 42 | } 43 | 44 | // Save changed fields. 45 | if err := u.Update(); err != nil { 46 | SendResponse(c, errno.ErrDatabase, nil) 47 | return 48 | } 49 | 50 | SendResponse(c, nil, nil) 51 | } 52 | -------------------------------------------------------------------------------- /demo14/handler/user/update.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | "apiserver/util" 10 | 11 | "github.com/gin-gonic/gin" 12 | "github.com/lexkong/log" 13 | "github.com/lexkong/log/lager" 14 | ) 15 | 16 | // Update update a exist user account info. 17 | func Update(c *gin.Context) { 18 | log.Info("Update function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 19 | // Get the user id from the url parameter. 20 | userId, _ := strconv.Atoi(c.Param("id")) 21 | 22 | // Binding the user data. 23 | var u model.UserModel 24 | if err := c.Bind(&u); err != nil { 25 | SendResponse(c, errno.ErrBind, nil) 26 | return 27 | } 28 | 29 | // We update the record based on the user id. 30 | u.Id = uint64(userId) 31 | 32 | // Validate the data. 33 | if err := u.Validate(); err != nil { 34 | SendResponse(c, errno.ErrValidation, nil) 35 | return 36 | } 37 | 38 | // Encrypt the user password. 39 | if err := u.Encrypt(); err != nil { 40 | SendResponse(c, errno.ErrEncrypt, nil) 41 | return 42 | } 43 | 44 | // Save changed fields. 45 | if err := u.Update(); err != nil { 46 | SendResponse(c, errno.ErrDatabase, nil) 47 | return 48 | } 49 | 50 | SendResponse(c, nil, nil) 51 | } 52 | -------------------------------------------------------------------------------- /demo15/handler/user/update.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | "apiserver/util" 10 | 11 | "github.com/gin-gonic/gin" 12 | "github.com/lexkong/log" 13 | "github.com/lexkong/log/lager" 14 | ) 15 | 16 | // Update update a exist user account info. 17 | func Update(c *gin.Context) { 18 | log.Info("Update function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 19 | // Get the user id from the url parameter. 20 | userId, _ := strconv.Atoi(c.Param("id")) 21 | 22 | // Binding the user data. 23 | var u model.UserModel 24 | if err := c.Bind(&u); err != nil { 25 | SendResponse(c, errno.ErrBind, nil) 26 | return 27 | } 28 | 29 | // We update the record based on the user id. 30 | u.Id = uint64(userId) 31 | 32 | // Validate the data. 33 | if err := u.Validate(); err != nil { 34 | SendResponse(c, errno.ErrValidation, nil) 35 | return 36 | } 37 | 38 | // Encrypt the user password. 39 | if err := u.Encrypt(); err != nil { 40 | SendResponse(c, errno.ErrEncrypt, nil) 41 | return 42 | } 43 | 44 | // Save changed fields. 45 | if err := u.Update(); err != nil { 46 | SendResponse(c, errno.ErrDatabase, nil) 47 | return 48 | } 49 | 50 | SendResponse(c, nil, nil) 51 | } 52 | -------------------------------------------------------------------------------- /demo16/handler/user/update.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | 6 | . "apiserver/handler" 7 | "apiserver/model" 8 | "apiserver/pkg/errno" 9 | "apiserver/util" 10 | 11 | "github.com/gin-gonic/gin" 12 | "github.com/lexkong/log" 13 | "github.com/lexkong/log/lager" 14 | ) 15 | 16 | // Update update a exist user account info. 17 | func Update(c *gin.Context) { 18 | log.Info("Update function called.", lager.Data{"X-Request-Id": util.GetReqID(c)}) 19 | // Get the user id from the url parameter. 20 | userId, _ := strconv.Atoi(c.Param("id")) 21 | 22 | // Binding the user data. 23 | var u model.UserModel 24 | if err := c.Bind(&u); err != nil { 25 | SendResponse(c, errno.ErrBind, nil) 26 | return 27 | } 28 | 29 | // We update the record based on the user id. 30 | u.Id = uint64(userId) 31 | 32 | // Validate the data. 33 | if err := u.Validate(); err != nil { 34 | SendResponse(c, errno.ErrValidation, nil) 35 | return 36 | } 37 | 38 | // Encrypt the user password. 39 | if err := u.Encrypt(); err != nil { 40 | SendResponse(c, errno.ErrEncrypt, nil) 41 | return 42 | } 43 | 44 | // Save changed fields. 45 | if err := u.Update(); err != nil { 46 | SendResponse(c, errno.ErrDatabase, nil) 47 | return 48 | } 49 | 50 | SendResponse(c, nil, nil) 51 | } 52 | -------------------------------------------------------------------------------- /demo02/config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "log" 5 | "strings" 6 | 7 | "github.com/fsnotify/fsnotify" 8 | "github.com/spf13/viper" 9 | ) 10 | 11 | type Config struct { 12 | Name string 13 | } 14 | 15 | func Init(cfg string) error { 16 | c := Config{ 17 | Name: cfg, 18 | } 19 | 20 | // 初始化配置文件 21 | if err := c.initConfig(); err != nil { 22 | return err 23 | } 24 | 25 | // 监控配置文件变化并热加载程序 26 | c.watchConfig() 27 | 28 | return nil 29 | } 30 | 31 | func (c *Config) initConfig() error { 32 | if c.Name != "" { 33 | viper.SetConfigFile(c.Name) // 如果指定了配置文件,则解析指定的配置文件 34 | } else { 35 | viper.AddConfigPath("conf") // 如果没有指定配置文件,则解析默认的配置文件 36 | viper.SetConfigName("config") 37 | } 38 | viper.SetConfigType("yaml") // 设置配置文件格式为YAML 39 | viper.AutomaticEnv() // 读取匹配的环境变量 40 | viper.SetEnvPrefix("APISERVER") // 读取环境变量的前缀为APISERVER 41 | replacer := strings.NewReplacer(".", "_") 42 | viper.SetEnvKeyReplacer(replacer) 43 | if err := viper.ReadInConfig(); err != nil { // viper解析配置文件 44 | return err 45 | } 46 | 47 | return nil 48 | } 49 | 50 | // 监控配置文件变化并热加载程序 51 | func (c *Config) watchConfig() { 52 | viper.WatchConfig() 53 | viper.OnConfigChange(func(e fsnotify.Event) { 54 | log.Printf("Config file changed: %s", e.Name) 55 | }) 56 | } 57 | -------------------------------------------------------------------------------- /demo07/pkg/errno/errno.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | import "fmt" 4 | 5 | type Errno struct { 6 | Code int 7 | Message string 8 | } 9 | 10 | func (err Errno) Error() string { 11 | return err.Message 12 | } 13 | 14 | // Err represents an error 15 | type Err struct { 16 | Code int 17 | Message string 18 | Err error 19 | } 20 | 21 | func New(errno *Errno, err error) *Err { 22 | return &Err{Code: errno.Code, Message: errno.Message, Err: err} 23 | } 24 | 25 | func (err *Err) Add(message string) error { 26 | err.Message += " " + message 27 | return err 28 | } 29 | 30 | func (err *Err) Addf(format string, args ...interface{}) error { 31 | err.Message += " " + fmt.Sprintf(format, args...) 32 | return err 33 | } 34 | 35 | func (err *Err) Error() string { 36 | return fmt.Sprintf("Err - code: %d, message: %s, error: %s", err.Code, err.Message, err.Err) 37 | } 38 | 39 | func IsErrUserNotFound(err error) bool { 40 | code, _ := DecodeErr(err) 41 | return code == ErrUserNotFound.Code 42 | } 43 | 44 | func DecodeErr(err error) (int, string) { 45 | if err == nil { 46 | return OK.Code, OK.Message 47 | } 48 | 49 | switch typed := err.(type) { 50 | case *Err: 51 | return typed.Code, typed.Message 52 | case *Errno: 53 | return typed.Code, typed.Message 54 | default: 55 | } 56 | 57 | return InternalServerError.Code, err.Error() 58 | } 59 | -------------------------------------------------------------------------------- /demo08/pkg/errno/errno.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | import "fmt" 4 | 5 | type Errno struct { 6 | Code int 7 | Message string 8 | } 9 | 10 | func (err Errno) Error() string { 11 | return err.Message 12 | } 13 | 14 | // Err represents an error 15 | type Err struct { 16 | Code int 17 | Message string 18 | Err error 19 | } 20 | 21 | func New(errno *Errno, err error) *Err { 22 | return &Err{Code: errno.Code, Message: errno.Message, Err: err} 23 | } 24 | 25 | func (err *Err) Add(message string) error { 26 | err.Message += " " + message 27 | return err 28 | } 29 | 30 | func (err *Err) Addf(format string, args ...interface{}) error { 31 | err.Message += " " + fmt.Sprintf(format, args...) 32 | return err 33 | } 34 | 35 | func (err *Err) Error() string { 36 | return fmt.Sprintf("Err - code: %d, message: %s, error: %s", err.Code, err.Message, err.Err) 37 | } 38 | 39 | func IsErrUserNotFound(err error) bool { 40 | code, _ := DecodeErr(err) 41 | return code == ErrUserNotFound.Code 42 | } 43 | 44 | func DecodeErr(err error) (int, string) { 45 | if err == nil { 46 | return OK.Code, OK.Message 47 | } 48 | 49 | switch typed := err.(type) { 50 | case *Err: 51 | return typed.Code, typed.Message 52 | case *Errno: 53 | return typed.Code, typed.Message 54 | default: 55 | } 56 | 57 | return InternalServerError.Code, err.Error() 58 | } 59 | -------------------------------------------------------------------------------- /demo09/pkg/errno/errno.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | import "fmt" 4 | 5 | type Errno struct { 6 | Code int 7 | Message string 8 | } 9 | 10 | func (err Errno) Error() string { 11 | return err.Message 12 | } 13 | 14 | // Err represents an error 15 | type Err struct { 16 | Code int 17 | Message string 18 | Err error 19 | } 20 | 21 | func New(errno *Errno, err error) *Err { 22 | return &Err{Code: errno.Code, Message: errno.Message, Err: err} 23 | } 24 | 25 | func (err *Err) Add(message string) error { 26 | err.Message += " " + message 27 | return err 28 | } 29 | 30 | func (err *Err) Addf(format string, args ...interface{}) error { 31 | err.Message += " " + fmt.Sprintf(format, args...) 32 | return err 33 | } 34 | 35 | func (err *Err) Error() string { 36 | return fmt.Sprintf("Err - code: %d, message: %s, error: %s", err.Code, err.Message, err.Err) 37 | } 38 | 39 | func IsErrUserNotFound(err error) bool { 40 | code, _ := DecodeErr(err) 41 | return code == ErrUserNotFound.Code 42 | } 43 | 44 | func DecodeErr(err error) (int, string) { 45 | if err == nil { 46 | return OK.Code, OK.Message 47 | } 48 | 49 | switch typed := err.(type) { 50 | case *Err: 51 | return typed.Code, typed.Message 52 | case *Errno: 53 | return typed.Code, typed.Message 54 | default: 55 | } 56 | 57 | return InternalServerError.Code, err.Error() 58 | } 59 | -------------------------------------------------------------------------------- /demo10/pkg/errno/errno.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | import "fmt" 4 | 5 | type Errno struct { 6 | Code int 7 | Message string 8 | } 9 | 10 | func (err Errno) Error() string { 11 | return err.Message 12 | } 13 | 14 | // Err represents an error 15 | type Err struct { 16 | Code int 17 | Message string 18 | Err error 19 | } 20 | 21 | func New(errno *Errno, err error) *Err { 22 | return &Err{Code: errno.Code, Message: errno.Message, Err: err} 23 | } 24 | 25 | func (err *Err) Add(message string) error { 26 | err.Message += " " + message 27 | return err 28 | } 29 | 30 | func (err *Err) Addf(format string, args ...interface{}) error { 31 | err.Message += " " + fmt.Sprintf(format, args...) 32 | return err 33 | } 34 | 35 | func (err *Err) Error() string { 36 | return fmt.Sprintf("Err - code: %d, message: %s, error: %s", err.Code, err.Message, err.Err) 37 | } 38 | 39 | func IsErrUserNotFound(err error) bool { 40 | code, _ := DecodeErr(err) 41 | return code == ErrUserNotFound.Code 42 | } 43 | 44 | func DecodeErr(err error) (int, string) { 45 | if err == nil { 46 | return OK.Code, OK.Message 47 | } 48 | 49 | switch typed := err.(type) { 50 | case *Err: 51 | return typed.Code, typed.Message 52 | case *Errno: 53 | return typed.Code, typed.Message 54 | default: 55 | } 56 | 57 | return InternalServerError.Code, err.Error() 58 | } 59 | -------------------------------------------------------------------------------- /demo11/pkg/errno/errno.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | import "fmt" 4 | 5 | type Errno struct { 6 | Code int 7 | Message string 8 | } 9 | 10 | func (err Errno) Error() string { 11 | return err.Message 12 | } 13 | 14 | // Err represents an error 15 | type Err struct { 16 | Code int 17 | Message string 18 | Err error 19 | } 20 | 21 | func New(errno *Errno, err error) *Err { 22 | return &Err{Code: errno.Code, Message: errno.Message, Err: err} 23 | } 24 | 25 | func (err *Err) Add(message string) error { 26 | err.Message += " " + message 27 | return err 28 | } 29 | 30 | func (err *Err) Addf(format string, args ...interface{}) error { 31 | err.Message += " " + fmt.Sprintf(format, args...) 32 | return err 33 | } 34 | 35 | func (err *Err) Error() string { 36 | return fmt.Sprintf("Err - code: %d, message: %s, error: %s", err.Code, err.Message, err.Err) 37 | } 38 | 39 | func IsErrUserNotFound(err error) bool { 40 | code, _ := DecodeErr(err) 41 | return code == ErrUserNotFound.Code 42 | } 43 | 44 | func DecodeErr(err error) (int, string) { 45 | if err == nil { 46 | return OK.Code, OK.Message 47 | } 48 | 49 | switch typed := err.(type) { 50 | case *Err: 51 | return typed.Code, typed.Message 52 | case *Errno: 53 | return typed.Code, typed.Message 54 | default: 55 | } 56 | 57 | return InternalServerError.Code, err.Error() 58 | } 59 | -------------------------------------------------------------------------------- /demo12/pkg/errno/errno.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | import "fmt" 4 | 5 | type Errno struct { 6 | Code int 7 | Message string 8 | } 9 | 10 | func (err Errno) Error() string { 11 | return err.Message 12 | } 13 | 14 | // Err represents an error 15 | type Err struct { 16 | Code int 17 | Message string 18 | Err error 19 | } 20 | 21 | func New(errno *Errno, err error) *Err { 22 | return &Err{Code: errno.Code, Message: errno.Message, Err: err} 23 | } 24 | 25 | func (err *Err) Add(message string) error { 26 | err.Message += " " + message 27 | return err 28 | } 29 | 30 | func (err *Err) Addf(format string, args ...interface{}) error { 31 | err.Message += " " + fmt.Sprintf(format, args...) 32 | return err 33 | } 34 | 35 | func (err *Err) Error() string { 36 | return fmt.Sprintf("Err - code: %d, message: %s, error: %s", err.Code, err.Message, err.Err) 37 | } 38 | 39 | func IsErrUserNotFound(err error) bool { 40 | code, _ := DecodeErr(err) 41 | return code == ErrUserNotFound.Code 42 | } 43 | 44 | func DecodeErr(err error) (int, string) { 45 | if err == nil { 46 | return OK.Code, OK.Message 47 | } 48 | 49 | switch typed := err.(type) { 50 | case *Err: 51 | return typed.Code, typed.Message 52 | case *Errno: 53 | return typed.Code, typed.Message 54 | default: 55 | } 56 | 57 | return InternalServerError.Code, err.Error() 58 | } 59 | -------------------------------------------------------------------------------- /demo13/pkg/errno/errno.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | import "fmt" 4 | 5 | type Errno struct { 6 | Code int 7 | Message string 8 | } 9 | 10 | func (err Errno) Error() string { 11 | return err.Message 12 | } 13 | 14 | // Err represents an error 15 | type Err struct { 16 | Code int 17 | Message string 18 | Err error 19 | } 20 | 21 | func New(errno *Errno, err error) *Err { 22 | return &Err{Code: errno.Code, Message: errno.Message, Err: err} 23 | } 24 | 25 | func (err *Err) Add(message string) error { 26 | err.Message += " " + message 27 | return err 28 | } 29 | 30 | func (err *Err) Addf(format string, args ...interface{}) error { 31 | err.Message += " " + fmt.Sprintf(format, args...) 32 | return err 33 | } 34 | 35 | func (err *Err) Error() string { 36 | return fmt.Sprintf("Err - code: %d, message: %s, error: %s", err.Code, err.Message, err.Err) 37 | } 38 | 39 | func IsErrUserNotFound(err error) bool { 40 | code, _ := DecodeErr(err) 41 | return code == ErrUserNotFound.Code 42 | } 43 | 44 | func DecodeErr(err error) (int, string) { 45 | if err == nil { 46 | return OK.Code, OK.Message 47 | } 48 | 49 | switch typed := err.(type) { 50 | case *Err: 51 | return typed.Code, typed.Message 52 | case *Errno: 53 | return typed.Code, typed.Message 54 | default: 55 | } 56 | 57 | return InternalServerError.Code, err.Error() 58 | } 59 | -------------------------------------------------------------------------------- /demo14/pkg/errno/errno.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | import "fmt" 4 | 5 | type Errno struct { 6 | Code int 7 | Message string 8 | } 9 | 10 | func (err Errno) Error() string { 11 | return err.Message 12 | } 13 | 14 | // Err represents an error 15 | type Err struct { 16 | Code int 17 | Message string 18 | Err error 19 | } 20 | 21 | func New(errno *Errno, err error) *Err { 22 | return &Err{Code: errno.Code, Message: errno.Message, Err: err} 23 | } 24 | 25 | func (err *Err) Add(message string) error { 26 | err.Message += " " + message 27 | return err 28 | } 29 | 30 | func (err *Err) Addf(format string, args ...interface{}) error { 31 | err.Message += " " + fmt.Sprintf(format, args...) 32 | return err 33 | } 34 | 35 | func (err *Err) Error() string { 36 | return fmt.Sprintf("Err - code: %d, message: %s, error: %s", err.Code, err.Message, err.Err) 37 | } 38 | 39 | func IsErrUserNotFound(err error) bool { 40 | code, _ := DecodeErr(err) 41 | return code == ErrUserNotFound.Code 42 | } 43 | 44 | func DecodeErr(err error) (int, string) { 45 | if err == nil { 46 | return OK.Code, OK.Message 47 | } 48 | 49 | switch typed := err.(type) { 50 | case *Err: 51 | return typed.Code, typed.Message 52 | case *Errno: 53 | return typed.Code, typed.Message 54 | default: 55 | } 56 | 57 | return InternalServerError.Code, err.Error() 58 | } 59 | -------------------------------------------------------------------------------- /demo15/pkg/errno/errno.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | import "fmt" 4 | 5 | type Errno struct { 6 | Code int 7 | Message string 8 | } 9 | 10 | func (err Errno) Error() string { 11 | return err.Message 12 | } 13 | 14 | // Err represents an error 15 | type Err struct { 16 | Code int 17 | Message string 18 | Err error 19 | } 20 | 21 | func New(errno *Errno, err error) *Err { 22 | return &Err{Code: errno.Code, Message: errno.Message, Err: err} 23 | } 24 | 25 | func (err *Err) Add(message string) error { 26 | err.Message += " " + message 27 | return err 28 | } 29 | 30 | func (err *Err) Addf(format string, args ...interface{}) error { 31 | err.Message += " " + fmt.Sprintf(format, args...) 32 | return err 33 | } 34 | 35 | func (err *Err) Error() string { 36 | return fmt.Sprintf("Err - code: %d, message: %s, error: %s", err.Code, err.Message, err.Err) 37 | } 38 | 39 | func IsErrUserNotFound(err error) bool { 40 | code, _ := DecodeErr(err) 41 | return code == ErrUserNotFound.Code 42 | } 43 | 44 | func DecodeErr(err error) (int, string) { 45 | if err == nil { 46 | return OK.Code, OK.Message 47 | } 48 | 49 | switch typed := err.(type) { 50 | case *Err: 51 | return typed.Code, typed.Message 52 | case *Errno: 53 | return typed.Code, typed.Message 54 | default: 55 | } 56 | 57 | return InternalServerError.Code, err.Error() 58 | } 59 | -------------------------------------------------------------------------------- /demo16/pkg/errno/errno.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | import "fmt" 4 | 5 | type Errno struct { 6 | Code int 7 | Message string 8 | } 9 | 10 | func (err Errno) Error() string { 11 | return err.Message 12 | } 13 | 14 | // Err represents an error 15 | type Err struct { 16 | Code int 17 | Message string 18 | Err error 19 | } 20 | 21 | func New(errno *Errno, err error) *Err { 22 | return &Err{Code: errno.Code, Message: errno.Message, Err: err} 23 | } 24 | 25 | func (err *Err) Add(message string) error { 26 | err.Message += " " + message 27 | return err 28 | } 29 | 30 | func (err *Err) Addf(format string, args ...interface{}) error { 31 | err.Message += " " + fmt.Sprintf(format, args...) 32 | return err 33 | } 34 | 35 | func (err *Err) Error() string { 36 | return fmt.Sprintf("Err - code: %d, message: %s, error: %s", err.Code, err.Message, err.Err) 37 | } 38 | 39 | func IsErrUserNotFound(err error) bool { 40 | code, _ := DecodeErr(err) 41 | return code == ErrUserNotFound.Code 42 | } 43 | 44 | func DecodeErr(err error) (int, string) { 45 | if err == nil { 46 | return OK.Code, OK.Message 47 | } 48 | 49 | switch typed := err.(type) { 50 | case *Err: 51 | return typed.Code, typed.Message 52 | case *Errno: 53 | return typed.Code, typed.Message 54 | default: 55 | } 56 | 57 | return InternalServerError.Code, err.Error() 58 | } 59 | -------------------------------------------------------------------------------- /demo17/pkg/errno/errno.go: -------------------------------------------------------------------------------- 1 | package errno 2 | 3 | import "fmt" 4 | 5 | type Errno struct { 6 | Code int 7 | Message string 8 | } 9 | 10 | func (err Errno) Error() string { 11 | return err.Message 12 | } 13 | 14 | // Err represents an error 15 | type Err struct { 16 | Code int 17 | Message string 18 | Err error 19 | } 20 | 21 | func New(errno *Errno, err error) *Err { 22 | return &Err{Code: errno.Code, Message: errno.Message, Err: err} 23 | } 24 | 25 | func (err *Err) Add(message string) error { 26 | err.Message += " " + message 27 | return err 28 | } 29 | 30 | func (err *Err) Addf(format string, args ...interface{}) error { 31 | err.Message += " " + fmt.Sprintf(format, args...) 32 | return err 33 | } 34 | 35 | func (err *Err) Error() string { 36 | return fmt.Sprintf("Err - code: %d, message: %s, error: %s", err.Code, err.Message, err.Err) 37 | } 38 | 39 | func IsErrUserNotFound(err error) bool { 40 | code, _ := DecodeErr(err) 41 | return code == ErrUserNotFound.Code 42 | } 43 | 44 | func DecodeErr(err error) (int, string) { 45 | if err == nil { 46 | return OK.Code, OK.Message 47 | } 48 | 49 | switch typed := err.(type) { 50 | case *Err: 51 | return typed.Code, typed.Message 52 | case *Errno: 53 | return typed.Code, typed.Message 54 | default: 55 | } 56 | 57 | return InternalServerError.Code, err.Error() 58 | } 59 | -------------------------------------------------------------------------------- /demo12/Makefile: -------------------------------------------------------------------------------- 1 | SHELL := /bin/bash 2 | BASEDIR = $(shell pwd) 3 | 4 | # build with verison infos 5 | versionDir = "apiserver/pkg/version" 6 | gitTag = $(shell if [ "`git describe --tags --abbrev=0 2>/dev/null`" != "" ];then git describe --tags --abbrev=0; else git log --pretty=format:'%h' -n 1; fi) 7 | buildDate = $(shell TZ=Asia/Shanghai date +%FT%T%z) 8 | gitCommit = $(shell git log --pretty=format:'%H' -n 1) 9 | gitTreeState = $(shell if git status|grep -q 'clean';then echo clean; else echo dirty; fi) 10 | 11 | ldflags="-w -X ${versionDir}.gitTag=${gitTag} -X ${versionDir}.buildDate=${buildDate} -X ${versionDir}.gitCommit=${gitCommit} -X ${versionDir}.gitTreeState=${gitTreeState}" 12 | 13 | all: gotool 14 | @go build -v -ldflags ${ldflags} . 15 | clean: 16 | rm -f apiserver 17 | find . -name "[._]*.s[a-w][a-z]" | xargs -i rm -f {} 18 | gotool: 19 | gofmt -w . 20 | go tool vet . |& grep -v vendor;true 21 | ca: 22 | openssl req -new -nodes -x509 -out conf/server.crt -keyout conf/server.key -days 3650 -subj "/C=DE/ST=NRW/L=Earth/O=Random Company/OU=IT/CN=127.0.0.1/emailAddress=xxxxx@qq.com" 23 | 24 | help: 25 | @echo "make - compile the source code" 26 | @echo "make clean - remove binary file and vim swp files" 27 | @echo "make gotool - run go tool 'fmt' and 'vet'" 28 | @echo "make ca - generate ca files" 29 | 30 | .PHONY: clean gotool ca help 31 | 32 | 33 | -------------------------------------------------------------------------------- /demo13/Makefile: -------------------------------------------------------------------------------- 1 | SHELL := /bin/bash 2 | BASEDIR = $(shell pwd) 3 | 4 | # build with verison infos 5 | versionDir = "apiserver/pkg/version" 6 | gitTag = $(shell if [ "`git describe --tags --abbrev=0 2>/dev/null`" != "" ];then git describe --tags --abbrev=0; else git log --pretty=format:'%h' -n 1; fi) 7 | buildDate = $(shell TZ=Asia/Shanghai date +%FT%T%z) 8 | gitCommit = $(shell git log --pretty=format:'%H' -n 1) 9 | gitTreeState = $(shell if git status|grep -q 'clean';then echo clean; else echo dirty; fi) 10 | 11 | ldflags="-w -X ${versionDir}.gitTag=${gitTag} -X ${versionDir}.buildDate=${buildDate} -X ${versionDir}.gitCommit=${gitCommit} -X ${versionDir}.gitTreeState=${gitTreeState}" 12 | 13 | all: gotool 14 | @go build -v -ldflags ${ldflags} . 15 | clean: 16 | rm -f apiserver 17 | find . -name "[._]*.s[a-w][a-z]" | xargs -i rm -f {} 18 | gotool: 19 | gofmt -w . 20 | go tool vet . |& grep -v vendor;true 21 | ca: 22 | openssl req -new -nodes -x509 -out conf/server.crt -keyout conf/server.key -days 3650 -subj "/C=DE/ST=NRW/L=Earth/O=Random Company/OU=IT/CN=127.0.0.1/emailAddress=xxxxx@qq.com" 23 | 24 | help: 25 | @echo "make - compile the source code" 26 | @echo "make clean - remove binary file and vim swp files" 27 | @echo "make gotool - run go tool 'fmt' and 'vet'" 28 | @echo "make ca - generate ca files" 29 | 30 | .PHONY: clean gotool ca help 31 | 32 | 33 | -------------------------------------------------------------------------------- /demo14/Makefile: -------------------------------------------------------------------------------- 1 | SHELL := /bin/bash 2 | BASEDIR = $(shell pwd) 3 | 4 | # build with verison infos 5 | versionDir = "apiserver/pkg/version" 6 | gitTag = $(shell if [ "`git describe --tags --abbrev=0 2>/dev/null`" != "" ];then git describe --tags --abbrev=0; else git log --pretty=format:'%h' -n 1; fi) 7 | buildDate = $(shell TZ=Asia/Shanghai date +%FT%T%z) 8 | gitCommit = $(shell git log --pretty=format:'%H' -n 1) 9 | gitTreeState = $(shell if git status|grep -q 'clean';then echo clean; else echo dirty; fi) 10 | 11 | ldflags="-w -X ${versionDir}.gitTag=${gitTag} -X ${versionDir}.buildDate=${buildDate} -X ${versionDir}.gitCommit=${gitCommit} -X ${versionDir}.gitTreeState=${gitTreeState}" 12 | 13 | all: gotool 14 | @go build -v -ldflags ${ldflags} . 15 | clean: 16 | rm -f apiserver 17 | find . -name "[._]*.s[a-w][a-z]" | xargs -i rm -f {} 18 | gotool: 19 | gofmt -w . 20 | go tool vet . |& grep -v vendor;true 21 | ca: 22 | openssl req -new -nodes -x509 -out conf/server.crt -keyout conf/server.key -days 3650 -subj "/C=DE/ST=NRW/L=Earth/O=Random Company/OU=IT/CN=127.0.0.1/emailAddress=xxxxx@qq.com" 23 | 24 | help: 25 | @echo "make - compile the source code" 26 | @echo "make clean - remove binary file and vim swp files" 27 | @echo "make gotool - run go tool 'fmt' and 'vet'" 28 | @echo "make ca - generate ca files" 29 | 30 | .PHONY: clean gotool ca help 31 | 32 | 33 | -------------------------------------------------------------------------------- /demo15/Makefile: -------------------------------------------------------------------------------- 1 | SHELL := /bin/bash 2 | BASEDIR = $(shell pwd) 3 | 4 | # build with verison infos 5 | versionDir = "apiserver/pkg/version" 6 | gitTag = $(shell if [ "`git describe --tags --abbrev=0 2>/dev/null`" != "" ];then git describe --tags --abbrev=0; else git log --pretty=format:'%h' -n 1; fi) 7 | buildDate = $(shell TZ=Asia/Shanghai date +%FT%T%z) 8 | gitCommit = $(shell git log --pretty=format:'%H' -n 1) 9 | gitTreeState = $(shell if git status|grep -q 'clean';then echo clean; else echo dirty; fi) 10 | 11 | ldflags="-w -X ${versionDir}.gitTag=${gitTag} -X ${versionDir}.buildDate=${buildDate} -X ${versionDir}.gitCommit=${gitCommit} -X ${versionDir}.gitTreeState=${gitTreeState}" 12 | 13 | all: gotool 14 | @go build -v -ldflags ${ldflags} . 15 | clean: 16 | rm -f apiserver 17 | find . -name "[._]*.s[a-w][a-z]" | xargs -i rm -f {} 18 | gotool: 19 | gofmt -w . 20 | go tool vet . |& grep -v vendor;true 21 | ca: 22 | openssl req -new -nodes -x509 -out conf/server.crt -keyout conf/server.key -days 3650 -subj "/C=DE/ST=NRW/L=Earth/O=Random Company/OU=IT/CN=127.0.0.1/emailAddress=xxxxx@qq.com" 23 | 24 | help: 25 | @echo "make - compile the source code" 26 | @echo "make clean - remove binary file and vim swp files" 27 | @echo "make gotool - run go tool 'fmt' and 'vet'" 28 | @echo "make ca - generate ca files" 29 | 30 | .PHONY: clean gotool ca help 31 | 32 | 33 | -------------------------------------------------------------------------------- /demo16/Makefile: -------------------------------------------------------------------------------- 1 | SHELL := /bin/bash 2 | BASEDIR = $(shell pwd) 3 | 4 | # build with verison infos 5 | versionDir = "apiserver/pkg/version" 6 | gitTag = $(shell if [ "`git describe --tags --abbrev=0 2>/dev/null`" != "" ];then git describe --tags --abbrev=0; else git log --pretty=format:'%h' -n 1; fi) 7 | buildDate = $(shell TZ=Asia/Shanghai date +%FT%T%z) 8 | gitCommit = $(shell git log --pretty=format:'%H' -n 1) 9 | gitTreeState = $(shell if git status|grep -q 'clean';then echo clean; else echo dirty; fi) 10 | 11 | ldflags="-w -X ${versionDir}.gitTag=${gitTag} -X ${versionDir}.buildDate=${buildDate} -X ${versionDir}.gitCommit=${gitCommit} -X ${versionDir}.gitTreeState=${gitTreeState}" 12 | 13 | all: gotool 14 | @go build -v -ldflags ${ldflags} . 15 | clean: 16 | rm -f apiserver 17 | find . -name "[._]*.s[a-w][a-z]" | xargs -i rm -f {} 18 | gotool: 19 | gofmt -w . 20 | go tool vet . |& grep -v vendor;true 21 | ca: 22 | openssl req -new -nodes -x509 -out conf/server.crt -keyout conf/server.key -days 3650 -subj "/C=DE/ST=NRW/L=Earth/O=Random Company/OU=IT/CN=127.0.0.1/emailAddress=xxxxx@qq.com" 23 | 24 | help: 25 | @echo "make - compile the source code" 26 | @echo "make clean - remove binary file and vim swp files" 27 | @echo "make gotool - run go tool 'fmt' and 'vet'" 28 | @echo "make ca - generate ca files" 29 | 30 | .PHONY: clean gotool ca help 31 | 32 | 33 | -------------------------------------------------------------------------------- /demo17/Makefile: -------------------------------------------------------------------------------- 1 | SHELL := /bin/bash 2 | BASEDIR = $(shell pwd) 3 | 4 | # build with verison infos 5 | versionDir = "apiserver/pkg/version" 6 | gitTag = $(shell if [ "`git describe --tags --abbrev=0 2>/dev/null`" != "" ];then git describe --tags --abbrev=0; else git log --pretty=format:'%h' -n 1; fi) 7 | buildDate = $(shell TZ=Asia/Shanghai date +%FT%T%z) 8 | gitCommit = $(shell git log --pretty=format:'%H' -n 1) 9 | gitTreeState = $(shell if git status|grep -q 'clean';then echo clean; else echo dirty; fi) 10 | 11 | ldflags="-w -X ${versionDir}.gitTag=${gitTag} -X ${versionDir}.buildDate=${buildDate} -X ${versionDir}.gitCommit=${gitCommit} -X ${versionDir}.gitTreeState=${gitTreeState}" 12 | 13 | all: gotool 14 | @go build -v -ldflags ${ldflags} . 15 | clean: 16 | rm -f apiserver 17 | find . -name "[._]*.s[a-w][a-z]" | xargs -i rm -f {} 18 | gotool: 19 | gofmt -w . 20 | go tool vet . |& grep -v vendor;true 21 | ca: 22 | openssl req -new -nodes -x509 -out conf/server.crt -keyout conf/server.key -days 3650 -subj "/C=DE/ST=NRW/L=Earth/O=Random Company/OU=IT/CN=127.0.0.1/emailAddress=xxxxx@qq.com" 23 | 24 | help: 25 | @echo "make - compile the source code" 26 | @echo "make clean - remove binary file and vim swp files" 27 | @echo "make gotool - run go tool 'fmt' and 'vet'" 28 | @echo "make ca - generate ca files" 29 | 30 | .PHONY: clean gotool ca help 31 | 32 | 33 | -------------------------------------------------------------------------------- /demo16/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "net/http" 5 | 6 | "apiserver/handler/sd" 7 | "apiserver/handler/user" 8 | "apiserver/router/middleware" 9 | 10 | "github.com/gin-contrib/pprof" 11 | "github.com/gin-gonic/gin" 12 | ) 13 | 14 | // Load loads the middlewares, routes, handlers. 15 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 16 | // Middlewares. 17 | g.Use(gin.Recovery()) 18 | g.Use(middleware.NoCache) 19 | g.Use(middleware.Options) 20 | g.Use(middleware.Secure) 21 | g.Use(mw...) 22 | // 404 Handler. 23 | g.NoRoute(func(c *gin.Context) { 24 | c.String(http.StatusNotFound, "The incorrect API route.") 25 | }) 26 | 27 | // pprof router 28 | pprof.Register(g) 29 | 30 | // api for authentication functionalities 31 | g.POST("/login", user.Login) 32 | 33 | // The user handlers, requiring authentication 34 | u := g.Group("/v1/user") 35 | u.Use(middleware.AuthMiddleware()) 36 | { 37 | u.POST("", user.Create) 38 | u.DELETE("/:id", user.Delete) 39 | u.PUT("/:id", user.Update) 40 | u.GET("", user.List) 41 | u.GET("/:username", user.Get) 42 | } 43 | 44 | // The health check handlers 45 | svcd := g.Group("/sd") 46 | { 47 | svcd.GET("/health", sd.HealthCheck) 48 | svcd.GET("/disk", sd.DiskCheck) 49 | svcd.GET("/cpu", sd.CPUCheck) 50 | svcd.GET("/ram", sd.RAMCheck) 51 | } 52 | 53 | return g 54 | } 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 目录 2 | 3 | **注意:** 此项目不再维护,如果想学习本项目可以移步:https://github.com/marmotedu/goserver 4 | 5 | **另外**:此课程已经升级为极客时间课程,课程介绍[《Go 语言项目开发实战》](https://time.geekbang.org/column/intro/100079601),建议学习该课程,更专业、内容更多。 6 | 7 | ## apiserver_demos 项目介绍 8 | 9 | 本教程是掘金小册:[基于 Go 语言构建企业级的 RESTful API 服务](https://juejin.cn/book/6844733730678898702) 实战类教学项目,旨在让初学者花尽可能短的时间,通过尽可能详细的步骤,历经 17 个 demo,最终一步步构建出一个生产级的 API 服务器。从开发准备到 API 设计,再到 API 实现、测试和部署,每一步都详细介绍了如何去构建。通过本教程的学习,你将学到如下知识点: 10 | 11 | ![技术雷达](./docs/技术雷达.png) 12 | 13 | 知识点很多,跟着教程一节一节进行学习,你将完整的学会如何用 Go 做 API 开发。 14 | 15 | ## 源码目录介绍 16 | 17 | | 目录 | 介绍 | 18 | | --- | --- | 19 | | demo01 |实战:启动一个最简单的 RESTful API 服务器 | 20 | | demo02 |实战:配置文件读取 | 21 | | demo03 |实战:记录和管理 API 日志 | 22 | | demo04 |实战:初始化 MySQL 数据库并建立连接 | 23 | | demo05 |实战:自定义业务错误信息 | 24 | | demo06 |实战:读取和返回 HTTP 请求 | 25 | | demo07 |实战:用户业务逻辑处理(业务处理) | 26 | | demo08 |实战:HTTP 调用添加自定义处理逻辑 | 27 | | demo09 |实战:API 身份验证 | 28 | | demo10 |进阶:用 HTTPS 加密 API 请求 | 29 | | demo11 |进阶:用 Makefile 管理 API 项目 | 30 | | demo12 |进阶:给 API 命令增加版本功能 | 31 | | demo13 |进阶:给 API 增加启动脚本 | 32 | | demo14 |进阶:基于 Nginx 的 API 部署方案 | 33 | | demo15 |进阶:go test 测试你的代码 | 34 | | demo16 |进阶:API 性能分析 | 35 | | demo17 |进阶:生成 Swagger 在线文档 | 36 | 37 | ## 项目适宜人群 38 | 39 | - 掌握一定 Go 语法基础,零 Go 服务器研发经验,想通过一个完整的实战,来系统学习 Go 服务器开发的同学; 40 | - 有意从事 Go 服务器开发,但尚未入门或入门尚浅的同学; 41 | - 有过 Go 服务器开发经验,但想了解某一部分构建方法的同学。 42 | 43 | 44 | ## 你应该具备什么 45 | 46 | - 基本的 Go 语言编程知识 47 | - 基本的 Linux/Uinx 命令行知识 48 | -------------------------------------------------------------------------------- /demo01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "log" 6 | "net/http" 7 | "time" 8 | 9 | "apiserver/router" 10 | 11 | "github.com/gin-gonic/gin" 12 | ) 13 | 14 | func main() { 15 | // Create the Gin engine. 16 | g := gin.New() 17 | 18 | middlewares := []gin.HandlerFunc{} 19 | 20 | // Routes. 21 | router.Load( 22 | // Cores. 23 | g, 24 | 25 | // Middlwares. 26 | middlewares..., 27 | ) 28 | 29 | // Ping the server to make sure the router is working. 30 | go func() { 31 | if err := pingServer(); err != nil { 32 | log.Fatal("The router has no response, or it might took too long to start up.", err) 33 | } 34 | log.Print("The router has been deployed successfully.") 35 | }() 36 | 37 | log.Printf("Start to listening the incoming requests on http address: %s", ":8080") 38 | log.Printf(http.ListenAndServe(":8080", g).Error()) 39 | } 40 | 41 | // pingServer pings the http server to make sure the router is working. 42 | func pingServer() error { 43 | for i := 0; i < 2; i++ { 44 | // Ping the server by sending a GET request to `/health`. 45 | resp, err := http.Get("http://127.0.0.1:8080" + "/sd/health") 46 | if err == nil && resp.StatusCode == 200 { 47 | return nil 48 | } 49 | 50 | // Sleep for a second to continue the next ping. 51 | log.Print("Waiting for the router, retry in 1 second.") 52 | time.Sleep(time.Second) 53 | } 54 | return errors.New("Cannot connect to the router.") 55 | } 56 | -------------------------------------------------------------------------------- /demo10/conf/server.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIID2TCCAsGgAwIBAgIJAMQRszo28YxYMA0GCSqGSIb3DQEBBQUAMIGCMQswCQYD 3 | VQQGEwJERTEMMAoGA1UECAwDTlJXMQ4wDAYDVQQHDAVFYXJ0aDEXMBUGA1UECgwO 4 | UmFuZG9tIENvbXBhbnkxCzAJBgNVBAsMAklUMRIwEAYDVQQDDAkxMjcuMC4wLjEx 5 | GzAZBgkqhkiG9w0BCQEWDHh4eHh4QHFxLmNvbTAeFw0xODA2MDQwNTI5MzdaFw0y 6 | ODA2MDEwNTI5MzdaMIGCMQswCQYDVQQGEwJERTEMMAoGA1UECAwDTlJXMQ4wDAYD 7 | VQQHDAVFYXJ0aDEXMBUGA1UECgwOUmFuZG9tIENvbXBhbnkxCzAJBgNVBAsMAklU 8 | MRIwEAYDVQQDDAkxMjcuMC4wLjExGzAZBgkqhkiG9w0BCQEWDHh4eHh4QHFxLmNv 9 | bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALw6CzJlFxNg79rSbFa/ 10 | Qn1IThDOb+MKOOpQjeWCSrKFTrWnU36BouUN7b9VYEn9+GpcFoyaThK5HsJX4wyd 11 | 65yTCct3WieuegdpbttA5w8vcHbUNwvfk9WTBbxXbweZrVajsGRhg1Y+8B2UM/DG 12 | dzwrkO3woKaTrYlo7kkVFegODUhE7+KkEt/B9hiLf8WWk9fDjh8VVq0mXRQXhuIR 13 | OfJ1UFb7CEdAoQa99wS0sc2hYW4QAkElgVbCAK+w2H1sPl48xaIVhsgeS/4BR1Om 14 | EsykygsFtU8jwO4J/c/e8seekNFPssUBc/kFHQXp333H/zMhFLQfYcEZW/wPTV8R 15 | C2ECAwEAAaNQME4wHQYDVR0OBBYEFCSzcWsMsL3gGOUnlWxSUZZOrud3MB8GA1Ud 16 | IwQYMBaAFCSzcWsMsL3gGOUnlWxSUZZOrud3MAwGA1UdEwQFMAMBAf8wDQYJKoZI 17 | hvcNAQEFBQADggEBAK8GS3jy4Og6WHB68BPCc2odBjAlug91otn0PNtpfp431fWw 18 | bpviOqRtr6aFqJ8SwdVtWynjAXTTeKZNJB0XNf7HnPMC15A+L4MwtUH9SPQ3abeW 19 | XLQTGl0Q5sgLPR9jADQ3gEgoO4cgKMNy97YhemkQZ1PpVhH9VGObebObcpPRvtQL 20 | 5+TurehVL1hYsrQ5e6q1VUZg/DJuYT096t238vYU5GimLgv8d4GSXA/PbAeTBzd6 21 | 1mofLFAyp2eJkjOZgo8OgNVSQ3aRqUluoD/8qSjnBhr9GoANCuBFJMphqPqMxYtZ 22 | cBM/rpG8PFiF5gCjeU/6rt+39w9QEST7y583dVk= 23 | -----END CERTIFICATE----- 24 | -------------------------------------------------------------------------------- /demo11/conf/server.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIID2TCCAsGgAwIBAgIJAI/8axTNy37vMA0GCSqGSIb3DQEBBQUAMIGCMQswCQYD 3 | VQQGEwJERTEMMAoGA1UECAwDTlJXMQ4wDAYDVQQHDAVFYXJ0aDEXMBUGA1UECgwO 4 | UmFuZG9tIENvbXBhbnkxCzAJBgNVBAsMAklUMRIwEAYDVQQDDAkxMjcuMC4wLjEx 5 | GzAZBgkqhkiG9w0BCQEWDHh4eHh4QHFxLmNvbTAeFw0xODA2MDQwNjMwMzFaFw0y 6 | ODA2MDEwNjMwMzFaMIGCMQswCQYDVQQGEwJERTEMMAoGA1UECAwDTlJXMQ4wDAYD 7 | VQQHDAVFYXJ0aDEXMBUGA1UECgwOUmFuZG9tIENvbXBhbnkxCzAJBgNVBAsMAklU 8 | MRIwEAYDVQQDDAkxMjcuMC4wLjExGzAZBgkqhkiG9w0BCQEWDHh4eHh4QHFxLmNv 9 | bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKHbnpmaxHokFC8rnJlG 10 | 42eL4C3tog7rffv96DrwDajdFNk8DeaNUpZ+R4X4YPecumsCsbol2dDC1IHHGJUN 11 | q/A1vRjyDptMLmzp30p1aqVPcz+j8GMXtZUflLgup+HeKZRdrsk/0SaH1C3ywUBm 12 | yDMNHUxEvoFj0x9aJoPutnkEk9miZt/kF2vxlTbKFM14/TecVr3ljNwTebJAqEw9 13 | iaZpNXn/IQV2I2PTGlxjyT6XNsCchjMTJ9y/XS9rBeX6BFHgQsV52CW1mWz8FieM 14 | /nyF9hE/TZKCpMtHWEYIdBbrxxY0BlhMxEtyIFzTha5zltFrQJGUYz7RIlyuabjk 15 | or8CAwEAAaNQME4wHQYDVR0OBBYEFIjLBQlToqUDoyOLeUd6HeaqiiLJMB8GA1Ud 16 | IwQYMBaAFIjLBQlToqUDoyOLeUd6HeaqiiLJMAwGA1UdEwQFMAMBAf8wDQYJKoZI 17 | hvcNAQEFBQADggEBAHAqpqGNUNgYCr3JvrVULDqFKmqLpvDKfLd6kmtnFzvuZLSz 18 | ANE2RXXqQ5Ms3F0oHqZQq4aOvgvfas5dBLoToPL/ip+GibQ7O/1PsPD5bZaczUel 19 | AnmClX4ewcOEWmZx9mbYOz2C8RREvKU3MoBERrWA33LquYH0+8W8WHyMKNNF97oD 20 | BgWZ8R1t3N59ySZyHcye7ddlJUubRbdyCGrHbmziHV3Cj61NJiwS2JRvhYkc71M6 21 | 8921j63qEM6i0NusFYG/w0GM3x/OeaeY/om6x+IOhJp3vIa1JPSekVyNSCwDEc3B 22 | +8WmVFaeMMXwErSkuu8nCbqRP8J1jiKgzpG/92g= 23 | -----END CERTIFICATE----- 24 | -------------------------------------------------------------------------------- /demo12/conf/server.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIID2TCCAsGgAwIBAgIJAI/8axTNy37vMA0GCSqGSIb3DQEBBQUAMIGCMQswCQYD 3 | VQQGEwJERTEMMAoGA1UECAwDTlJXMQ4wDAYDVQQHDAVFYXJ0aDEXMBUGA1UECgwO 4 | UmFuZG9tIENvbXBhbnkxCzAJBgNVBAsMAklUMRIwEAYDVQQDDAkxMjcuMC4wLjEx 5 | GzAZBgkqhkiG9w0BCQEWDHh4eHh4QHFxLmNvbTAeFw0xODA2MDQwNjMwMzFaFw0y 6 | ODA2MDEwNjMwMzFaMIGCMQswCQYDVQQGEwJERTEMMAoGA1UECAwDTlJXMQ4wDAYD 7 | VQQHDAVFYXJ0aDEXMBUGA1UECgwOUmFuZG9tIENvbXBhbnkxCzAJBgNVBAsMAklU 8 | MRIwEAYDVQQDDAkxMjcuMC4wLjExGzAZBgkqhkiG9w0BCQEWDHh4eHh4QHFxLmNv 9 | bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKHbnpmaxHokFC8rnJlG 10 | 42eL4C3tog7rffv96DrwDajdFNk8DeaNUpZ+R4X4YPecumsCsbol2dDC1IHHGJUN 11 | q/A1vRjyDptMLmzp30p1aqVPcz+j8GMXtZUflLgup+HeKZRdrsk/0SaH1C3ywUBm 12 | yDMNHUxEvoFj0x9aJoPutnkEk9miZt/kF2vxlTbKFM14/TecVr3ljNwTebJAqEw9 13 | iaZpNXn/IQV2I2PTGlxjyT6XNsCchjMTJ9y/XS9rBeX6BFHgQsV52CW1mWz8FieM 14 | /nyF9hE/TZKCpMtHWEYIdBbrxxY0BlhMxEtyIFzTha5zltFrQJGUYz7RIlyuabjk 15 | or8CAwEAAaNQME4wHQYDVR0OBBYEFIjLBQlToqUDoyOLeUd6HeaqiiLJMB8GA1Ud 16 | IwQYMBaAFIjLBQlToqUDoyOLeUd6HeaqiiLJMAwGA1UdEwQFMAMBAf8wDQYJKoZI 17 | hvcNAQEFBQADggEBAHAqpqGNUNgYCr3JvrVULDqFKmqLpvDKfLd6kmtnFzvuZLSz 18 | ANE2RXXqQ5Ms3F0oHqZQq4aOvgvfas5dBLoToPL/ip+GibQ7O/1PsPD5bZaczUel 19 | AnmClX4ewcOEWmZx9mbYOz2C8RREvKU3MoBERrWA33LquYH0+8W8WHyMKNNF97oD 20 | BgWZ8R1t3N59ySZyHcye7ddlJUubRbdyCGrHbmziHV3Cj61NJiwS2JRvhYkc71M6 21 | 8921j63qEM6i0NusFYG/w0GM3x/OeaeY/om6x+IOhJp3vIa1JPSekVyNSCwDEc3B 22 | +8WmVFaeMMXwErSkuu8nCbqRP8J1jiKgzpG/92g= 23 | -----END CERTIFICATE----- 24 | --------------------------------------------------------------------------------