duan117890 2017-06-02 22: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 04: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 DevEco studio开发工具 真机联调找不到手机设备
  • ¥15 请教前后端分离的问题
  • ¥100 冷钱包突然失效,急寻解决方案
  • ¥15 下载honeyd时报错 configure: error: you need to instal a more recent version of libdnet
  • ¥15 距离软磁铁一定距离的磁感应强度大小怎么求
  • ¥15 霍尔传感器hmc5883l的xyz轴输出和该点的磁感应强度大小的关系是什么
  • ¥15 vscode开发micropython,import模块出现异常
  • ¥20 Excel数据自动录入表单并提交
  • ¥30 silcavo仿真,30分钟,只需要代码
  • ¥15 FastReport 怎么实现打印后马上关闭打印预览窗口