feat(foundation):构建基本的路由创建结构。
This commit is contained in:
parent
35dc66f935
commit
d614bcc8e1
9
main.go
9
main.go
|
@ -3,6 +3,7 @@ package main
|
||||||
import (
|
import (
|
||||||
"electricity_bill_calc/config"
|
"electricity_bill_calc/config"
|
||||||
"electricity_bill_calc/global"
|
"electricity_bill_calc/global"
|
||||||
|
"electricity_bill_calc/router"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
|
||||||
|
@ -30,11 +31,7 @@ func init() {
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
r := gin.Default()
|
gin.SetMode(config.ServerSettings.RunMode)
|
||||||
r.GET("/ping", func(c *gin.Context) {
|
r := router.Router()
|
||||||
c.JSON(200, gin.H{
|
|
||||||
"message": "pong",
|
|
||||||
})
|
|
||||||
})
|
|
||||||
r.Run(fmt.Sprintf(":%d", config.ServerSettings.HttpPort))
|
r.Run(fmt.Sprintf(":%d", config.ServerSettings.HttpPort))
|
||||||
}
|
}
|
||||||
|
|
28
response/base-response.go
Normal file
28
response/base-response.go
Normal file
|
@ -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)
|
||||||
|
}
|
35
router/router.go
Normal file
35
router/router.go
Normal file
|
@ -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()
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user