http.FileServer正在发送”404页面未找到”。

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

http.FileServer is sending "404 page not found"

问题

我正在尝试通过http.FileServer来提供静态文件,但它从未返回我所请求的目录。以下是代码片段:

func main() {
    fmt.Println("Serving Files")
    http.HandleFunc("/", homeFunc)
    http.HandleFunc("/search", searchFunc)
    http.Handle("/tmp/",
        http.StripPrefix("/tmp/", http.FileServer(http.Dir("/assets"))))

    http.ListenAndServe(":8080", nil)
}

当访问mywebsite.com/tmp/时,会显示"404页面未找到"的文本。如果我漏掉了什么,请帮助我解决问题,谢谢!

编辑:这是文件结构:

主文件夹
|
|-/Assets
|--(assets)
|
|-main.go
英文:

I'm trying to serve static files via http.FileServer, however it never sends back the directory I'm asking for. The code is snipped below:

func main() {

fmt.Println("Serving Files")
http.HandleFunc("/", homeFunc)
http.HandleFunc("/search", searchFunc)
http.Handle("/tmp/",
	http.StripPrefix("/tmp/", http.FileServer(http.Dir("/assets"))))

http.ListenAndServe(":8080", nil)
}

When visiting mywebsite.com/tmp/, text appears saying "404 page not found." A little help in case I'm missing something would be greatly appreciated!

Edit: Here's the file architecture:

main folder
|
|-/Assets
|--(assets)
|
|-main.go

答案1

得分: 2

目录/assets存在吗?请注意,/assets是一个绝对路径,因此它必须位于文件系统的根目录下。如果你想要在执行程序的当前工作目录中找到某个文件,你应该使用./assets

英文:

Does the directory /assets exist? Note that /assets is an absolute path, so it must be at the root of your filesystem. If you want something in the working directory where you're executing your program, you should use ./assets.

答案2

得分: 1

如果您使用相对路径,您可以检查您的路径是什么。

import (
    "fmt"
    "os"
)

dir, _ := os.Getwd()
fmt.Println("当前路径:" + dir)
英文:

If you use relative path, you can check what your path is.

import (
"fmt"
"os"
)

dir, _ := os.Getwd()
fmt.Println("current path :" + dir)

huangapple
  • 本文由 发表于 2017年6月27日 22:18:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/44782680.html
匿名

发表评论

匿名网友

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

确定