From d614bcc8e1838d463ccf19361dd7b3da6aa4e32e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E6=B6=9B?= Date: Tue, 9 Aug 2022 15:22:25 +0800 Subject: [PATCH] =?UTF-8?q?feat(foundation):=E6=9E=84=E5=BB=BA=E5=9F=BA?= =?UTF-8?q?=E6=9C=AC=E7=9A=84=E8=B7=AF=E7=94=B1=E5=88=9B=E5=BB=BA=E7=BB=93?= =?UTF-8?q?=E6=9E=84=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.go | 9 +++------ response/base-response.go | 28 ++++++++++++++++++++++++++++ router/router.go | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 6 deletions(-) create mode 100644 response/base-response.go create mode 100644 router/router.go diff --git a/main.go b/main.go index 4bf8598..42f0dc0 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package main import ( "electricity_bill_calc/config" "electricity_bill_calc/global" + "electricity_bill_calc/router" "fmt" "log" @@ -30,11 +31,7 @@ func init() { } func main() { - r := gin.Default() - r.GET("/ping", func(c *gin.Context) { - c.JSON(200, gin.H{ - "message": "pong", - }) - }) + gin.SetMode(config.ServerSettings.RunMode) + r := router.Router() r.Run(fmt.Sprintf(":%d", config.ServerSettings.HttpPort)) } diff --git a/response/base-response.go b/response/base-response.go new file mode 100644 index 0000000..756492f --- /dev/null +++ b/response/base-response.go @@ -0,0 +1,28 @@ +package response + +import ( + "net/http" + + "github.com/gin-gonic/gin" +) + +type Result struct { + Ctx *gin.Context +} + +type BaseResponse struct { + Code int `json:"code"` + Message string `json:"message"` +} + +func NewResult(ctx *gin.Context) *Result { + return &Result{Ctx: ctx} +} + +// 统一出错信息 +func (r *Result) Error(code int, msg string) { + res := BaseResponse{} + res.Code = code + res.Message = msg + r.Ctx.JSON(http.StatusOK, res) +} diff --git a/router/router.go b/router/router.go new file mode 100644 index 0000000..66f8622 --- /dev/null +++ b/router/router.go @@ -0,0 +1,35 @@ +package router + +import ( + "electricity_bill_calc/response" + "log" + "runtime/debug" + + "github.com/gin-gonic/gin" +) + +func Router() *gin.Engine { + router := gin.Default() + router.Use(Recover) + + return router +} + +//404 +func HandleNotFound(c *gin.Context) { + response.NewResult(c).Error(404, "资源未找到") +} + +//500 +func Recover(c *gin.Context) { + defer func() { + if r := recover(); r != nil { + //打印错误堆栈信息 + log.Printf("panic: %v\n", r) + debug.PrintStack() + response.NewResult(c).Error(500, "服务器内部错误") + } + }() + //继续后续接口调用 + c.Next() +}