尝试从文件系统提供文件时出现404错误。

huangapple go评论111阅读模式
英文:

404 when trying to serve files from the filesystem

问题

你的代码似乎没有问题。但是,当你访问localhost:8080/时出现404错误,可能是因为你的静态文件目录中没有名为"static"的文件夹。请确保你的代码中的文件路径是正确的,并且在该路径下存在一个名为"static"的文件夹,其中包含你要提供的静态文件。

英文:
  1. import (
  2. "net/http"
  3. )
  4. func main() {
  5. http.Handle("/", http.FileServer(http.Dir("static")))
  6. http.ListenAndServe(":8080", nil)
  7. }

I navigate to localhost:8080/ and get a 404 error. What am i doing wrong?

答案1

得分: 2

试试这个:

  1. import (
  2. "net/http"
  3. "os"
  4. )
  5. func main() {
  6. server.RegisterHandlers()
  7. // 获取运行目录。
  8. runningDirectory, err := os.Getwd()
  9. if err != nil {
  10. // 处理错误。
  11. return err
  12. }
  13. http.Handle("/", http.FileServer(http.Dir(runningDirectory+"/static")))
  14. http.ListenAndServe(":8080", nil)
  15. }

希望对你有帮助!

英文:

Try this:

  1. import (
  2. "net/http"
  3. "os"
  4. )
  5. func main() {
  6. server.RegisterHandlers()
  7. // Get the running directory.
  8. runningDirectory, err := os.Getwd()
  9. if err != nil {
  10. // Handle the error.
  11. return err
  12. }
  13. http.Handle("/", http.FileServer(http.Dir(runningDirectory + "/static"))
  14. http.ListenAndServe(":8080", nil)
  15. }

答案2

得分: 0

使用以下结构:

  1. main.go
  2. static
  3. |- index.html

并且main.go包含以下内容:

  1. package main
  2. import (
  3. "net/http"
  4. )
  5. func main() {
  6. http.Handle("/", http.FileServer(http.Dir("static")))
  7. if err := http.ListenAndServe(":8080", nil); err != nil {
  8. panic(err)
  9. }
  10. }

在使用go run main.go运行您的解决方案后,您应该能够访问localhost:8080/并获得index.html的内容。

如果不起作用,也许添加的错误处理可能会有所帮助。代码是正确的。

英文:

With the following structure:

  1. main.go
  2. static
  3. |- index.html

And with main.go containing:

  1. package main
  2. import (
  3. "net/http"
  4. )
  5. func main() {
  6. http.Handle("/", http.FileServer(http.Dir("static")))
  7. if err := http.ListenAndServe(":8080", nil); err != nil {
  8. panic(err)
  9. }
  10. }

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.

huangapple
  • 本文由 发表于 2014年1月15日 18:08:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/21134464.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定