How to hide static files while serving in go?

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

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:

&lt;script type=&quot;text/javascript&quot; src=&quot;/tmpfiles/js/app2.js&quot;&gt;&lt;/script&gt;

On the server side I have something like this:

router.PathPrefix(&quot;/tmpfiles/&quot;).Handler(http.StripPrefix(&quot;/tmpfiles/&quot;, http.FileServer(http.Dir(&quot;.&quot;))))

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(&quot;.&quot;))

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(&quot;/tmpfiles/&quot;).Handler(
    http.StripPrefix(&quot;/tmpfiles/&quot;, http.FileServer(http.Dir(&quot;./public&quot;))))

Which will remove the /tmpfiles/ from the url, and then serve that file from the public directory.

huangapple
  • 本文由 发表于 2017年6月23日 05:50:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/44709898.html
匿名

发表评论

匿名网友

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

确定