duan117890 2017-06-03 06:50
浏览 268
已采纳

在Go中提供静态文件时是否需要http.StripPrefix?

What's wrong with http.Handle("/static/", http.FileServer(http.Dir("")))?

The shortest example I can find looks like this:

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

Is http.StripPrefix necessary?

  • 写回答

1条回答 默认 最新

  • dongpu3347 2017-06-03 12:41
    关注

    No it is not required, but if you DO NOT use it the path used to find the file will include the prefix. This is clearer with an example, so imagine your folder structure was:

    main.go
    static/
      styles.css
    

    And you serve the files with:

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

    Then a user requesting the file at yoursite.com/static/styles.css would get the styles.css file in the static dir. But for this to work your paths must line up perfectly.

    Most people prefer to do the following instead:

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

    Because they could change their URL path to be something like /assets/ without needing to rename the static dir (or vise versa - change the local dir structure w/out updating the URL path).

    TL;DR - Path prefix isn't required but is useful to break any requirements of URL paths and local directory structure matching perfectly.

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

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试