英文:
Golang serve static files in different directory
问题
我有一个用于Go Web服务器的库,其中包含JS文件,因此这应该是用户应用程序的目录树。myapp
是用户的应用程序,mylib
是通过go get
获取的库。
src
`-- github.com
|-- mylib
| |-- myJSlib
| `-- myGOlib
`-- myapp
|-- main.go
`-- static
|-- index.html
|-- js
`-- css
用户应用程序的Web服务器将通过以下方式提供static
子目录中的静态HTML:
http.Handle("/", http.FileServer(http.Dir("static")))
我的问题是,我无法将库的脚本包含在index.html
中,因为http.FileServer
在static
目录中提供服务。天真的解决方案是将http.FileServer
的根目录移动到src
中。但这不是我想要的解决方案,因为从src
中包含脚本时太冗长。另一个解决方案是告诉用户将js文件移动到static
目录中,如果用户处于生产模式并且我有我的jslib的缩小版本,那么这样做是可以的,但在需要有结构化树形文件夹的开发模式下,这个解决方案就行不通了。也许我可以为myGOlib和myJSlib分别创建存储库,用户可以使用go get
获取myGOlib,并将myJSlib克隆到static目录中。但我希望用户只需简单地使用go get
,一切都可以正常工作,而无需再次进行结构化处理。
任何解决方案都将不胜感激。谢谢!
英文:
I have a library for go webserver and contain js file as well, so this is supposed to be the directory trees of users app. myapp
is users app and mylib
is library that fetched through go get
.
src
`-- github.com
|-- mylib
| |-- myJSlib
| `-- myGOlib
`-- myapp
|-- main.go
`-- static
|-- index.html
|-- js
`-- css
The web server of user app will serve static html in static
subdirectory via
http.Handle("/", http.FileServer(http.Dir("static"))
My problem is i can't include the script of library into index.html
because the http.FileServer
serve in directory static
. Naive solution is i move the root of http.FileServer
into src
. But this is not the solution i want because it's to verbose when include the script from src
. The other solution is i tell the user move the js file into static
directory, this is fine if user in production mode and i have minified version of my jslib but in development mode that require structured tree folder this is just can't solve it. Maybe i can separate repo for myGOlib and myJSlib and user can use go get
to fetch the myGOlib and clone the myJSlib into static directory. But i want user just simply use go get
and everything works both lib without structurize things again.
Any solution would be appreciate. thanks
答案1
得分: 4
你可以为JavaScript添加第二个处理程序,用于从不同的文件夹提供服务(甚至可以是可配置的):
thirdPartyDir := "<configuration driven dir name>"
http.Handle("/", http.FileServer(http.Dir("static")))
http.Handle("/thirdparty", http.FileServer(http.Dir(thirdPartyDir)))
然后在你的 index.js
中,你可以包含第三方代码:
<script src='/thirdparty/foo.js'></script>
英文:
You could add a second handler for javascript that serves from a different folder (which could even be configurable):
thirdPartyDir := "<configuration driven dir name>"
http.Handle("/", http.FileServer(http.Dir("static"))
http.Handle("/thirdparty", http.FileServer(http.Dir(thirdPartyDir))
And then in your index.js
you could include 3rd party code like:
<script src='/thirdparty/foo.js'/>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论