英文:
404 when trying to serve files from the filesystem
问题
你的代码似乎没有问题。但是,当你访问localhost:8080/时出现404错误,可能是因为你的静态文件目录中没有名为"static"的文件夹。请确保你的代码中的文件路径是正确的,并且在该路径下存在一个名为"static"的文件夹,其中包含你要提供的静态文件。
英文:
import (
	"net/http"
)
func main() {
	http.Handle("/", http.FileServer(http.Dir("static")))
	http.ListenAndServe(":8080", nil)
}
I navigate to localhost:8080/ and get a 404 error. What am i doing wrong?
答案1
得分: 2
试试这个:
import (
    "net/http"
    "os"
)
func main() {
    server.RegisterHandlers()
    // 获取运行目录。
    runningDirectory, err := os.Getwd()
    if err != nil {
        // 处理错误。
        return err
    }
    http.Handle("/", http.FileServer(http.Dir(runningDirectory+"/static")))
    http.ListenAndServe(":8080", nil)
}
希望对你有帮助!
英文:
Try this:
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)
}
答案2
得分: 0
使用以下结构:
main.go
static
  |- index.html
并且main.go包含以下内容:
package main
import (
	"net/http"
)
func main() {
	http.Handle("/", http.FileServer(http.Dir("static")))
	if err := http.ListenAndServe(":8080", nil); err != nil {
		panic(err)
	}
}
在使用go run main.go运行您的解决方案后,您应该能够访问localhost:8080/并获得index.html的内容。
如果不起作用,也许添加的错误处理可能会有所帮助。代码是正确的。
英文:
With the following structure:
main.go
static
  |- index.html
And with main.go containing:
package main
import (
	"net/http"
)
func main() {
	http.Handle("/", http.FileServer(http.Dir("static")))
	if err := http.ListenAndServe(":8080", nil); err != nil {
		panic(err)
	}
}
After running your solution with go run main.go, you should be able to go to localhost:8080/ and end up with the content of index.html.
If it doesn't work, maybe the added error handling might help out. The code is correct.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论