picgo/handler/static.go

26 lines
557 B
Go
Raw Normal View History

2024-07-11 21:25:58 +08:00
package handler
import (
"net/http"
"os"
"path/filepath"
"picgo/configs"
2024-07-11 21:25:58 +08:00
)
func StaticHandler() http.Handler {
2024-07-11 21:25:58 +08:00
// 文件服务器的根目录
root := configs.Settings.Server.StaticPath
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 获取文件路径
path := filepath.Join(root, r.URL.Path)
// 检查路径是否为目录
info, err := os.Stat(path)
if err == nil && info.IsDir() {
http.NotFound(w, r) // 如果是目录则返回404
return
}
// 否则提供文件
http.ServeFile(w, r, path)
})
2024-07-11 21:25:58 +08:00
}