使用Go语言在同一个服务器上提供HTTP请求和文件服务

huangapple go评论84阅读模式
英文:

Serving HTTP Requests and Files using same server in Go Lang

问题

你好,我正在尝试使用Go语言创建一个同时提供文件和HTTP请求的服务器。

我希望"/upload"路径接受POST请求,
"/files"路径在"fpath"中提供静态文件。

我尝试了以下代码,但是出现了404错误:

func main() {
    fpath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
    fpath+="/public"
    fmt.Println(fpath)
    http.HandleFunc("/upload",uploadFunc)
    http.HandleFunc("/files",http.FileServer(http.Dir(fpath)))
    panic(http.ListenAndServe(":8080", nil))
}

请帮我翻译以上内容。

英文:

Hi I am trying to create a server in Go Lang which serves files and HTTP Requests at the same time.

I want <code>/upload</code> path to accept post requests and
<code>/files</code> path to serve static files in the <code>fpath</code>

I tried with the following code but i get a 404 error

func main() {
	fpath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	fpath+=&quot;/public&quot;
	fmt.Println(fpath)
	http.HandleFunc(&quot;/upload&quot;,uploadFunc)
	http.HandleFunc(&quot;/files&quot;,http.FileServer(http.Dir(fpath)))
	panic(http.ListenAndServe(&quot;:8080&quot;, nil))
}

答案1

得分: 3

你需要在处理路径上添加尾部斜杠,如果它是一个目录的话。更多信息请参考http://golang.org/pkg/net/http/#ServeMux。

模式名称固定,根路径,如"/favicon.ico",或者根子树,如"/images/"(注意尾部斜杠)。

尝试一下:

func main() {
    fpath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
    fpath += "/public"
    fmt.Println(fpath)
    http.HandleFunc("/upload", uploadFunc)
    http.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir(fpath))))
    panic(http.ListenAndServe(":8080", nil))
}
英文:

You need trailing slashes on your handle path if it's a directory. See http://golang.org/pkg/net/http/#ServeMux for more info.

>Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash).

Try

func main() {
    fpath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
    fpath+=&quot;/public&quot;
    fmt.Println(fpath)
    http.HandleFunc(&quot;/upload&quot;,uploadFunc)
    http.Handle(&quot;/files/&quot;, http.StripPrefix(&quot;/files/&quot;, http.FileServer(http.Dir(fpath))))
    panic(http.ListenAndServe(&quot;:8080&quot;, nil))
}

huangapple
  • 本文由 发表于 2014年8月20日 13:06:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/25397054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定