2024-07-11 21:25:58 +08:00
|
|
|
|
package handler
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"net/http"
|
|
|
|
|
"os"
|
|
|
|
|
"path/filepath"
|
2024-07-13 20:33:20 +08:00
|
|
|
|
"picgo/configs"
|
2024-07-11 21:25:58 +08:00
|
|
|
|
)
|
|
|
|
|
|
2024-07-13 20:33:20 +08:00
|
|
|
|
func StaticHandler() http.Handler {
|
2024-07-11 21:25:58 +08:00
|
|
|
|
// 文件服务器的根目录
|
2024-07-13 20:33:20 +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
|
|
|
|
}
|