Compare commits

...

15 Commits

33 changed files with 1273 additions and 86 deletions

View File

@@ -0,0 +1,138 @@
## 更新到 golangci-lint@v1.52.2
run:
timeout: 1m
build-tags: [ ]
skip-dirs: [ ]
skip-files: [ ]
linters:
disable-all: true
enable:
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- typecheck
- unused
- asasalint
- asciicheck
- bidichk
- bodyclose
- containedctx
- cyclop
- dupl
- durationcheck
- errname
- errorlint
- exhaustive
- exportloopref
- funlen
- gocheckcompilerdirectives
- gochecknoinits
- goconst
- gocritic
- gocyclo
- goimports
- gomnd
- goprintffuncname
- gosec
- lll
- loggercheck
- makezero
- nakedret
- nestif
- nilnil
- noctx
- nolintlint
- nosprintfhostport
- prealloc
- predeclared
- promlinter
- reassign
- revive
- stylecheck
- tenv
- testableexamples
- testpackage
- tparallel
- unconvert
- unparam
- usestdlibvars
- wastedassign
- whitespace
linters-settings:
errcheck:
check-type-assertions: true
exclude-functions: [ ]
govet:
enable-all: true
disable: [ ]
cyclop:
max-complexity: 10
package-average: 0.0
dupl:
threshold: 150
exhaustive:
check:
- switch
- map
funlen:
lines: 100
statements: 60
gocritic:
disabled-checks:
- commentFormatting
settings:
captLocal:
paramsOnly: false
underef:
skipRecvDeref: false
gocyclo:
min-complexity: 20
gomnd:
ignored-functions:
- os.Chmod
- os.Mkdir
- os.MkdirAll
- os.OpenFile
- os.WriteFile
- prometheus.ExponentialBuckets
- prometheus.ExponentialBucketsRange
- prometheus.LinearBuckets
lll:
line-length: 240
nakedret:
max-func-lines: 10
nestif:
min-complexity: 5
predeclared:
ignore: ""
q: false
reassign:
patterns:
- ".*"
tenv:
all: true
usestdlibvars:
time-month: true
time-layout: true
crypto-hash: true
default-rpc-path: true
os-dev-null: true
sql-isolation-level: true
tls-signature-scheme: true
constant-kind: true
syslog-priority: true
issues:
max-same-issues: 10
exclude-rules:
- source: "//noinspection"
linters: [ gocritic ]
- path: "_test\\.go"
linters:
- bodyclose
- dupl
- funlen
- goconst
- gosec
- noctx

View File

@@ -3,6 +3,6 @@ module git.blauwelle.com/go/crate/cmd/http-reflect-server
go 1.20 go 1.20
require ( require (
git.blauwelle.com/go/crate/exegroup v0.3.0 git.blauwelle.com/go/crate/exegroup v0.4.0
git.blauwelle.com/go/crate/log v0.6.0 git.blauwelle.com/go/crate/log v0.9.0
) )

View File

@@ -1,4 +1,4 @@
git.blauwelle.com/go/crate/exegroup v0.3.0 h1:TBLygDztECKc67NeIIBsFDxlA4KcJpbOmafqqRuKRcM= git.blauwelle.com/go/crate/exegroup v0.4.0 h1:hr9vhYDL+LidvoEBCabdUZ22oekUq0s2NK69tklb42g=
git.blauwelle.com/go/crate/exegroup v0.3.0/go.mod h1:DJoID54YI5WFHGHoTCjBao8oS3HFRzwbWMZW6P57AIQ= git.blauwelle.com/go/crate/exegroup v0.4.0/go.mod h1:DJoID54YI5WFHGHoTCjBao8oS3HFRzwbWMZW6P57AIQ=
git.blauwelle.com/go/crate/log v0.6.0 h1:s/TeJUaV/Y8hHaz/3FumdbwQWCbRMmOx8prrNmByJHs= git.blauwelle.com/go/crate/log v0.9.0 h1:H01AQIKcYybeCZGdReBzMoWhkXPQJAoY1t+K0J1asEk=
git.blauwelle.com/go/crate/log v0.6.0/go.mod h1:jfVfpRODZTA70A8IkApVeGsS1zfLk1D77sLWZM/w+L0= git.blauwelle.com/go/crate/log v0.9.0/go.mod h1:jfVfpRODZTA70A8IkApVeGsS1zfLk1D77sLWZM/w+L0=

View File

@@ -12,6 +12,10 @@ import (
"git.blauwelle.com/go/crate/log" "git.blauwelle.com/go/crate/log"
) )
const (
maxParseMemory = 16 * 1024 * 1024
)
func newHandler() http.HandlerFunc { func newHandler() http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) { return func(rw http.ResponseWriter, r *http.Request) {
start := time.Now() start := time.Now()
@@ -59,7 +63,6 @@ func newHandler() http.HandlerFunc {
log.Field("code", code), log.Field("code", code),
log.Field("duration", duration.String()), log.Field("duration", duration.String()),
).Info(ctx, message) ).Info(ctx, message)
} }
} }
@@ -93,6 +96,7 @@ type ResponseRequest struct {
ContentLength int64 `json:"contentLength"` ContentLength int64 `json:"contentLength"`
} }
//nolint:cyclop
func readBody(ctx context.Context, r *http.Request) (any, error) { func readBody(ctx context.Context, r *http.Request) (any, error) {
contentType := r.Header.Get("Content-Type") contentType := r.Header.Get("Content-Type")
switch { switch {
@@ -122,7 +126,7 @@ func readBody(ctx context.Context, r *http.Request) (any, error) {
return string(b), nil return string(b), nil
//case : //case :
case strings.HasPrefix(contentType, "multipart/form-data"): case strings.HasPrefix(contentType, "multipart/form-data"):
if err := r.ParseMultipartForm(16 * 1024 * 1024); err != nil { if err := r.ParseMultipartForm(maxParseMemory); err != nil {
log.Error(ctx, err.Error()) log.Error(ctx, err.Error())
return nil, err return nil, err
} }
@@ -148,8 +152,9 @@ func readBody(ctx context.Context, r *http.Request) (any, error) {
log.Error(ctx, err.Error()) log.Error(ctx, err.Error())
return nil, err return nil, err
} }
if len(b) > 96 { const maxBodyByteSizeToReturn = 96
b = b[:96] if len(b) > maxBodyByteSizeToReturn {
b = b[:maxBodyByteSizeToReturn]
} }
return b, nil return b, nil
} }

View File

@@ -11,7 +11,7 @@ import (
"git.blauwelle.com/go/crate/log/logsdk/logjson" "git.blauwelle.com/go/crate/log/logsdk/logjson"
) )
var port = flag.Int("port", 8080, "HTTP Port") var port = flag.Int("port", 8080, "HTTP Port") //nolint:gomnd
func main() { func main() {
flag.Parse() flag.Parse()
@@ -20,7 +20,7 @@ func main() {
mux := http.NewServeMux() mux := http.NewServeMux()
var handler http.Handler = mux var handler http.Handler = mux
mux.HandleFunc("/", newHandler()) mux.HandleFunc("/", newHandler())
g.New().WithGoStop(exegroup.HttpListenAndServe(*port, handler)) g.New().WithGoStop(exegroup.HTTPListenAndServe(*port, handler))
log.Infof(context.Background(), "listening %d", *port) log.Infof(context.Background(), "listening %d", *port)
log.Error(context.Background(), "exit: ", g.Run(context.Background())) log.Error(context.Background(), "exit: ", g.Run(context.Background()))
} }

138
cmd/retry/.golangci.yaml Normal file
View File

@@ -0,0 +1,138 @@
## 更新到 golangci-lint@v1.52.2
run:
timeout: 1m
build-tags: [ ]
skip-dirs: [ ]
skip-files: [ ]
linters:
disable-all: true
enable:
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- typecheck
- unused
- asasalint
- asciicheck
- bidichk
- bodyclose
- containedctx
- cyclop
- dupl
- durationcheck
- errname
- errorlint
- exhaustive
- exportloopref
- funlen
- gocheckcompilerdirectives
- gochecknoinits
- goconst
- gocritic
- gocyclo
- goimports
- gomnd
- goprintffuncname
- gosec
- lll
- loggercheck
- makezero
- nakedret
- nestif
- nilnil
- noctx
- nolintlint
- nosprintfhostport
- prealloc
- predeclared
- promlinter
- reassign
- revive
- stylecheck
- tenv
- testableexamples
- testpackage
- tparallel
- unconvert
- unparam
- usestdlibvars
- wastedassign
- whitespace
linters-settings:
errcheck:
check-type-assertions: true
exclude-functions: [ ]
govet:
enable-all: true
disable: [ ]
cyclop:
max-complexity: 10
package-average: 0.0
dupl:
threshold: 150
exhaustive:
check:
- switch
- map
funlen:
lines: 100
statements: 60
gocritic:
disabled-checks:
- commentFormatting
settings:
captLocal:
paramsOnly: false
underef:
skipRecvDeref: false
gocyclo:
min-complexity: 20
gomnd:
ignored-functions:
- os.Chmod
- os.Mkdir
- os.MkdirAll
- os.OpenFile
- os.WriteFile
- prometheus.ExponentialBuckets
- prometheus.ExponentialBucketsRange
- prometheus.LinearBuckets
lll:
line-length: 240
nakedret:
max-func-lines: 10
nestif:
min-complexity: 5
predeclared:
ignore: ""
q: false
reassign:
patterns:
- ".*"
tenv:
all: true
usestdlibvars:
time-month: true
time-layout: true
crypto-hash: true
default-rpc-path: true
os-dev-null: true
sql-isolation-level: true
tls-signature-scheme: true
constant-kind: true
syslog-priority: true
issues:
max-same-issues: 10
exclude-rules:
- source: "//noinspection"
linters: [ gocritic ]
- path: "_test\\.go"
linters:
- bodyclose
- dupl
- funlen
- goconst
- gosec
- noctx

View File

@@ -14,7 +14,7 @@ var (
) )
func main() { func main() {
flag.IntVar(&count, "c", 5, "maximum execution times") flag.IntVar(&count, "c", 5, "maximum execution times") //nolint:gomnd
flag.DurationVar(&interval, "i", time.Second, "retry interval") flag.DurationVar(&interval, "i", time.Second, "retry interval")
flag.Parse() flag.Parse()
if count < 1 { if count < 1 {
@@ -34,7 +34,7 @@ func main() {
fmt.Printf("retry %d after %s...\n", i, interval) fmt.Printf("retry %d after %s...\n", i, interval)
time.Sleep(interval) time.Sleep(interval)
} }
cmd := exec.Command(args[0], args[1:]...) cmd := exec.Command(args[0], args[1:]...) // #nosec G204
cmd.Stdout = os.Stdout cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr
err = cmd.Run() err = cmd.Run()

95
exegroup/eghttp/actor.go Normal file
View File

@@ -0,0 +1,95 @@
package eghttp
import (
"context"
"net"
"net/http"
"strconv"
"sync/atomic"
"time"
)
const (
DefaultAddr = ":8080"
DefaultReadHeaderTimeout = time.Second
)
type Option interface {
apply(cfg *config)
}
func WithPort(port int) Option {
return optionFunc(func(cfg *config) {
cfg.server.Addr = net.JoinHostPort("", strconv.Itoa(port))
})
}
func WithHandler(handler http.Handler) Option {
return optionFunc(func(cfg *config) {
cfg.server.Handler = handler
})
}
func WithServer(server *http.Server) Option {
return optionFunc(func(cfg *config) {
cfg.server = server
})
}
func WithStartFn(fn func(server *http.Server) error) Option {
return optionFunc(func(cfg *config) {
cfg.startFn = fn
})
}
// WithServerOption 使用 fn 配置 [http.Server];
func WithServerOption(fn func(server *http.Server)) Option {
return optionFunc(func(cfg *config) {
fn(cfg.server)
})
}
type config struct {
server *http.Server
startFn func(server *http.Server) error
}
func newDefaultConfig() *config {
return &config{
server: &http.Server{
Addr: DefaultAddr,
ReadHeaderTimeout: DefaultReadHeaderTimeout,
},
startFn: func(server *http.Server) error {
return server.ListenAndServe()
},
}
}
type optionFunc func(cfg *config)
func (fn optionFunc) apply(cfg *config) {
fn(cfg)
}
// HTTPListenAndServe 创建 [http.Server] 并提供启动和停止函数;
func HTTPListenAndServe(opts ...Option) (func(ctx context.Context) error, func(ctx context.Context)) {
cfg := newDefaultConfig()
for _, opt := range opts {
opt.apply(cfg)
}
inShutdown := &atomic.Bool{}
c := make(chan error, 1)
goFunc := func(_ context.Context) error {
err := cfg.startFn(cfg.server)
if inShutdown.Load() {
err = <-c
}
return err
}
stopFunc := func(ctx context.Context) {
inShutdown.Store(true)
c <- cfg.server.Shutdown(ctx)
}
return goFunc, stopFunc
}

View File

@@ -1,33 +0,0 @@
package exegroup
import (
"context"
"net"
"net/http"
"strconv"
"sync/atomic"
"time"
)
// HTTPListenAndServe 提供 [http.Server] 的启动和停止函数;
func HTTPListenAndServe(port int, handler http.Handler) (func(ctx context.Context) error, func(ctx context.Context)) {
server := &http.Server{
Addr: net.JoinHostPort("", strconv.Itoa(port)),
Handler: handler,
ReadHeaderTimeout: time.Second,
}
inShutdown := &atomic.Bool{}
c := make(chan error, 1)
goFunc := func(_ context.Context) error {
err := server.ListenAndServe()
if inShutdown.Load() {
err = <-c
}
return err
}
stopFunc := func(ctx context.Context) {
inShutdown.Store(true)
c <- server.Shutdown(ctx)
}
return goFunc, stopFunc
}

141
httpdata/.golangci.yaml Normal file
View File

@@ -0,0 +1,141 @@
## 基于 golangci-lint@v1.52.2
run:
timeout: 1m
build-tags: [ ]
skip-dirs: [ ]
skip-files: [ ]
linters:
disable-all: true
enable:
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- typecheck
- unused
- asasalint
- asciicheck
- bidichk
- bodyclose
- containedctx
- cyclop
- dupl
- durationcheck
- errname
- errorlint
- exhaustive
- exportloopref
- funlen
- gocheckcompilerdirectives
- gochecknoinits
- goconst
- gocritic
- gocyclo
- goimports
- gomnd
- goprintffuncname
- gosec
- lll
- loggercheck
- makezero
- nakedret
- nestif
- nilnil
- noctx
- nolintlint
- prealloc
- predeclared
- promlinter
- reassign
- revive
- rowserrcheck
- stylecheck
- tenv
- testableexamples
- testpackage
- tparallel
- unconvert
- unparam
- usestdlibvars
- wastedassign
- whitespace
linters-settings:
errcheck:
check-type-assertions: true
exclude-functions: [ ]
govet:
enable-all: true
disable: [ ]
cyclop:
max-complexity: 10
package-average: 0.0
dupl:
threshold: 150
exhaustive:
check:
- switch
- map
funlen:
lines: 100
statements: 60
gocritic:
disabled-checks:
- commentFormatting
settings:
captLocal:
paramsOnly: false
underef:
skipRecvDeref: false
gocyclo:
min-complexity: 20
gomnd:
ignored-functions:
- os.Chmod
- os.Mkdir
- os.MkdirAll
- os.OpenFile
- os.WriteFile
- prometheus.ExponentialBuckets
- prometheus.ExponentialBucketsRange
- prometheus.LinearBuckets
lll:
line-length: 240
nakedret:
max-func-lines: 10
nestif:
min-complexity: 5
predeclared:
ignore: ""
q: false
reassign:
patterns:
- ".*"
rowserrcheck:
packages:
- github.com/jmoiron/sqlx
tenv:
all: true
usestdlibvars:
time-month: true
time-layout: true
crypto-hash: true
default-rpc-path: true
os-dev-null: true
sql-isolation-level: true
tls-signature-scheme: true
constant-kind: true
syslog-priority: true
issues:
max-same-issues: 10
exclude-rules:
- source: "//noinspection"
linters: [ gocritic ]
- path: "_test\\.go"
linters:
- bodyclose
- dupl
- funlen
- goconst
- gosec
- noctx

14
httpdata/code.go Normal file
View File

@@ -0,0 +1,14 @@
package httpdata
type Code string
const (
CodeOK Code = "ok"
CodeError Code = "error"
CodeBadRequest Code = "bad_request"
CodeInternal Code = "internal"
CodeInternalUpstream Code = "internal.upstream"
CodeUnexpect Code = "unexpect"
CodeUnexpectPanic Code = "unexpect.panic"
CodeUnknown Code = "unknown"
)

22
httpdata/data.go Normal file
View File

@@ -0,0 +1,22 @@
package httpdata
type Response struct {
Data any `json:"data,omitempty"`
Code Code `json:"code"`
Message string `json:"message,omitempty"`
}
type PageData struct {
List []any `json:"list"`
PageIndex int `json:"pageIndex"` // >=1
PageSize int `json:"pageSize"` // >=1
Total int `json:"total"` // maybe 0
}
func NewOkResponse(data any) Response {
return Response{
Code: CodeOK,
Message: "",
Data: data,
}
}

42
httpdata/error.go Normal file
View File

@@ -0,0 +1,42 @@
package httpdata
import (
"errors"
)
type UniverseError struct {
Code Code
Message string
}
func NewUniverseError(code Code, message string) error {
return UniverseError{
Code: code,
Message: message,
}
}
func NewBadRequestError(message string) error {
return UniverseError{
Code: CodeBadRequest,
Message: message,
}
}
func (err UniverseError) Error() string {
if err.Message == "" {
return string(err.Code)
}
return string(err.Code) + ": " + err.Message
}
func IsUniverseError(err error) bool {
return errors.As(err, &UniverseError{})
}
func ToUniverseError(err error, code Code, message string) error {
if err == nil || IsUniverseError(err) {
return err
}
return NewUniverseError(code, message)
}

3
httpdata/go.mod Normal file
View File

@@ -0,0 +1,3 @@
module git.blauwelle.com/go/crate/httpdata
go 1.21.1

View File

@@ -54,7 +54,7 @@ log.Logger()
- `SetReportStack` 设置生成调用栈; - `SetReportStack` 设置生成调用栈;
- `SetReportStackLevel` 当日志等级小于设定值时强制生成调用栈; - `SetReportStackLevel` 当日志等级小于设定值时强制生成调用栈;
- `Reset` 把 Logger 恢复到初始状态; - `Reset` 把 Logger 恢复到初始状态;
- `SetExit` 设置 `Logger` 的退出函数(`Logger.Exit`), 当日志等级为 `LevelFatal` 时调用这个函数; - `AddBeforeExit` 增加 Exit 在调用 [os.Exit] 前执行的函数, 先增加的后执行;
### 日志生成 ### 日志生成
@@ -84,11 +84,13 @@ log.Logger()
### 其他用法 ### 其他用法
关闭日志生成 `log.Logger().SetLevel(logsdk.LevelDisabled)` 关闭日志生成, `log.Logger().SetLevel(logsdk.LevelDisabled)`;
关闭强制生成调用栈 `log.Logger().SetReportStackLevel(logsdk.LevelDisabled)` 关闭强制生成调用栈, `log.Logger().SetReportStackLevel(logsdk.LevelDisabled)`;
mock 实现 mock 日志处理器对生成的日志进行处理 记录 panic, 在 `defer v = recover()` 后执行 `log.Z(context.Background(), v)`, 其中 `Z` 需要是附加调用栈的等级;
mock, 实现 mock 日志处理器对生成的日志进行处理;
--- ---

View File

@@ -145,11 +145,17 @@ func Fatalf(ctx context.Context, format string, args ...any) {
globalLogger.AddCallerSkip(1).Fatalf(ctx, format, args...) globalLogger.AddCallerSkip(1).Fatalf(ctx, format, args...)
} }
// Panicf 格式化输出 LevelPanic 等级的日志 // Panicf 格式化输出 LevelPanic 等级的日志,
// 即使 Logger 日志等级高于 LevelPanic 也会 panic.
func Panicf(ctx context.Context, format string, args ...any) { func Panicf(ctx context.Context, format string, args ...any) {
globalLogger.AddCallerSkip(1).Panicf(ctx, format, args...) globalLogger.AddCallerSkip(1).Panicf(ctx, format, args...)
} }
// Exit 调用全局 logger 的 Exit
func Exit(code int) {
globalLogger.Exit(code)
}
// Logger 返回全局 logger, 通常用来在程序启动时对全局 logger 进行配置, // Logger 返回全局 logger, 通常用来在程序启动时对全局 logger 进行配置,
// 业务代码处理日志时直接使用这个包里定义的日志函数. // 业务代码处理日志时直接使用这个包里定义的日志函数.
func Logger() *logsdk.Logger { func Logger() *logsdk.Logger {

View File

@@ -169,19 +169,19 @@ func (entry Entry) Fatalf(ctx context.Context, format string, args ...any) {
entry.logger.Exit(1) entry.logger.Exit(1)
} }
// Panicf 格式化输出 LevelPanic 等级的日志 // Panicf 格式化输出 LevelPanic 等级的日志,
// 即使 Logger 日志等级高于 LevelPanic 也会 panic. // 即使 Logger 日志等级高于 LevelPanic 也会 panic.
func (entry Entry) Panicf(ctx context.Context, format string, args ...any) { func (entry Entry) Panicf(ctx context.Context, format string, args ...any) {
entry.log(ctx, LevelPanic, fmt.Sprintf(format, args...)) entry.log(ctx, LevelPanic, fmt.Sprintf(format, args...))
} }
func (entry Entry) log(ctx context.Context, level Level, message string) { func (entry Entry) log(ctx context.Context, level Level, message string) {
newEntry := entry.copy()
defer func() { defer func() {
if level == LevelPanic { if level == LevelPanic {
panic(message) panic(message)
} }
}() }()
newEntry := entry.copy()
if newEntry.logger.GetLevel() < level { if newEntry.logger.GetLevel() < level {
return return
} }

View File

@@ -1,6 +1,8 @@
package logsdk package logsdk
import "fmt" import (
"fmt"
)
// Level 日志等级 // Level 日志等级
type Level int type Level int
@@ -12,6 +14,30 @@ func (level Level) String() string {
return "unknown" return "unknown"
} }
// ParseLevel 把 level 字符串解析成 Level,
// 支持的字符串: panic, fatal, error, warn, info, debug, trace,
// 传入不支持的字符串返回 LevelInfo.
func ParseLevel(s string) Level {
switch s {
case LevelPanicValue:
return LevelPanic
case LevelFatalValue:
return LevelFatal
case LevelErrorValue:
return LevelError
case LevelWarnValue:
return LevelWarn
case LevelInfoValue:
return LevelInfo
case LevelDebugValue:
return LevelDebug
case LevelTraceValue:
return LevelTrace
default:
return LevelInfo
}
}
func (level Level) MarshalText() ([]byte, error) { func (level Level) MarshalText() ([]byte, error) {
switch level { switch level {
case LevelPanic: case LevelPanic:
@@ -38,14 +64,14 @@ const (
// LevelCount 日志等级的个数 // LevelCount 日志等级的个数
LevelCount = 7 LevelCount = 7
// LevelOffset 是把 LevelInfo 等级的日志值偏移到零值的偏移量 // levelOffset 是把 LevelInfo 等级的日志值偏移到零值的偏移量
LevelOffset = 4 levelOffset = 4
) )
const ( const (
// LevelDisabled 表示不处理任何等级的日志, // LevelDisabled 表示不处理任何等级的日志,
// 其他日志等级的值越小表示日志严重程度越高. // 其他日志等级的值越小表示日志严重程度越高.
LevelDisabled Level = iota - LevelOffset - 1 LevelDisabled Level = iota - levelOffset - 1
LevelPanic LevelPanic
LevelFatal LevelFatal
LevelError LevelError

View File

@@ -20,10 +20,11 @@ type entry = Entry
// Logger 中保存了日志所需的全局配置, // Logger 中保存了日志所需的全局配置,
// 使用 Logger 处理日志. // 使用 Logger 处理日志.
type Logger struct { type Logger struct {
exit func(code int) // protected by lock beforeExitFns []func() // protected by lock
levelProcessors levelProcessors // protected by lock levelProcessors levelProcessors // protected by lock
entry entry
lock sync.RWMutex lock sync.RWMutex
exitOnce sync.Once
level atomic.Int32 level atomic.Int32
reportStackLevel atomic.Int32 reportStackLevel atomic.Int32
callerSkip atomic.Int32 callerSkip atomic.Int32
@@ -35,7 +36,7 @@ type Logger struct {
func (logger *Logger) AddProcessor(levels []Level, processor EntryProcessor) { func (logger *Logger) AddProcessor(levels []Level, processor EntryProcessor) {
logger.lock.Lock() logger.lock.Lock()
for _, level := range levels { for _, level := range levels {
logger.levelProcessors[level+LevelOffset] = append(logger.levelProcessors[level+LevelOffset], processor) logger.levelProcessors[level+levelOffset] = append(logger.levelProcessors[level+levelOffset], processor)
} }
logger.lock.Unlock() logger.lock.Unlock()
} }
@@ -97,7 +98,7 @@ func (logger *Logger) SetReportStackLevel(level Level) {
// Reset 把 Logger 重置到初始状态 // Reset 把 Logger 重置到初始状态
func (logger *Logger) Reset() { func (logger *Logger) Reset() {
logger.lock.Lock() logger.lock.Lock()
logger.exit = nil logger.beforeExitFns = nil
logger.levelProcessors = levelProcessors{} logger.levelProcessors = levelProcessors{}
logger.lock.Unlock() logger.lock.Unlock()
@@ -108,28 +109,38 @@ func (logger *Logger) Reset() {
logger.SetReportStack(false) logger.SetReportStack(false)
} }
// Exit 退出程序, 执行的具体过程可以通过 SetExit 指定 // BeforeExit 按照先添加后执行的顺序执行 AddBeforeExit 添加的函数,
func (logger *Logger) Exit(code int) { // AddBeforeExit 只会执行1次.
logger.lock.RLock() func (logger *Logger) BeforeExit() {
exit := logger.exit logger.exitOnce.Do(func() {
logger.lock.RUnlock() logger.lock.RLock()
if exit == nil { beforeExitFns := make([]func(), len(logger.beforeExitFns))
os.Exit(code) copy(beforeExitFns, logger.beforeExitFns)
} logger.lock.RUnlock()
exit(code) for i := len(beforeExitFns) - 1; i >= 0; i-- {
beforeExitFns[i]()
}
})
} }
// SetExit 指定退出程序时执行的函数 // Exit 执行 BeforeExit 后调用 [os.Exit]退出程序.
func (logger *Logger) SetExit(fn func(code int)) { func (logger *Logger) Exit(code int) {
logger.BeforeExit()
os.Exit(code)
}
// AddBeforeExit 增加 Exit 在调用 [os.Exit] 前执行的函数,
// 先增加的后执行.
func (logger *Logger) AddBeforeExit(fn ...func()) {
logger.lock.Lock() logger.lock.Lock()
logger.exit = fn logger.beforeExitFns = append(logger.beforeExitFns, fn...)
logger.lock.Unlock() logger.lock.Unlock()
} }
func (logger *Logger) getLevelProcessors(level Level) []EntryProcessor { func (logger *Logger) getLevelProcessors(level Level) []EntryProcessor {
logger.lock.RLock() logger.lock.RLock()
defer logger.lock.RUnlock() defer logger.lock.RUnlock()
return logger.levelProcessors[level+LevelOffset] return logger.levelProcessors[level+levelOffset]
} }
func (logger *Logger) newEntry() Entry { func (logger *Logger) newEntry() Entry {

View File

@@ -8,6 +8,8 @@ const (
maximumFrames = 32 maximumFrames = 32
getCallerSkipOffset = 2 getCallerSkipOffset = 2
entrySkipOffset = 2 entrySkipOffset = 2
runtimeMain = "runtime.main"
) )
// Frame 调用相关信息 // Frame 调用相关信息
@@ -44,6 +46,9 @@ func getStack(skip, maximumFrames int) []Frame {
for { for {
frame, more := frames.Next() frame, more := frames.Next()
if frame.PC != 0 { if frame.PC != 0 {
if frame.Function == runtimeMain {
break
}
stack = append(stack, Frame{ stack = append(stack, Frame{
Function: frame.Function, Function: frame.Function,
File: frame.File, File: frame.File,

View File

@@ -22,7 +22,8 @@ func newConfig(opts ...Option) *config {
func defaultConfig() *config { func defaultConfig() *config {
return &config{ return &config{
hasPool: false, hasPool: false,
defaultSpan: false,
} }
} }
@@ -34,6 +35,13 @@ func WithBufferPool(pool logjson.BytesBufferPool) Option {
}) })
} }
// WithDefaultSpan 设置当 span 没有在记录时创建新 span
func WithDefaultSpan(defaultSpan bool) Option {
return optionFunc(func(cfg *config) {
cfg.defaultSpan = defaultSpan
})
}
// Option 配置 Processor // Option 配置 Processor
type Option interface { type Option interface {
apply(cfg *config) apply(cfg *config)
@@ -42,6 +50,7 @@ type Option interface {
type config struct { type config struct {
bytesBufferPool logjson.BytesBufferPool bytesBufferPool logjson.BytesBufferPool
hasPool bool hasPool bool
defaultSpan bool
} }
type optionFunc func(cfg *config) type optionFunc func(cfg *config)

View File

@@ -9,6 +9,7 @@ import (
"git.blauwelle.com/go/crate/log/logsdk" "git.blauwelle.com/go/crate/log/logsdk"
"git.blauwelle.com/go/crate/log/logsdk/logjson" "git.blauwelle.com/go/crate/log/logsdk/logjson"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
semconv "go.opentelemetry.io/otel/semconv/v1.17.0" semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
@@ -19,7 +20,8 @@ import (
func New(opts ...Option) *Processor { func New(opts ...Option) *Processor {
cfg := newConfig(opts...) cfg := newConfig(opts...)
return &Processor{ return &Processor{
bufferPool: cfg.bytesBufferPool, bufferPool: cfg.bytesBufferPool,
defaultSpan: cfg.defaultSpan,
} }
} }
@@ -27,11 +29,18 @@ var _ logsdk.EntryProcessor = &Processor{}
// Processor 用于把日志和 opentelemetry 对接 // Processor 用于把日志和 opentelemetry 对接
type Processor struct { type Processor struct {
bufferPool logjson.BytesBufferPool bufferPool logjson.BytesBufferPool
defaultSpan bool
} }
func (processor *Processor) Process(ctx context.Context, entry logsdk.ReadonlyEntry) { func (processor *Processor) Process(ctx context.Context, entry logsdk.ReadonlyEntry) {
span := trace.SpanFromContext(ctx) span := trace.SpanFromContext(ctx)
if !span.IsRecording() {
if processor.defaultSpan {
ctx, span = otel.Tracer("git.blauwelle.com/go/crate/logotel").Start(ctx, "default") //nolint:ineffassign,staticcheck,wastedassign
defer span.End()
}
}
if !span.IsRecording() { if !span.IsRecording() {
return return
} }

138
synchelper/.golangci.yaml Normal file
View File

@@ -0,0 +1,138 @@
## 更新到 golangci-lint@v1.52.2
run:
timeout: 1m
build-tags: [ ]
skip-dirs: [ ]
skip-files: [ ]
linters:
disable-all: true
enable:
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- typecheck
- unused
- asasalint
- asciicheck
- bidichk
- bodyclose
- containedctx
- cyclop
- dupl
- durationcheck
- errname
- errorlint
- exhaustive
- exportloopref
- funlen
- gocheckcompilerdirectives
- gochecknoinits
- goconst
- gocritic
- gocyclo
- goimports
- gomnd
- goprintffuncname
- gosec
- lll
- loggercheck
- makezero
- nakedret
- nestif
- nilnil
- noctx
- nolintlint
- nosprintfhostport
- prealloc
- predeclared
- promlinter
- reassign
- revive
- stylecheck
- tenv
- testableexamples
- testpackage
- tparallel
- unconvert
- unparam
- usestdlibvars
- wastedassign
- whitespace
linters-settings:
errcheck:
check-type-assertions: true
exclude-functions: [ ]
govet:
enable-all: true
disable: [ ]
cyclop:
max-complexity: 10
package-average: 0.0
dupl:
threshold: 150
exhaustive:
check:
- switch
- map
funlen:
lines: 100
statements: 60
gocritic:
disabled-checks:
- commentFormatting
settings:
captLocal:
paramsOnly: false
underef:
skipRecvDeref: false
gocyclo:
min-complexity: 20
gomnd:
ignored-functions:
- os.Chmod
- os.Mkdir
- os.MkdirAll
- os.OpenFile
- os.WriteFile
- prometheus.ExponentialBuckets
- prometheus.ExponentialBucketsRange
- prometheus.LinearBuckets
lll:
line-length: 240
nakedret:
max-func-lines: 10
nestif:
min-complexity: 5
predeclared:
ignore: ""
q: false
reassign:
patterns:
- ".*"
tenv:
all: true
usestdlibvars:
time-month: true
time-layout: true
crypto-hash: true
default-rpc-path: true
os-dev-null: true
sql-isolation-level: true
tls-signature-scheme: true
constant-kind: true
syslog-priority: true
issues:
max-same-issues: 10
exclude-rules:
- source: "//noinspection"
linters: [ gocritic ]
- path: "_test\\.go"
linters:
- bodyclose
- dupl
- funlen
- goconst
- gosec
- noctx

View File

@@ -18,7 +18,7 @@ type syncWriter struct {
lock sync.Mutex lock sync.Mutex
} }
func (w *syncWriter) Write(p []byte) (n int, err error) { func (w *syncWriter) Write(p []byte) (int, error) {
w.lock.Lock() w.lock.Lock()
defer w.lock.Unlock() defer w.lock.Unlock()
return w.writer.Write(p) return w.writer.Write(p)

138
timehelper/.golangci.yaml Normal file
View File

@@ -0,0 +1,138 @@
## 更新到 golangci-lint@v1.52.2
run:
timeout: 1m
build-tags: [ ]
skip-dirs: [ ]
skip-files: [ ]
linters:
disable-all: true
enable:
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- typecheck
- unused
- asasalint
- asciicheck
- bidichk
- bodyclose
- containedctx
- cyclop
- dupl
- durationcheck
- errname
- errorlint
- exhaustive
- exportloopref
- funlen
- gocheckcompilerdirectives
- gochecknoinits
- goconst
- gocritic
- gocyclo
- goimports
- gomnd
- goprintffuncname
- gosec
- lll
- loggercheck
- makezero
- nakedret
- nestif
- nilnil
- noctx
- nolintlint
- nosprintfhostport
- prealloc
- predeclared
- promlinter
- reassign
- revive
- stylecheck
- tenv
- testableexamples
- testpackage
- tparallel
- unconvert
- unparam
- usestdlibvars
- wastedassign
- whitespace
linters-settings:
errcheck:
check-type-assertions: true
exclude-functions: [ ]
govet:
enable-all: true
disable: [ ]
cyclop:
max-complexity: 10
package-average: 0.0
dupl:
threshold: 150
exhaustive:
check:
- switch
- map
funlen:
lines: 100
statements: 60
gocritic:
disabled-checks:
- commentFormatting
settings:
captLocal:
paramsOnly: false
underef:
skipRecvDeref: false
gocyclo:
min-complexity: 20
gomnd:
ignored-functions:
- os.Chmod
- os.Mkdir
- os.MkdirAll
- os.OpenFile
- os.WriteFile
- prometheus.ExponentialBuckets
- prometheus.ExponentialBucketsRange
- prometheus.LinearBuckets
lll:
line-length: 240
nakedret:
max-func-lines: 10
nestif:
min-complexity: 5
predeclared:
ignore: ""
q: false
reassign:
patterns:
- ".*"
tenv:
all: true
usestdlibvars:
time-month: true
time-layout: true
crypto-hash: true
default-rpc-path: true
os-dev-null: true
sql-isolation-level: true
tls-signature-scheme: true
constant-kind: true
syslog-priority: true
issues:
max-same-issues: 10
exclude-rules:
- source: "//noinspection"
linters: [ gocritic ]
- path: "_test\\.go"
linters:
- bodyclose
- dupl
- funlen
- goconst
- gosec
- noctx

View File

@@ -4,5 +4,5 @@ import "time"
// SetupCST 把本地时区固定到CST // SetupCST 把本地时区固定到CST
func SetupCST() { func SetupCST() {
time.Local = time.FixedZone("CST", 8*3600) time.Local = time.FixedZone("CST", 8*3600) //nolint:gomnd,reassign
} }

View File

@@ -14,20 +14,20 @@ func ExampleRFC3339Nano() {
// Output: 2023-01-15T15:16:17.123456789+08:00 // Output: 2023-01-15T15:16:17.123456789+08:00
} }
func ExampleRFC3339Nano2Sec() { func ExampleRFC3339_nano2Sec() {
t, _ := time.Parse(time.RFC3339Nano, "2023-01-15T15:16:17.123456789+08:00") t, _ := time.Parse(time.RFC3339Nano, "2023-01-15T15:16:17.123456789+08:00")
fmt.Println(t.Format(time.RFC3339)) fmt.Println(t.Format(time.RFC3339))
// Output: 2023-01-15T15:16:17+08:00 // Output: 2023-01-15T15:16:17+08:00
} }
// 使用 RFC3339 没有丢失纳秒精度 // 使用 RFC3339 没有丢失纳秒精度
func ExampleRFC3339Sec2Nano() { func ExampleRFC3339_sec2Nano() {
t, _ := time.Parse(time.RFC3339, "2023-01-15T15:16:17.123456789+08:00") t, _ := time.Parse(time.RFC3339, "2023-01-15T15:16:17.123456789+08:00")
fmt.Println(t.Format(time.RFC3339Nano)) fmt.Println(t.Format(time.RFC3339Nano))
// Output: 2023-01-15T15:16:17.123456789+08:00 // Output: 2023-01-15T15:16:17.123456789+08:00
} }
func ExampleRFC3339NanoOtherZone() { func ExampleRFC3339_nanoOtherZone() {
t, _ := time.Parse(time.RFC3339Nano, "2023-01-15T15:16:17.123456789+09:00") t, _ := time.Parse(time.RFC3339Nano, "2023-01-15T15:16:17.123456789+09:00")
fmt.Println(t.Format(time.RFC3339Nano)) fmt.Println(t.Format(time.RFC3339Nano))
// Output: 2023-01-15T15:16:17.123456789+09:00 // Output: 2023-01-15T15:16:17.123456789+09:00

View File

@@ -0,0 +1,138 @@
## 更新到 golangci-lint@v1.52.2
run:
timeout: 1m
build-tags: [ ]
skip-dirs: [ ]
skip-files: [ ]
linters:
disable-all: true
enable:
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- typecheck
- unused
- asasalint
- asciicheck
- bidichk
- bodyclose
- containedctx
- cyclop
- dupl
- durationcheck
- errname
- errorlint
- exhaustive
- exportloopref
- funlen
- gocheckcompilerdirectives
- gochecknoinits
- goconst
- gocritic
- gocyclo
- goimports
- gomnd
- goprintffuncname
- gosec
- lll
- loggercheck
- makezero
- nakedret
- nestif
- nilnil
- noctx
- nolintlint
- nosprintfhostport
- prealloc
- predeclared
- promlinter
- reassign
- revive
- stylecheck
- tenv
- testableexamples
- testpackage
- tparallel
- unconvert
- unparam
- usestdlibvars
- wastedassign
- whitespace
linters-settings:
errcheck:
check-type-assertions: true
exclude-functions: [ ]
govet:
enable-all: true
disable: [ ]
cyclop:
max-complexity: 10
package-average: 0.0
dupl:
threshold: 150
exhaustive:
check:
- switch
- map
funlen:
lines: 100
statements: 60
gocritic:
disabled-checks:
- commentFormatting
settings:
captLocal:
paramsOnly: false
underef:
skipRecvDeref: false
gocyclo:
min-complexity: 20
gomnd:
ignored-functions:
- os.Chmod
- os.Mkdir
- os.MkdirAll
- os.OpenFile
- os.WriteFile
- prometheus.ExponentialBuckets
- prometheus.ExponentialBucketsRange
- prometheus.LinearBuckets
lll:
line-length: 240
nakedret:
max-func-lines: 10
nestif:
min-complexity: 5
predeclared:
ignore: ""
q: false
reassign:
patterns:
- ".*"
tenv:
all: true
usestdlibvars:
time-month: true
time-layout: true
crypto-hash: true
default-rpc-path: true
os-dev-null: true
sql-isolation-level: true
tls-signature-scheme: true
constant-kind: true
syslog-priority: true
issues:
max-same-issues: 10
exclude-rules:
- source: "//noinspection"
linters: [ gocritic ]
- path: "_test\\.go"
linters:
- bodyclose
- dupl
- funlen
- goconst
- gosec
- noctx

View File

@@ -23,7 +23,7 @@ require (
go.opentelemetry.io/otel/sdk/metric v0.36.0 // indirect go.opentelemetry.io/otel/sdk/metric v0.36.0 // indirect
go.opentelemetry.io/otel/trace v1.13.0 // indirect go.opentelemetry.io/otel/trace v1.13.0 // indirect
go.opentelemetry.io/proto/otlp v0.19.0 // indirect go.opentelemetry.io/proto/otlp v0.19.0 // indirect
golang.org/x/net v0.6.0 // indirect golang.org/x/net v0.7.0 // indirect
golang.org/x/sys v0.5.0 // indirect golang.org/x/sys v0.5.0 // indirect
golang.org/x/text v0.7.0 // indirect golang.org/x/text v0.7.0 // indirect
google.golang.org/genproto v0.0.0-20230202175211-008b39050e57 // indirect google.golang.org/genproto v0.0.0-20230202175211-008b39050e57 // indirect

View File

@@ -250,6 +250,8 @@ golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81R
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.6.0 h1:L4ZwwTvKW9gr0ZMS1yrHD9GZhIuVjOBBnaKH+SPQK0Q= golang.org/x/net v0.6.0 h1:L4ZwwTvKW9gr0ZMS1yrHD9GZhIuVjOBBnaKH+SPQK0Q=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=

138
wireexample/.golangci.yaml Normal file
View File

@@ -0,0 +1,138 @@
## 更新到 golangci-lint@v1.52.2
run:
timeout: 1m
build-tags: [ ]
skip-dirs: [ ]
skip-files: [ ]
linters:
disable-all: true
enable:
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- typecheck
- unused
- asasalint
- asciicheck
- bidichk
- bodyclose
- containedctx
- cyclop
- dupl
- durationcheck
- errname
- errorlint
- exhaustive
- exportloopref
- funlen
- gocheckcompilerdirectives
- gochecknoinits
- goconst
- gocritic
- gocyclo
- goimports
- gomnd
- goprintffuncname
- gosec
- lll
- loggercheck
- makezero
- nakedret
- nestif
- nilnil
- noctx
- nolintlint
- nosprintfhostport
- prealloc
- predeclared
- promlinter
- reassign
- revive
- stylecheck
- tenv
- testableexamples
- testpackage
- tparallel
- unconvert
- unparam
- usestdlibvars
- wastedassign
- whitespace
linters-settings:
errcheck:
check-type-assertions: true
exclude-functions: [ ]
govet:
enable-all: true
disable: [ ]
cyclop:
max-complexity: 10
package-average: 0.0
dupl:
threshold: 150
exhaustive:
check:
- switch
- map
funlen:
lines: 100
statements: 60
gocritic:
disabled-checks:
- commentFormatting
settings:
captLocal:
paramsOnly: false
underef:
skipRecvDeref: false
gocyclo:
min-complexity: 20
gomnd:
ignored-functions:
- os.Chmod
- os.Mkdir
- os.MkdirAll
- os.OpenFile
- os.WriteFile
- prometheus.ExponentialBuckets
- prometheus.ExponentialBucketsRange
- prometheus.LinearBuckets
lll:
line-length: 240
nakedret:
max-func-lines: 10
nestif:
min-complexity: 5
predeclared:
ignore: ""
q: false
reassign:
patterns:
- ".*"
tenv:
all: true
usestdlibvars:
time-month: true
time-layout: true
crypto-hash: true
default-rpc-path: true
os-dev-null: true
sql-isolation-level: true
tls-signature-scheme: true
constant-kind: true
syslog-priority: true
issues:
max-same-issues: 10
exclude-rules:
- source: "//noinspection"
linters: [ gocritic ]
- path: "_test\\.go"
linters:
- bodyclose
- dupl
- funlen
- goconst
- gosec
- noctx

View File

@@ -16,7 +16,7 @@ func approachA() {
rander := &MockRander{} rander := &MockRander{}
guess := InjectGuessWithoutMock(rander) guess := InjectGuessWithoutMock(rander)
rander.Value = 1 rander.Value = 1
fmt.Println("approachA:", guess.Guess(10)) fmt.Println("approachA:", guess.Guess(10)) //nolint:gomnd
} }
// approach B: // approach B:
@@ -25,5 +25,5 @@ func approachA() {
func approachB() { func approachB() {
guessWithMock := InjectMockGuess() guessWithMock := InjectMockGuess()
guessWithMock.Mock.Value = 1 guessWithMock.Mock.Value = 1
fmt.Println("approachB:", guessWithMock.Guess.Guess(10)) fmt.Println("approachB:", guessWithMock.Guess.Guess(10)) //nolint:gomnd
} }

View File

@@ -14,7 +14,7 @@ type Rander interface {
type DefaultRander struct{} type DefaultRander struct{}
func (r *DefaultRander) Rand() int { func (r *DefaultRander) Rand() int {
return rand.Int() return rand.Int() //nolint:gosec
} }
func NewRander() *DefaultRander { func NewRander() *DefaultRander {