Compare commits
4 Commits
log/v0.13.
...
httpdata/v
| Author | SHA1 | Date | |
|---|---|---|---|
| 91a82b5f48 | |||
| c2bf543f0a | |||
| c82211c957 | |||
| a698a8135d |
95
exegroup/eghttp/actor.go
Normal file
95
exegroup/eghttp/actor.go
Normal 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
|
||||
}
|
||||
@@ -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
141
httpdata/.golangci.yaml
Normal 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
14
httpdata/code.go
Normal 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
22
httpdata/data.go
Normal 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
42
httpdata/error.go
Normal 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
3
httpdata/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module git.blauwelle.com/go/crate/httpdata
|
||||
|
||||
go 1.21.1
|
||||
@@ -54,8 +54,7 @@ log.Logger()
|
||||
- `SetReportStack` 设置生成调用栈;
|
||||
- `SetReportStackLevel` 当日志等级小于设定值时强制生成调用栈;
|
||||
- `Reset` 把 Logger 恢复到初始状态;
|
||||
- `AddBeforeExit` 新增调用 `Logger.Exit` 时优先执行的函数, 先增加的后执行;
|
||||
- `SetExit` 设置 `Logger` 的退出函数(`Logger.Exit`), 当日志等级为 `LevelFatal` 时调用这个函数;
|
||||
- `AddBeforeExit` 增加 Exit 在调用 [os.Exit] 前执行的函数, 先增加的后执行;
|
||||
|
||||
### 日志生成
|
||||
|
||||
|
||||
@@ -20,7 +20,6 @@ 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
|
||||
@@ -99,7 +98,6 @@ 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()
|
||||
@@ -125,27 +123,13 @@ func (logger *Logger) BeforeExit() {
|
||||
})
|
||||
}
|
||||
|
||||
// Exit 执行 BeforeExit 后退出程序, 执行的退出函数可以通过 SetExit 指定,
|
||||
// 当没有通过 SetExit 指定退出函数时调用 [os.Exit].
|
||||
// Exit 执行 BeforeExit 后调用 [os.Exit]退出程序.
|
||||
func (logger *Logger) Exit(code int) {
|
||||
logger.BeforeExit()
|
||||
logger.lock.RLock()
|
||||
exit := logger.exit
|
||||
logger.lock.RUnlock()
|
||||
if exit == nil {
|
||||
exit = os.Exit
|
||||
}
|
||||
exit(code)
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
// SetExit 指定退出程序时执行的函数
|
||||
func (logger *Logger) SetExit(fn func(code int)) {
|
||||
logger.lock.Lock()
|
||||
logger.exit = fn
|
||||
logger.lock.Unlock()
|
||||
}
|
||||
|
||||
// AddBeforeExit 增加 Exit 在调用 SetExit 指定的函数前执行的函数,
|
||||
// AddBeforeExit 增加 Exit 在调用 [os.Exit] 前执行的函数,
|
||||
// 先增加的后执行.
|
||||
func (logger *Logger) AddBeforeExit(fn ...func()) {
|
||||
logger.lock.Lock()
|
||||
|
||||
Reference in New Issue
Block a user