一些典型的矫枉过正「反例」

83 阅读1分钟

过度设计

  • gin返回体的封装

本意抽象逻辑,但实在必要不大。过度设计。练手除外。

package response  
  
type Response struct {  
    RequestId string `json:"requestId,omitempty"`  
    Code      int32  `json:"code,omitempty"`  
    Info      string `json:"info,omitempty"`  
    Msg       string `json:"msg,omitempty"`  
    Status    string `json:"status,omitempty"`  
}  
  
type response struct {  
    Response  
    Data any `json:"data"`  
}  
  
func (e *response) SetTraceID(id string) {  
    e.RequestId = id  
}  
  
func (e *response) SetMsg(msg string) {  
    e.Msg = msg  
}  
  
func (e *response) SetInfo(info string) {  
    e.Info = info  
}  
  
func (e *response) SetCode(code int32) {  
    e.Code = code  
}  
  
func (e *response) SetSuccess(success bool) {  
    if !success {  
       e.Status = "error"  
    }  
}  
  
type Page struct {  
    Count     int `json:"count"`  
    PageIndex int `json:"page_index"`  
    PageSize  int `json:"page_size"`  
}  
  
type page struct {  
    Page  
    List any `json:"list"`  
}  
  
func (e *response) SetData(data any) {  
    e.Data = data  
}  
  
func (e response) Clone() Responses {  
    return &e  
}
var Default = &response{}  
  
// Error 失败数据处理  
func Error(c *gin.Context, code int, err error, msg string) {  
    res := Default.Clone()  
    res.SetInfo(msg)  
    if err != nil {  
       res.SetInfo(err.Error())  
    }  
    if msg != "" {  
       res.SetMsg(msg)  
    }  
    res.SetTraceID(traceId.GetTraceId(c))  
    res.SetCode(int32(code))  
    res.SetSuccess(false)  
    // 记录日志  
    xlog.Error(traceId.GetLogContext(c, msg, logz.F("err", err), logz.F("response", res)))  
    // 写入上下文  
    c.Set("result", res)  
    // 返回结果集  
    c.AbortWithStatusJSON(http.StatusOK, res)  
}  
  
// OK 通常成功数据处理  
func OK(c *gin.Context, data any, msg string) {  
    res := Default.Clone()  
    res.SetData(data)  
    res.SetSuccess(true)  
    if msg != "" {  
       res.SetMsg(msg)  
       res.SetInfo(msg)  
    }  
    res.SetTraceID(traceId.GetTraceId(c))  
    res.SetCode(http.StatusOK)  
    // 记录日志  
    xlog.Info(traceId.GetLogContext(c, msg, logz.F("response", res)))  
    // 写入上下文  
    c.Set("result", res)  
    c.AbortWithStatusJSON(http.StatusOK, res)  
}  
  
// PageOK 分页数据处理  
func PageOK(c *gin.Context, result any, count int, pageIndex int, pageSize int, msg string) {  
    var res page  
    res.List = result  
    res.Count = count  
    res.PageIndex = pageIndex  
    res.PageSize = pageSize  
    OK(c, res, msg)  
}  
  
// Custum 兼容函数  
func Custum(c *gin.Context, data gin.H) {  
    data["requestId"] = traceId.GetTraceId(c)  
    c.Set("result", data)  
    c.AbortWithStatusJSON(http.StatusOK, data)  
}