Serving Subdirectories in HTTP handlers [GoLang]

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

Serving Subdirectories in HTTP handlers [GoLang]

问题

我有以下代码:

r := mux.NewRouter()
r.Handle("/", http.FileServer(http.Dir("./frontend/build/")))
r.Handle("/static", http.FileServer(http.Dir("./frontend/build/static/")))
r.PathPrefix("/api").Handler(auth)

/api 应该是安全的。如果用户访问 /,我希望他们能够查看 PROJECTDIR/frontend 目录中的 index.html

前端目录结构如下:

frontend
    /build
        index.html
        /static
            /js
            /css
            /media

index.html/static 加载所有内容。无论我如何配置,当我访问 localhost:3000 时,我可以获取到 index.html,但是 /static 下的所有内容都是 404。

我配置有什么问题吗?

英文:

I have the following code:

r := mux.NewRouter()
r.Handle("/", http.FileServer(http.Dir("./frontend/build/")))
r.Handle("/static", http.FileServer(http.Dir("./frontend/build/static/")))
r.PathPrefix("/api").Handler(auth)

/api is supposed to be secure. If a user hits /, I want them to view the index.html in the PROJECTDIR/frontend directory.

The frontend directory looks like

frontend
    /build
        index.html
        /static
            /js
            /css
            /media

The index.html loads all contents from /static. No matter how I seem to configure this, when I visit localhost:3000, I can get the index.html but everything under /static is 404'd.

How am I configuring this incorrectly?

答案1

得分: 5

假设您想在端点/static上提供整个"static"目录的内容,并且您正在运行一个BSD/Linux机器,以下语法应该可以工作:

http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
英文:

Assuming you want to serve the whole content of the directory "static" on the endpoint /static and you are running a bsd/linux machine the following syntax should work:

http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))

huangapple
  • 本文由 发表于 2017年4月26日 10:32:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/43624016.html
匿名

发表评论

匿名网友

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

确定