dongshi6969 2018-03-09 17:07
浏览 48
已采纳

Golang处理静态文件夹

I'm not able to get files placed in static folder. I'm using gorilla mux package.

main.go code:

fs := http.FileServer(http.Dir("static"))
mainRouter.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
http.Handle("/", &mainRouter)

Project structure:

static
templates
--style
--javascript
--...
main.go

When I hit index page:

loclalhost:8080/cruise_schedule

I get all stylesheets and js files, but when I jump to another page:

localhost:8080/cruise_schedule/selected_cruise/e58ed042aad24b9b87fba8917c085534

I get following errors:

Refused to apply style from 'http://localhost:8080/cruise_schedule/static/style/style.css' because its MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

and:

http://localhost:8080/cruise_schedule/static/javascript/resources.js 

What should I do in order to properly serve static files?

  • 写回答

1条回答 默认 最新

  • dsnnvpobaljihv3490 2018-03-09 17:14
    关注

    Your Go application is not at fault here, your generated HTML output is.

    Your error message says that your sub-page tries to load its CSS from http://localhost:8080/cruise_schedule/static/..., when it actually should load from http://localhost:8080/static/.... The first URL will not serve the static file since it's not below the /static prefix, and your application will probably serve its default 404 page (presumably a text/plain page).

    To solve this, I'd suggest either using absolute paths for your CSS (<link href="/static/...) or using an appropriate <base> tag.

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

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line