70 lines
1.3 KiB
Go
70 lines
1.3 KiB
Go
package infra
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.apinb.com/bsm-sdk/core/vars"
|
|
"github.com/gofiber/fiber/v2"
|
|
)
|
|
|
|
var Response Reply
|
|
|
|
type Reply struct {
|
|
Ret int `json:"ret"`
|
|
Msg string `json:"msg"`
|
|
Data interface{} `json:"data"`
|
|
}
|
|
|
|
type ReplyIdent struct {
|
|
ID uint `json:"id"`
|
|
Identiy string `json:"identity"`
|
|
}
|
|
|
|
func (r *Reply) Error(ctx *fiber.Ctx, err error) error {
|
|
// Status code defaults to 500
|
|
reply := Reply{
|
|
Ret: http.StatusInternalServerError,
|
|
}
|
|
if e, ok := err.(*fiber.Error); ok {
|
|
reply.Ret = e.Code
|
|
}
|
|
|
|
// 获取执行信息
|
|
ExcuteTime(ctx)
|
|
|
|
reply.Msg = err.Error()
|
|
|
|
// Send error
|
|
return ctx.Status(fiber.StatusInternalServerError).JSON(reply)
|
|
}
|
|
func (r *Reply) Success(ctx *fiber.Ctx, data interface{}) error {
|
|
reply := Reply{
|
|
Ret: http.StatusOK,
|
|
}
|
|
|
|
if data == nil {
|
|
reply.Data = ""
|
|
} else {
|
|
reply.Data = data
|
|
}
|
|
|
|
// 获取执行信息
|
|
ExcuteTime(ctx)
|
|
|
|
return ctx.Status(fiber.StatusOK).JSON(reply)
|
|
}
|
|
|
|
func ExcuteTime(ctx *fiber.Ctx) error {
|
|
// 从context中获取开始时间
|
|
startTime, ok := ctx.Locals("startTime").(time.Time)
|
|
if !ok {
|
|
// 如果转换失败,则默认为当前时间
|
|
startTime = time.Now()
|
|
}
|
|
|
|
exectime := time.Since(startTime)
|
|
ctx.Response().Header.Add("Execute-Node", vars.HostName+","+exectime.String())
|
|
return nil
|
|
}
|