package staticServer
import (
"fmt"
"net/http"
"os"
"time"
)
const staticPath = "./web" // 静态web目录
func Start() {
serveMux := http.NewServeMux()
serveMux.HandleFunc("/", StaticServer)
server := http.Server{
Addr: ":8080",
Handler: serveMux,
ReadTimeout: 10 * time.Second,
}
err := server.ListenAndServe()
if err != nil {
fmt.Println(err)
}
}
func StaticServer(w http.ResponseWriter, r *http.Request) {
if isFile(staticPath + r.URL.Path) {
http.StripPrefix("/", http.FileServer(http.Dir(staticPath))).ServeHTTP(w, r)
} else {
http.StripPrefix(r.URL.Path, http.FileServer(http.Dir(staticPath))).ServeHTTP(w, r)
}
}
// 是否是文件 不是文件也不一定是目录
func isFile(path string) bool {
s, err := os.Stat(path)
if err != nil {
return false
}
return !s.IsDir()
}
有疑问加站长微信联系(非本文作者)