且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何在 Go 中提供 CSS 和 JS

更新时间:2022-12-05 10:08:33

http.Handle("/", http.FileServer(http.Dir("css/")))

将在 / 提供您的 css 目录.当然,您可以在您选择的任何路径下为任何目录提供服务.

Would serve your css directory at /. Of course you can serve whichever directory at whatever path you choose.

您可能想确保静态路径不会妨碍其他路径并使用类似的方法.

You probably want to make sure that the static path isn't in the way of other paths and use something like this.

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

jscss 放在项目的 static 目录中.这将在 domain.com/static/css/filename.cssdomain.com/static/js/filename.js

Placing both your js and css in the directory static in your project. This would then serve them at domain.com/static/css/filename.css and domain.com/static/js/filename.js

StripPrefix 方法删除前缀,因此它不会尝试搜索,例如在 static/css/filename.cssstatic 目录中,当然,它不会找到.它将在 static 目录中查找 css/filename.css,这是正确的.

The StripPrefix method removes the prefix, so it doesn't try to search e.g. in the static directory for static/css/filename.css which, of course, it wouldn't find. It would look for css/filename.css in the static directory, which would be correct.