Compare commits

..

13 Commits

28 changed files with 1029 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
require (
git.blauwelle.com/go/crate/exegroup v0.3.0
git.blauwelle.com/go/crate/log v0.6.0
git.blauwelle.com/go/crate/exegroup v0.4.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.3.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.6.0/go.mod h1:jfVfpRODZTA70A8IkApVeGsS1zfLk1D77sLWZM/w+L0=
git.blauwelle.com/go/crate/exegroup v0.4.0 h1:hr9vhYDL+LidvoEBCabdUZ22oekUq0s2NK69tklb42g=
git.blauwelle.com/go/crate/exegroup v0.4.0/go.mod h1:DJoID54YI5WFHGHoTCjBao8oS3HFRzwbWMZW6P57AIQ=
git.blauwelle.com/go/crate/log v0.9.0 h1:H01AQIKcYybeCZGdReBzMoWhkXPQJAoY1t+K0J1asEk=
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"
)
const (
maxParseMemory = 16 * 1024 * 1024
)
func newHandler() http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
start := time.Now()
@@ -59,7 +63,6 @@ func newHandler() http.HandlerFunc {
log.Field("code", code),
log.Field("duration", duration.String()),
).Info(ctx, message)
}
}
@@ -93,6 +96,7 @@ type ResponseRequest struct {
ContentLength int64 `json:"contentLength"`
}
//nolint:cyclop
func readBody(ctx context.Context, r *http.Request) (any, error) {
contentType := r.Header.Get("Content-Type")
switch {
@@ -122,7 +126,7 @@ func readBody(ctx context.Context, r *http.Request) (any, error) {
return string(b), nil
//case :
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())
return nil, err
}
@@ -148,8 +152,9 @@ func readBody(ctx context.Context, r *http.Request) (any, error) {
log.Error(ctx, err.Error())
return nil, err
}
if len(b) > 96 {
b = b[:96]
const maxBodyByteSizeToReturn = 96
if len(b) > maxBodyByteSizeToReturn {
b = b[:maxBodyByteSizeToReturn]
}
return b, nil
}

View File

@@ -11,7 +11,7 @@ import (
"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() {
flag.Parse()
@@ -20,7 +20,7 @@ func main() {
mux := http.NewServeMux()
var handler http.Handler = mux
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.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() {
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.Parse()
if count < 1 {
@@ -34,7 +34,7 @@ func main() {
fmt.Printf("retry %d after %s...\n", i, 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.Stderr = os.Stderr
err = cmd.Run()

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

@@ -0,0 +1,73 @@
package eghttp
import (
"context"
"net"
"net/http"
"strconv"
"sync/atomic"
"time"
)
const (
DefaultAddr = ":8080"
DefaultReadHeaderTimeout = time.Second
)
type Option interface {
apply(server *http.Server)
}
func WithPort(port int) Option {
return optionFunc(func(server *http.Server) {
server.Addr = net.JoinHostPort("", strconv.Itoa(port))
})
}
func WithHandler(handler http.Handler) Option {
return optionFunc(func(server *http.Server) {
server.Handler = handler
})
}
// WithServerOption 使用 fn 配置 [http.Server];
func WithServerOption(fn func(server *http.Server)) Option {
return optionFunc(fn)
}
type optionFunc func(server *http.Server)
func (fn optionFunc) apply(server *http.Server) {
fn(server)
}
// HTTPListenAndServe 创建 [http.Server] 并提供启动和停止函数;
// opts 按照顺序应用到 [http.Server] 上.
func HTTPListenAndServe(opts ...Option) (func(ctx context.Context) error, func(ctx context.Context)) {
server := &http.Server{
Addr: DefaultAddr,
ReadHeaderTimeout: DefaultReadHeaderTimeout,
}
for _, opt := range opts {
opt.apply(server)
}
return HTTPServer(server)
}
// HTTPServer 提供 [http.Server] 的启动和停止函数;
func HTTPServer(server *http.Server) (func(ctx context.Context) error, func(ctx context.Context)) {
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
}

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
}

View File

@@ -54,7 +54,7 @@ log.Logger()
- `SetReportStack` 设置生成调用栈;
- `SetReportStackLevel` 当日志等级小于设定值时强制生成调用栈;
- `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...)
}
// Panicf 格式化输出 LevelPanic 等级的日志
// Panicf 格式化输出 LevelPanic 等级的日志,
// 即使 Logger 日志等级高于 LevelPanic 也会 panic.
func Panicf(ctx context.Context, format string, args ...any) {
globalLogger.AddCallerSkip(1).Panicf(ctx, format, args...)
}
// Exit 调用全局 logger 的 Exit
func Exit(code int) {
globalLogger.Exit(code)
}
// Logger 返回全局 logger, 通常用来在程序启动时对全局 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)
}
// Panicf 格式化输出 LevelPanic 等级的日志
// Panicf 格式化输出 LevelPanic 等级的日志,
// 即使 Logger 日志等级高于 LevelPanic 也会 panic.
func (entry Entry) Panicf(ctx context.Context, format string, args ...any) {
entry.log(ctx, LevelPanic, fmt.Sprintf(format, args...))
}
func (entry Entry) log(ctx context.Context, level Level, message string) {
newEntry := entry.copy()
defer func() {
if level == LevelPanic {
panic(message)
}
}()
newEntry := entry.copy()
if newEntry.logger.GetLevel() < level {
return
}

View File

@@ -1,6 +1,8 @@
package logsdk
import "fmt"
import (
"fmt"
)
// Level 日志等级
type Level int
@@ -12,6 +14,30 @@ func (level Level) String() string {
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) {
switch level {
case LevelPanic:
@@ -38,14 +64,14 @@ const (
// LevelCount 日志等级的个数
LevelCount = 7
// LevelOffset 是把 LevelInfo 等级的日志值偏移到零值的偏移量
LevelOffset = 4
// levelOffset 是把 LevelInfo 等级的日志值偏移到零值的偏移量
levelOffset = 4
)
const (
// LevelDisabled 表示不处理任何等级的日志,
// 其他日志等级的值越小表示日志严重程度越高.
LevelDisabled Level = iota - LevelOffset - 1
LevelDisabled Level = iota - levelOffset - 1
LevelPanic
LevelFatal
LevelError

View File

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

View File

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

View File

@@ -23,6 +23,7 @@ func newConfig(opts ...Option) *config {
func defaultConfig() *config {
return &config{
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
type Option interface {
apply(cfg *config)
@@ -42,6 +50,7 @@ type Option interface {
type config struct {
bytesBufferPool logjson.BytesBufferPool
hasPool bool
defaultSpan bool
}
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/logjson"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
semconv "go.opentelemetry.io/otel/semconv/v1.17.0"
@@ -20,6 +21,7 @@ func New(opts ...Option) *Processor {
cfg := newConfig(opts...)
return &Processor{
bufferPool: cfg.bytesBufferPool,
defaultSpan: cfg.defaultSpan,
}
}
@@ -28,10 +30,17 @@ var _ logsdk.EntryProcessor = &Processor{}
// Processor 用于把日志和 opentelemetry 对接
type Processor struct {
bufferPool logjson.BytesBufferPool
defaultSpan bool
}
func (processor *Processor) Process(ctx context.Context, entry logsdk.ReadonlyEntry) {
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() {
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
}
func (w *syncWriter) Write(p []byte) (n int, err error) {
func (w *syncWriter) Write(p []byte) (int, error) {
w.lock.Lock()
defer w.lock.Unlock()
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
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
}
func ExampleRFC3339Nano2Sec() {
func ExampleRFC3339_nano2Sec() {
t, _ := time.Parse(time.RFC3339Nano, "2023-01-15T15:16:17.123456789+08:00")
fmt.Println(t.Format(time.RFC3339))
// Output: 2023-01-15T15:16:17+08:00
}
// 使用 RFC3339 没有丢失纳秒精度
func ExampleRFC3339Sec2Nano() {
func ExampleRFC3339_sec2Nano() {
t, _ := time.Parse(time.RFC3339, "2023-01-15T15:16:17.123456789+08:00")
fmt.Println(t.Format(time.RFC3339Nano))
// 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")
fmt.Println(t.Format(time.RFC3339Nano))
// 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/trace v1.13.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/text v0.7.0 // 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.6.0 h1:L4ZwwTvKW9gr0ZMS1yrHD9GZhIuVjOBBnaKH+SPQK0Q=
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-20190226205417-e64efc72b421/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{}
guess := InjectGuessWithoutMock(rander)
rander.Value = 1
fmt.Println("approachA:", guess.Guess(10))
fmt.Println("approachA:", guess.Guess(10)) //nolint:gomnd
}
// approach B:
@@ -25,5 +25,5 @@ func approachA() {
func approachB() {
guessWithMock := InjectMockGuess()
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{}
func (r *DefaultRander) Rand() int {
return rand.Int()
return rand.Int() //nolint:gosec
}
func NewRander() *DefaultRander {