Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Http 为什么我的文件服务器处理程序没有';不行?_Http_Go_Fileserver - Fatal编程技术网

Http 为什么我的文件服务器处理程序没有';不行?

Http 为什么我的文件服务器处理程序没有';不行?,http,go,fileserver,Http,Go,Fileserver,我有一个简单的文件夹: Test/ main.go Images/ image1.png image2.png index.html 在main.go中,我刚刚放了: package main import ( "net/http" ) func main(){ fs := http.FileServer(http.Dir("./Images")) http.Handle("/Im

我有一个简单的文件夹:

Test/
    main.go
    Images/
          image1.png
          image2.png
          index.html
在main.go中,我刚刚放了:

package main

import (
       "net/http"
)

func main(){
     fs := http.FileServer(http.Dir("./Images"))
     http.Handle("/Images/*", fs)
     http.ListenAndServe(":3003", nil)
}
但当我卷曲或者甚至添加到路径文件的名称时,它就不起作用了。 我不明白,因为这与上一页的答复是一样的


你能告诉我这不起作用吗?

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

您需要删除
*
,并添加额外的子文件夹
图像

这很好:

Test/
    main.go
    Images/
          Images/
                image1.png
                image2.png
                index.html
代码:

然后
go运行main.go

以及:


或者简单地使用:

package main

import (
    "net/http"
)

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

请求未能返回您期望的内容的原因是它们与http.Handle(模式字符串,处理程序)调用中定义的模式不匹配。文档描述了如何组合模式。任何请求的前缀都是从最特定到最不特定的匹配。似乎您已经假设可以使用glob模式。您的处理程序将被调用,请求
/Images/*
。您需要像这样定义一个目录路径,
Images/

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

package main

import (
    "net/http"
)

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