Go Web端点无法找到静态index.html文件的问题排查
问题解决:Go静态文件服务404找不到static文件夹
你的问题出在相对路径的基准目录上:
- 当你在
microservices目录下执行go run ./frontend/cmd/web时,程序的工作目录是microservices,而非main.go所在的frontend/cmd/web目录。 - 代码里的
./static会指向microservices/static,但你的static文件夹实际在microservices/frontend/cmd/web/static,自然找不到对应文件,返回404。
三种解决方法
方法一:修改代码中的路径为完整相对路径
直接把静态目录路径改成从工作目录(microservices)出发的完整相对路径:
fileServer := http.FileServer(http.Dir("./frontend/cmd/web/static"))
方法二:切换到main.go所在目录再运行命令
先进入frontend/cmd/web目录,再执行启动命令:
cd frontend/cmd/web go run main.go
这时候./static就会指向正确的frontend/cmd/web/static目录。
方法三:动态获取文件所在目录(推荐,适配任意启动位置)
用Go的runtime.Caller获取当前代码文件的路径,再拼接static目录,这样不管从哪个目录启动都能找到静态文件:
package main import ( "fmt" "log" "net/http" "path/filepath" "runtime" ) const customPort = "3001" func main() { // 获取当前main.go文件的路径 _, filename, _, ok := runtime.Caller(0) if !ok { log.Panic("无法获取当前文件路径") } // 拿到文件所在目录 currentDir := filepath.Dir(filename) // 拼接static目录的绝对路径 staticDir := filepath.Join(currentDir, "static") fileServer := http.FileServer(http.Dir(staticDir)) port := fmt.Sprintf(":%s", customPort) http.Handle("/", fileServer) fmt.Printf("Starting front end service on port %s\n", port) err := http.ListenAndServe(port, nil) if err != nil { log.Panic(err) } }
内容的提问来源于stack exchange,提问作者yen
相关产品推荐
相关产品推荐

