Golang中如何根据参数调用不同的函数代码(Pluggable)

How to call different function code based on parameters(Pluggable) in Golang

我想实施一个 enables several different features based on different startup parameters or configuration files 可插入功能集 的项目。想要的效果是main.go可以根据参数运行调用cmd/<feature>/<feature>.go中的函数

├── cmd
│   ├── feature1
│   │   └── feature1.go
│   └── feature2
│       └── feature2.go
├── pkg
│   ├── feature1
│   │   └── feature1.go
│   └── feature2
│       └── feature2.go
└── main.go

项目 complex 并且需要 extended

有没有可以学习的design pattern或者existing project,有希望可以指教

非常感谢您对此提供的帮助。

这里有两件事需要讨论。

  1. 项目结构
  2. 可扩展性和可维护性

如果你想构建一个单一的应用程序,我建议你在 cmd 目录中有一个模块,在 pkg 目录中有所有功能(每个 cmd dir/file申请):

├── cmd
│   └── main.go
└── pkg
    ├── features
    │   ├── feature1.go
    │   ├── feature2.go
    │   └── feature3.go
    └── service
        └── service.go

如果功能集应该是可扩展的,您可能需要一个接口,所有功能都将实现该接口,例如:

type Feature interface {
    Run(context.Context) error
}

此外,您将拥有一项服务,该服务应使用提供的功能构建:

// pkg/service/service.go

type Service interface {
    Run(context.Context) error
}

// service is the Service implementation
type service struct {
    features []Feature
}

// Run runs the service. The service runs the features.
func (s *service) Run (ctx context.Context) error {
    for _, f := range s.features {
        err := f.Run(ctx)
        // check the error
    }
    // the rest of your code 
}

创建具有任意功能集的服务应该很容易。最简单的方法是将一部分功能传递给服务构造函数:

func NewService(features []Feature) Service {
    return &service{features: features}
}

将功能传递给服务构造函数的一种更优雅的方法是使用 functional options pattern.