54 lines
1.1 KiB
Go
54 lines
1.1 KiB
Go
package common
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
// Parser 文档解析器接口:从源文件抽取纯文本
|
|
type Parser interface {
|
|
// Parse 返回文档全文(保留标题/段落/空行结构,供分块器使用)
|
|
Parse(path string) (string, error)
|
|
}
|
|
|
|
var parsers = map[string]Parser{}
|
|
|
|
func init() {
|
|
registerParser("txt", &textParser{})
|
|
registerParser("md", &textParser{})
|
|
registerParser("pdf", &pdfParser{})
|
|
registerParser("docx", &docxParser{})
|
|
registerParser("html", &htmlParser{})
|
|
}
|
|
|
|
func registerParser(ext string, p Parser) {
|
|
parsers[ext] = p
|
|
}
|
|
|
|
// SupportedExts 返回支持的扩展名列表(不含点)
|
|
func SupportedExts() []string {
|
|
exts := make([]string, 0, len(parsers))
|
|
for ext := range parsers {
|
|
exts = append(exts, ext)
|
|
}
|
|
return exts
|
|
}
|
|
|
|
// ParseFile 按扩展名分发解析,返回全文
|
|
func ParseFile(path string) (string, error) {
|
|
ext := strings.TrimPrefix(extOf(path), ".")
|
|
p, ok := parsers[ext]
|
|
if !ok {
|
|
return "", fmt.Errorf("不支持的文档类型: .%s", ext)
|
|
}
|
|
return p.Parse(path)
|
|
}
|
|
|
|
func extOf(path string) string {
|
|
idx := strings.LastIndexByte(path, '.')
|
|
if idx < 0 {
|
|
return ""
|
|
}
|
|
return path[idx:]
|
|
}
|