Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

spi添加 #258

Merged
merged 14 commits into from
Jun 4, 2024
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/ecodeclub/ekit

go 1.20
go 1.22.0

require (
github.com/DATA-DOG/go-sqlmock v1.5.0
Expand Down
65 changes: 65 additions & 0 deletions spi/spi.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright 2021 ecodeclub
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package spi

import (
"errors"
"os"
"path/filepath"
"plugin"
)

// LoadService 加载 dir 下面的所有的实现了 T 接口的类型
// 举个例子来说,如果你有一个叫做 UserService 的接口
// 而后你将所有的实现都放到了 /ext/user_service 目录下
// 并且所有的实现,虽然在不同的包,但是都叫做 UserService
// 那么我可以执行 LoadService("/ext/user_service", "UserService")
// 加载到所有的实现
// LoadService 加载 dir 下面的所有的实现了 T 接口的类型

var DirNotFound = errors.New("目录不存在")

func LoadService[T any](dir string, symName string) ([]T, error) {
var services []T
// 检查目录是否存在
if _, err := os.Stat(dir); os.IsNotExist(err) {
return nil, DirNotFound
}
// 遍历目录下的所有 .so 文件
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() && filepath.Ext(path) == ".so" {
// 打开插件
p, err := plugin.Open(path)
if err != nil {
return err
}
// 查找变量
sym, err := p.Lookup(symName)
if err != nil {
return err
}

// 尝试将符号断言为接口类型
service, ok := sym.(T)
if !ok {
return errors.New("插件非该接口类型")
}
// 收集服务
services = append(services, service)
}
return nil
})
return services, err
}
69 changes: 69 additions & 0 deletions spi/spi_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright 2021 ecodeclub
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package spi

import (
"log"
"testing"

"github.com/stretchr/testify/assert"
)

func Test_LoadService(t *testing.T) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

添加 setupTest方法, 示例如下:

func setupTest(t *testing.T) {
	wd, err := os.Getwd()
	require.NoError(t, err)
	cmd := exec.Command("go", "generate", "./...")
	cmd.Dir = filepath.Join(wd, "testdata")
	output, err := cmd.CombinedOutput()
	require.NoError(t, err, fmt.Sprintf("执行 go generate 失败: %v\n%s", err, output))
}

cleanup操作,可选

testcases := []struct {
name string
dir string
svcName string
want []string
wantErr error
}{
{
name: "有一个插件",
dir: "./user_service",
svcName: "UserSvc",
want: []string{"Get"},
},
{
name: "有两个插件",
dir: "./user_service2",
svcName: "UserSvc",
want: []string{"A", "B"},
},
Copy link
Collaborator

@longyue0521 longyue0521 May 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

补充测试用例:

  1. svcName 为空
  2. svcName 非空但找不到

需要确认LoadService的语义:

dir下非空, ./testdata/user_service3下有 c和d, svcName 也非空, 就是没有与之匹配的,是报错还是返回nil, nil ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

我直接把,plugin原生的报错吐出去了

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

可以自定义一个err说明情况, 然后wrap plugin的err

{
name: "目录不存在",
dir: "./notfound",
wantErr: DirNotFound,
},
}
for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
list, err := LoadService[UserService](tc.dir, tc.svcName)
assert.Equal(t, tc.wantErr, err)
if err != nil {
return
}
ans := make([]string, 0, len(list))
for _, svc := range list {
ans = append(ans, svc.Get())
}
log.Println(ans)
assert.Equal(t, tc.want, ans)
})
}
}

type UserService interface {
Get() string
}
25 changes: 25 additions & 0 deletions spi/user_service/a.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Copyright 2021 ecodeclub
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. 既然user_service目录和user_service2目录只在测试中使用, 将其移动到/spi/testdata中, 研究一下go中testdata的用法.
  2. 选择使用go plugin方法实现,需要添加readme,或者Example来一步一步指导用户如何使用

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. 按照 testdata 的用法修改
  2. 写一个简单的 Example 就可以

//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main

// 测试用
//go:generate go build --buildmode=plugin -o a.so ./a.go

type UserService struct{}

func (u UserService) Get() string {
return "Get"
}

var UserSvc UserService
27 changes: 27 additions & 0 deletions spi/user_service2/a/a.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright 2021 ecodeclub
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

// 测试用

type UserService struct{}

// GetName returns the name of the service
func (u UserService) Get() string {
return "A"
}

// 导出对象
var UserSvc UserService
27 changes: 27 additions & 0 deletions spi/user_service2/b/b.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright 2021 ecodeclub
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

// 测试用

type UserService struct{}

// GetName returns the name of the service
func (u UserService) Get() string {
return "B"
}

// 导出对象
var UserSvc UserService
Loading