package responsex import ( "context" "fmt" ) type options struct { logger Logger ignoreLog bool traceId string defaultSuccessCode int defaultErrorCode int } var op *options = nil func init() { op = defaultOptions() } func InitOptions(ops ...Option) { for _, o := range ops { o(op) } } func defaultOptions() *options { return &options{ logger: &defaultLogger{}, defaultSuccessCode: 200, defaultErrorCode: 400, } } type Option func(*options) // 设置默认的成功code func SetDefaultSuccessCode(code int) Option { return func(o *options) { o.defaultSuccessCode = code } } // 设置默认的失败code func SetDefaultErrorCode(code int) Option { return func(o *options) { o.defaultErrorCode = code } } // 是否需要打印日志 func SetIgnoreLog() Option { return func(o *options) { o.ignoreLog = true } } // 设置日志打印器 func SetLogger(logger Logger) Option { return func(o *options) { o.logger = logger } } // 是否需要响应trace_id,&ctx里面的字段 func SetTraceId(traceId string) Option { return func(o *options) { o.traceId = traceId } } // trace_id如何获取 type Logger interface { Info(ctx context.Context, args ...interface{}) Infof(ctx context.Context, format string, args ...interface{}) Error(ctx context.Context, args ...interface{}) Errorf(ctx context.Context, format string, args ...interface{}) } type defaultLogger struct{} func (d defaultLogger) Info(ctx context.Context, args ...interface{}) { fmt.Println(args...) } func (d *defaultLogger) Infof(ctx context.Context, format string, args ...interface{}) { fmt.Printf(format, args...) } func (d defaultLogger) Error(ctx context.Context, args ...interface{}) { fmt.Println(args...) } func (d *defaultLogger) Errorf(ctx context.Context, format string, args ...interface{}) { fmt.Printf(format, args...) }