Files
goproxy/examples/plugin/plugins/storage/storage_plugin.go
DarkiT 098c721ee9 增强插件系统:添加插件类型支持
- 在插件接口和基本插件结构中引入插件类型(PluginType),并定义了多种预定义的插件类型。
- 更新插件管理器以支持按类型管理插件,新增按类型获取、初始化和启动插件的方法。
- 修改现有插件(如日志插件和统计插件)以实现插件类型接口,确保兼容性。
- 优化插件信息输出,包含插件类型信息。

此更新提升了插件系统的灵活性和可扩展性,便于未来添加更多插件类型。
2025-03-14 11:07:53 +08:00

139 lines
3.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"context"
"fmt"
"os"
"path/filepath"
"sync"
"github.com/darkit/goproxy/examples/plugin"
)
// StoragePlugin 存储插件
// 提供简单的文件存储功能
type StoragePlugin struct {
*plugin.BasePlugin // 嵌入基本插件结构
storageDir string // 存储目录
config map[string]interface{} // 配置
mu sync.RWMutex // 读写锁
}
// Plugin 导出的插件变量
// 注意变量名必须是Plugin大小写敏感
var Plugin = &StoragePlugin{
BasePlugin: plugin.NewBasePlugin(
"StoragePlugin",
"1.0.0",
"简单的文件存储插件",
"开发者",
plugin.PluginTypeStorage, // 设置插件类型为存储插件
),
}
// Init 初始化插件
func (p *StoragePlugin) Init(ctx context.Context, config map[string]interface{}) error {
p.config = config
// 获取存储目录路径
storageDir, ok := config["storage_dir"].(string)
if !ok {
// 使用默认路径
storageDir = "storage"
}
// 确保存储目录存在
if err := os.MkdirAll(storageDir, 0o755); err != nil {
return fmt.Errorf("创建存储目录失败: %v", err)
}
p.storageDir = storageDir
fmt.Println("存储插件初始化完成,存储目录:", storageDir)
return nil
}
// Start 启动插件
func (p *StoragePlugin) Start(ctx context.Context) error {
if p.storageDir == "" {
return fmt.Errorf("插件未初始化")
}
fmt.Println("存储插件已启动")
return nil
}
// Stop 停止插件
func (p *StoragePlugin) Stop(ctx context.Context) error {
fmt.Println("存储插件已停止")
return nil
}
// SaveFile 保存文件
func (p *StoragePlugin) SaveFile(filename string, data []byte) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.storageDir == "" {
return fmt.Errorf("插件未初始化")
}
filePath := filepath.Join(p.storageDir, filename)
return os.WriteFile(filePath, data, 0o644)
}
// LoadFile 加载文件
func (p *StoragePlugin) LoadFile(filename string) ([]byte, error) {
p.mu.RLock()
defer p.mu.RUnlock()
if p.storageDir == "" {
return nil, fmt.Errorf("插件未初始化")
}
filePath := filepath.Join(p.storageDir, filename)
return os.ReadFile(filePath)
}
// DeleteFile 删除文件
func (p *StoragePlugin) DeleteFile(filename string) error {
p.mu.Lock()
defer p.mu.Unlock()
if p.storageDir == "" {
return fmt.Errorf("插件未初始化")
}
filePath := filepath.Join(p.storageDir, filename)
return os.Remove(filePath)
}
// ListFiles 列出所有文件
func (p *StoragePlugin) ListFiles() ([]string, error) {
p.mu.RLock()
defer p.mu.RUnlock()
if p.storageDir == "" {
return nil, fmt.Errorf("插件未初始化")
}
var files []string
entries, err := os.ReadDir(p.storageDir)
if err != nil {
return nil, err
}
for _, entry := range entries {
if !entry.IsDir() {
files = append(files, entry.Name())
}
}
return files, nil
}
// main 函数是必须的,但不会被调用
func main() {
// 不会被执行,仅用于编译插件
}