picgo/handler/static.go

35 lines
663 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"
)
func StaticHandler(w http.ResponseWriter, r *http.Request) {
// 文件服务器的根目录
root := "./static"
// 自定义文件处理器
fileHandler := http.StripPrefix("/static/", http.FileServer(http.Dir(root)))
// 获取请求的路径
path := filepath.Join(root, r.URL.Path[len("/static/"):])
// 检查路径是否是一个目录
info, err := os.Stat(path)
if err != nil {
// 如果文件不存在返回404
http.NotFound(w, r)
return
}
if info.IsDir() {
// 如果是目录返回404
http.NotFound(w, r)
return
}
// 处理文件
fileHandler.ServeHTTP(w, r)
}