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()
}
以上所述就是小编给大家介绍的《前后端分离的Golang静态web服务器》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。