巧用golang的context减少方法传参

时间:2025-03-26 08:07:54
  • package options
  • import (
  • "context"
  • "fmt"
  • )
  • type demoConfig struct {
  • demoInt int64
  • demoBool bool
  • demoString string
  • }
  • type Option func(*demoConfig)
  • func DemoInt(in int64) Option {
  • return func(dc *demoConfig) {
  • = in
  • }
  • }
  • func DemoBool(in bool) Option {
  • return func(dc *demoConfig) {
  • = in
  • }
  • }
  • func DemoString(in string) Option {
  • return func(dc *demoConfig) {
  • = in
  • }
  • }
  • func (dc *demoConfig) Apply(opts ...Option) {
  • for _, opt := range opts {
  • opt(dc)
  • }
  • }
  • type demoConfigKey struct {}
  • // 赋值到context
  • func WithContext(ctx , cfg demoConfig) {
  • return (ctx, demoConfigKey{}, cfg)
  • }
  • type createFunc func() demoConfig
  • // 取出context中的config
  • func FromContextOrCreate(ctx , create createFunc) demoConfig {
  • vc, ok := (demoConfigKey{}).(demoConfig)
  • if !ok {
  • return create()
  • }
  • return vc
  • }
  • type Service struct {}
  • func NewService() *Service {
  • return &Service{}
  • }
  • func (s *Service) DefaultDemoConfigCreater() createFunc {
  • return func() demoConfig {
  • return demoConfig{
  • // default val
  • demoString: "hello",
  • }
  • }
  • }
  • func (s *Service) Demo(ctx ) {
  • cfg := FromContextOrCreate(ctx, ())
  • // print: {27 false hello}
  • (cfg)
  • }