英文:
How to hide static files while serving in go?
问题
我正在开发一个Web应用程序,目前遇到了提供静态CSS和JS文件的问题。在这些文件中,我使用以下方式引用:
<script type="text/javascript" src="/tmpfiles/js/app2.js"></script>
在服务器端,我有类似这样的代码:
router.PathPrefix("/tmpfiles/").Handler(http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("."))))
任何具备基本目录导航知识的人都可以看到源代码。我该如何隐藏这些文件并确保我的应用程序安全?
英文:
I'm working on a web app and came to the point where I serve the static css and JS files. In these files I refer like this:
<script type="text/javascript" src="/tmpfiles/js/app2.js"></script>
On the server side I have something like this:
router.PathPrefix("/tmpfiles/").Handler(http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("."))))
Anybody who has basic knowledge of navigating through directories can see the source code. How do I hide these files and make my application secure?
答案1
得分: 2
当你这样做时:
http.FileServer(http.Dir("."))
你告诉它从当前目录(你的所有源代码所在的目录)中提供文件。
我通常会创建一个名为/public
的文件夹,将所有静态的、可通过网络访问的文件放在其中。然后你可以这样做:
router.PathPrefix("/tmpfiles/").Handler(
http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("./public"))))
这将从URL中移除/tmpfiles/
,然后从public
目录中提供该文件。
英文:
When you do this:
http.FileServer(http.Dir("."))
You are telling it to serve files from the current directory (where all your source code lives).
What I typically do is have a folder /public
, where any static, web accessible files will live. Then you can do:
router.PathPrefix("/tmpfiles/").Handler(
http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("./public"))))
Which will remove the /tmpfiles/
from the url, and then serve that file from the public
directory.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论