Skip to content

Commit

Permalink
utils:1.移除zaplog文件及方法,2.string方法修改注释,3.字符串拼接改用strings.Builder;sail:新增…
Browse files Browse the repository at this point in the history
…logtrace方法;api:1.修改注释,2.字符串拼接改用strings.Builder;example:修改代码示例
  • Loading branch information
keepchen committed Nov 7, 2024
1 parent b1c2766 commit cd8c71f
Show file tree
Hide file tree
Showing 9 changed files with 186 additions and 167 deletions.
9 changes: 5 additions & 4 deletions constants/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ const (
)

const (
DateLayout string = "2006-01-02" //日期格式
TimeLayout string = "15:04:05" //时间格式
DatetimeLayout string = "2006-01-02 15:04:05" //日期时间格式
DatetimeTZLayout string = "2006-01-02T15:04:05Z" //日期时间格式-tz
DateLayout string = "2006-01-02" //日期格式
TimeLayout string = "15:04:05" //时间格式
DatetimeLayout string = "2006-01-02 15:04:05" //日期时间格式
DatetimeTZLayout string = "2006-01-02T15:04:05Z" //日期时间格式-tz
DateTimeTZLayoutWithMilli = "2006-01-02T15:04:05.000Z" //日期时间格式-tz,带毫秒
)
4 changes: 2 additions & 2 deletions examples/pkg/app/user/service/sayhello.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ func SayHelloSvc(c *gin.Context) {
resp response.SayHello
)
if err := c.ShouldBind(&form); err != nil {
sail.Response(c).Assemble(constants.ErrRequestParamsInvalid, nil).Send()
sail.Response(c).Builder(constants.ErrRequestParamsInvalid, nil).Send()
return
}

if errorCode, err := form.Validator(); err != nil {
sail.Response(c).Assemble(errorCode, nil, err.Error()).Send()
sail.Response(c).Builder(errorCode, nil, err.Error()).Send()
return
}

Expand Down
25 changes: 12 additions & 13 deletions examples/pkg/app/user/service/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package service
import (
"errors"

"go.uber.org/zap"

"github.com/keepchen/go-sail/v3/sail"

"github.com/gin-gonic/gin"
Expand All @@ -11,34 +13,31 @@ import (
"github.com/keepchen/go-sail/v3/examples/pkg/app/user/http/vo/response"
usersSvc "github.com/keepchen/go-sail/v3/examples/pkg/common/db/service/users"
"github.com/keepchen/go-sail/v3/lib/db"
"github.com/keepchen/go-sail/v3/lib/logger"
"go.uber.org/zap"
"gorm.io/gorm"
)

func GetUserInfoSvc(c *gin.Context) {
var (
form request.GetUserInfo
resp response.GetUserInfo
loggerWithFields = logger.GetLogger()
form request.GetUserInfo
resp response.GetUserInfo
logTracer = sail.LogTrace(c)
)
if newLogger, ok := c.Get("logger"); ok {
loggerWithFields = newLogger.(*zap.Logger)
}
if err := c.ShouldBind(&form); err != nil {
sail.Response(c).Assemble(constants.ErrRequestParamsInvalid, nil).Send()
sail.Response(c).Builder(constants.ErrRequestParamsInvalid, nil).Send()
return
}

if errorCode, err := form.Validator(); err != nil {
sail.Response(c).Assemble(errorCode, nil, err.Error()).Send()
sail.Response(c).Builder(errorCode, nil, err.Error()).Send()
return
}

userAndWallet, sqlErr := usersSvc.NewUserSvcImpl(db.GetInstance().R, db.GetInstance().W, loggerWithFields).GetUserAndWallet(form.UserID)
userAndWallet, sqlErr := usersSvc.NewUserSvcImpl(db.GetInstance().R, db.GetInstance().W, logTracer.GetLogger()).GetUserAndWallet(form.UserID)
if sqlErr != nil && errors.Is(sqlErr, gorm.ErrRecordNotFound) {
sail.Response(c).Assemble(constants.ErrRequestParamsInvalid, nil, "user not found").Send()
sail.Response(c).Builder(constants.ErrRequestParamsInvalid, nil, "user not found").Send()
return
} else {
logTracer.Warn("query failed, cause: ", zap.String("err", sqlErr.Error()))
}

resp.Data.User = response.UserInfo{
Expand All @@ -51,5 +50,5 @@ func GetUserInfoSvc(c *gin.Context) {
Status: userAndWallet.Wallet.Status,
}

sail.Response(c).Assemble(constants.ErrNone, resp).Send()
sail.Response(c).Builder(constants.ErrNone, resp).Send()
}
14 changes: 8 additions & 6 deletions http/api/response.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package api

import (
"bytes"
"net/http"
"reflect"
"strings"
"time"

"github.com/gin-gonic/gin"
Expand All @@ -14,6 +14,8 @@ import (
// Responder 响应器
type Responder interface {
// Builder 组装返回数据
//
// 该方法会根据传递的code码自动设置http状态、描述信息、当前系统毫秒时间戳以及请求id(需要在路由配置中调用 middleware.LogTrace 中间件)
Builder(code constants.ICodeType, resp dto.IResponse, message ...string) Responder
// Assemble 组装返回数据
//
Expand All @@ -25,7 +27,7 @@ type Responder interface {
Assemble(code constants.ICodeType, resp dto.IResponse, message ...string) Responder
// Status 指定http状态码
//
// 该方法会覆盖 Assemble 解析的http状态码值
// 该方法会覆盖 Assemble, Builder, SimpleAssemble, Wrap 解析的http状态码值
Status(httpCode int) Responder
// SendWithCode 以指定http状态码响应请求
SendWithCode(httpCode int)
Expand Down Expand Up @@ -307,11 +309,11 @@ func (a *responseEngine) mergeBody(code constants.ICodeType, resp interface{}, m

//如果message有值,则覆盖默认错误码所代表的错误信息
if len(message) > 0 {
var msg bytes.Buffer
var msg = strings.Builder{}
for index, v := range message {
_, _ = msg.Write([]byte(v))
_, _ = msg.WriteString(v)
if index < len(message)-1 {
_, _ = msg.Write([]byte(";"))
_, _ = msg.WriteString(";")
}
}
body.Message = msg.String()
Expand Down Expand Up @@ -347,7 +349,7 @@ func (a *responseEngine) mergeBody(code constants.ICodeType, resp interface{}, m

// Status 指定http状态码
//
// 该方法会覆盖 Assemble 解析的http状态码值
// 该方法会覆盖 Assemble, Builder, SimpleAssemble, Wrap 解析的http状态码值
func (a *responseEngine) Status(httpCode int) Responder {
a.httpCode = httpCode

Expand Down
136 changes: 136 additions & 0 deletions sail/logtrace.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package sail

import (
"github.com/gin-gonic/gin"
"github.com/keepchen/go-sail/v3/lib/logger"
"go.uber.org/zap"
)

// LogTracer 链路日志追踪器
type LogTracer interface {
// GetLogger 获取 zap.Logger 实例
//
// 此实例携带了上下文的requestId和spanId,用于链路追踪
GetLogger() *zap.Logger
// Debug 打印日志
//
// 尝试从上下文中获取logger实例进行打印,
//
// 从上下文中获取的logger实例会携带链路追踪的字段。
//
// 若获取失败,则调用logger库进行打印
//
// 日志级别:Debug
Debug(message string, fields ...zap.Field)
// Info 打印日志
//
// 尝试从上下文中获取logger实例进行打印,
//
// 从上下文中获取的logger实例会携带链路追踪的字段。
//
// 若获取失败,则调用logger库进行打印
//
// 日志级别:Info
Info(message string, fields ...zap.Field)
// Warn 打印日志
//
// 尝试从上下文中获取logger实例进行打印,
//
// 从上下文中获取的logger实例会携带链路追踪的字段。
//
// 若获取失败,则调用logger库进行打印
//
// 日志级别:Warn
Warn(message string, fields ...zap.Field)
// Error 打印日志
//
// 尝试从上下文中获取logger实例进行打印,
//
// 从上下文中获取的logger实例会携带链路追踪的字段。
//
// 若获取失败,则调用logger库进行打印
//
// 日志级别:Error
Error(message string, fields ...zap.Field)
// DPanic 打印日志
//
// 尝试从上下文中获取logger实例进行打印,
//
// 从上下文中获取的logger实例会携带链路追踪的字段。
//
// 若获取失败,则调用logger库进行打印
//
// 日志级别:DPanic
DPanic(message string, fields ...zap.Field)
// Panic 打印日志
//
// 尝试从上下文中获取logger实例进行打印,
//
// 从上下文中获取的logger实例会携带链路追踪的字段。
//
// 若获取失败,则调用logger库进行打印
//
// 日志级别:Panic
Panic(message string, fields ...zap.Field)
// Fatal 打印日志
//
// 尝试从上下文中获取logger实例进行打印,
//
// 从上下文中获取的logger实例会携带链路追踪的字段。
//
// 若获取失败,则调用logger库进行打印
//
// 日志级别:Fatal
Fatal(message string, fields ...zap.Field)
}

type logTrace struct {
ginContext *gin.Context
loggerSvc *zap.Logger
}

var _ LogTracer = (*logTrace)(nil)

// LogTrace 链路日志追踪
func LogTrace(c *gin.Context) LogTracer {
var zapLogger *zap.Logger
if loggerSvc, ok := c.Get("logger"); ok {
zapLogger = loggerSvc.(*zap.Logger)
} else {
zapLogger = logger.GetLogger()
}

return &logTrace{ginContext: c, loggerSvc: zapLogger}
}

func (l *logTrace) GetLogger() *zap.Logger {
return l.loggerSvc
}

func (l *logTrace) Debug(message string, fields ...zap.Field) {
l.loggerSvc.Debug(message, fields...)
}

func (l *logTrace) Info(message string, fields ...zap.Field) {
l.loggerSvc.Info(message, fields...)
}

func (l *logTrace) Warn(message string, fields ...zap.Field) {
l.loggerSvc.Warn(message, fields...)
}

func (l *logTrace) Error(message string, fields ...zap.Field) {
l.loggerSvc.Error(message, fields...)
}

func (l *logTrace) DPanic(message string, fields ...zap.Field) {
l.loggerSvc.DPanic(message, fields...)
}

func (l *logTrace) Panic(message string, fields ...zap.Field) {
l.loggerSvc.Panic(message, fields...)
}

func (l *logTrace) Fatal(message string, fields ...zap.Field) {
l.loggerSvc.Fatal(message, fields...)
}
9 changes: 5 additions & 4 deletions utils/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,25 @@ func Wordwrap(rawStr string, length int, split string) string {
var (
start int
end = length
finalStr string
finalStr = strings.Builder{}
)

for {
if start > len(strSplit) {
break
}
if end >= len(strSplit) {
finalStr += strings.Join(strSplit[start:], "")
finalStr.WriteString(strings.Join(strSplit[start:], ""))
} else {
finalStr += strings.Join(strSplit[start:end], "") + split
finalStr.WriteString(strings.Join(strSplit[start:end], ""))
finalStr.WriteString(split)
}

start = end
end += length
}

return finalStr
return finalStr.String()
}

// WrapRedisKey 包装redis键名
Expand Down
4 changes: 4 additions & 0 deletions utils/string_go1.19.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
)

// StrToBytes 字符串转换为字节数组
//
// nolint
func StrToBytes(s string) []byte {
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := reflect.SliceHeader{Data: sh.Data, Len: sh.Len, Cap: sh.Len}
Expand All @@ -17,6 +19,8 @@ func StrToBytes(s string) []byte {
}

// BytesToStr 字节数组转换为字符串
//
// nolint
func BytesToStr(b []byte) string {
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
sh := reflect.StringHeader{Data: bh.Data, Len: bh.Len}
Expand Down
26 changes: 14 additions & 12 deletions utils/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@ import (
)

type TIM struct {
loc *time.Location
datetimeTZLayout string
datetimeLayout string
dateLayout string
timeLayout string
dirtyTimezone bool
loc *time.Location
datetimeTZLayoutWithMilli string
datetimeTZLayout string
datetimeLayout string
dateLayout string
timeLayout string
dirtyTimezone bool
}

// NewTimeWithTimeZone 根据时区初始化时间
Expand All @@ -37,12 +38,13 @@ func NewTimeWithTimeZone(timeZone ...string) *TIM {
}

return &TIM{
loc: loc,
datetimeTZLayout: constants.DatetimeTZLayout,
datetimeLayout: constants.DatetimeLayout,
dateLayout: constants.DateLayout,
timeLayout: constants.TimeLayout,
dirtyTimezone: dirtyTimezone,
loc: loc,
datetimeTZLayoutWithMilli: constants.DateTimeTZLayoutWithMilli,
datetimeTZLayout: constants.DatetimeTZLayout,
datetimeLayout: constants.DatetimeLayout,
dateLayout: constants.DateLayout,
timeLayout: constants.TimeLayout,
dirtyTimezone: dirtyTimezone,
}
}

Expand Down
Loading

0 comments on commit cd8c71f

Please sign in to comment.