62 lines
1.5 KiB
Go
62 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
func main() {
|
|
// 硬编码目录配置
|
|
dirs := map[string]string{
|
|
"/bbs": "/files/bbs/www/bbs", // 修改右侧路径
|
|
"/active": "/files/active/www/active", // 添加新条目
|
|
}
|
|
|
|
port := 8080 // 固定端口
|
|
mux := http.NewServeMux()
|
|
|
|
// 注册所有目录路由
|
|
for prefix, path := range dirs {
|
|
absPath, err := filepath.Abs(path)
|
|
if err != nil {
|
|
log.Fatalf("目录[%s]解析失败: %v", path, err)
|
|
}
|
|
|
|
if err := os.MkdirAll(absPath, 0755); err != nil {
|
|
log.Fatalf("创建目录[%s]失败: %v", absPath, err)
|
|
}
|
|
|
|
fileServer := secureFileServer(http.Dir(absPath))
|
|
mux.Handle(prefix+"/", http.StripPrefix(prefix, fileServer))
|
|
log.Printf("已挂载目录: %s => %s", prefix, absPath)
|
|
}
|
|
|
|
// 启动服务器
|
|
serverAddr := fmt.Sprintf(":%d", port)
|
|
log.Printf("文件服务器启动在 http://localhost%s", serverAddr)
|
|
|
|
if err := http.ListenAndServe(serverAddr, mux); err != nil {
|
|
log.Fatalf("服务器启动失败: %v", err)
|
|
}
|
|
}
|
|
|
|
// 安全检查中间件
|
|
func secureFileServer(root http.FileSystem) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if strings.Contains(r.URL.Path, "..") {
|
|
http.Error(w, "无效的路径", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
w.Header().Set("X-Frame-Options", "DENY")
|
|
w.Header().Set("X-XSS-Protection", "1; mode=block")
|
|
|
|
http.FileServer(root).ServeHTTP(w, r)
|
|
})
|
|
} |