dpwo36915 2019-02-09 15:43
浏览 39
已采纳

在具有非常规目录结构的同一页面上提供HTML模板和CSS?

I have been trying to figure out how to serve css and html on the same page a few times now but I always just end up getting frustrated and using bootstrap. I really want to have my next project to have my own hand written css though. My source tree looks like this.

 - cmd
     - main.go 
 - static
     - css
     - templates

The reason my source tree looks like this because I want to have two packages in cmd: one for providing mock data the other for running the actual application. I have seen other posts where a http.FileServer is used however the project structure is much different with the main.go file at the root of the directory. I try to do a path something like:

fs := http.FileServer(http.Dir("../static/css"))
http.Handle("/signup/", http.StripPrefix("/static/css", fs))
  • 写回答

1条回答 默认 最新

  • duancaoqin6683 2019-02-09 17:43
    关注

    As mentioned in the comment above the directory you place your files in will be relative to the compiled binary.

    go run main.go will compile in your current directory and then run the executable, therefore any paths in your application will be from the place your application was compiled not the overall project structure. I'll try and show an example below:

    // Current working directory
    /your-github-username/project-folder
    
    // Folder with entry point (main.go)
    /your-github-username/project-folder/cmd
    
    // Folder with static files (css file)
    /your-github-username/project-folder/static
    

    If you run go run ./cmd/main.go in your /your-github-username/project folder, then the way you have it written in your question your application will try to load static files from /your-github-username/static. I.e one folder up from where you ran the go run command from.

    But if you build and deploy your application, the /static folder will need to be re-created relative to wherever you put your compiled binary.

    Something nice to do in your main.go is to have some sort of initialisation function which checks for required folders, creates them and then outputs instructions if they are empty etc still need things put in them as part of your deployment process.

    If you want a really nice example of static file hosting I'd recommend looking at the go-chi router library examples as there are some great ones including a static file hosting one:

    go-chi static file example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档