Go 404尝试从文件系统提供文件时
我导航到localhost:8080/并得到一个404错误。我做错了什么?试试这个:Go 404尝试从文件系统提供文件时,go,Go,我导航到localhost:8080/并得到一个404错误。我做错了什么?试试这个: import ( "net/http" ) func main() { http.Handle("/", http.FileServer(http.Dir("static"))) http.ListenAndServe(":8080", nil) } 结构如下: import ( "net/http" "os" ) func main() { server.
import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir("static")))
http.ListenAndServe(":8080", nil)
}
结构如下:
import (
"net/http"
"os"
)
func main() {
server.RegisterHandlers()
// Get the running directory.
runningDirectory, err := os.Getwd()
if err != nil {
// Handle the error.
return err
}
http.Handle("/", http.FileServer(http.Dir(runningDirectory + "/static"))
http.ListenAndServe(":8080", nil)
}
并带有main.go
包含:
main.go
static
|- index.html
使用go run main.go
运行解决方案后,您应该能够转到localhost:8080/
,并以index.html
的内容结束
如果它不起作用,那么添加的错误处理可能会有所帮助。代码是正确的。您对静态文件夹中的GET/?My Index.html有什么期望
server.registerhandles()
做什么?如果您有一个名为“static”的文件夹,没有它代码应该可以正常工作。抱歉,删除了该行。还是不起作用。真高兴它起作用了!你知道为什么一个完整的路径可能需要,而通常情况下,亲属应该是足够的?
package main
import (
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.Dir("static")))
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}