【问题标题】:Why my fileServer handler doesn't work?为什么我的 fileServer 处理程序不起作用?
【发布时间】:2017-01-19 07:40:41
【问题描述】:

我有一个简单的文件夹:

Test/
    main.go
    Images/
          image1.png
          image2.png
          index.html

在 main main.go 我只是放了:

package main

import (
       "net/http"
)

func main(){
     fs := http.FileServer(http.Dir("./Images"))
     http.Handle("/Images/*", fs)
     http.ListenAndServe(":3003", nil)
}

但是当我在 http://localhost:3003/Images/ 上卷曲时,甚至我添加到路径文件的名称时,它都不起作用。 我不明白,因为它与给出的回复相同 this subject

你能告诉我这样这行不通吗?

【问题讨论】:

    标签: http go fileserver


    【解决方案1】:

    ./Images 中的点指的是 cwd 当前工作目录,而不是您的项目根目录。为了让您的服务器正常工作,您必须从 Test/ 目录运行它,或者使用绝对根路径寻址图像。

    【讨论】:

      【解决方案2】:

      您需要删除 * 并添加额外的子文件夹 Images:
      这工作正常:

      Test/
          main.go
          Images/
                Images/
                      image1.png
                      image2.png
                      index.html
      

      代码:

      package main
      
      import (
          "net/http"
      )
      
      func main() {
          fs := http.FileServer(http.Dir("./Images"))
          http.Handle("/Images/", fs)
          http.ListenAndServe(":3003", nil)
      }
      

      然后go run main.go

      还有:

      http://localhost:3003/Images/


      或者干脆使用:

      package main
      
      import (
          "net/http"
      )
      
      func main() {
          fs := http.FileServer(http.Dir("./Images"))
          http.Handle("/", fs)
          http.ListenAndServe(":3003", nil)
      }
      

      与: http://localhost:3003/

      【讨论】:

        【解决方案3】:

        请求未能返回您预期的原因是因为它们与http.Handle(pattern string, handler Handler) 调用中定义的模式不匹配。 ServeMux 文档提供了如何组合模式的描述。任何请求的前缀都是从最具体到最不具体的匹配。看起来好像您已经假设可以使用 glob 模式。您的处理程序将通过对/Images/*<file system path> 的请求被调用。你需要像这样定义一个目录路径,Images/

        另一方面,值得考虑的是您的程序如何获取目录路径来提供文件。硬编码相对意味着您的程序只能在文件系统中的特定位置内运行,这非常脆弱。您可以使用命令行参数来允许用户指定路径或使用在运行时解析的配置文件。这些考虑因素使您的程序易于模块化和测试。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-06-24
          • 1970-01-01
          • 1970-01-01
          • 2020-07-02
          • 2015-09-22
          • 1970-01-01
          • 1970-01-01
          • 2016-03-16
          相关资源
          最近更新 更多