picgo/handler/static.go

26 lines
557 B
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 handler
import (
"net/http"
"os"
"path/filepath"
"picgo/configs"
)
func StaticHandler() http.Handler {
// 文件服务器的根目录
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)
})
}