Go web服务器在哪里查找文件?

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

Where does Go web server look for the files

问题

我有一个简单的网页应用程序,代码文件名为HttpServer.go:

package main

import (
	"net/http"
)

func main() {
	mux := http.NewServeMux()
	files := http.FileServer(http.Dir("/public"))
	mux.Handle("/static/", http.StripPrefix("/static/", files))
	server := &http.Server{
		Addr:    "localhost:8080",
		Handler: mux,
	}
	server.ListenAndServe()
}

我将这个代码文件放在%GOPATH%/src/first_app目录下,并使用go install命令安装了这个程序,first_app.exe出现在%GOPATH%/bin目录中。

当我启动web服务器后,我访问了http://localhost:8080/static/a.txt,但是出现了404(未找到)的错误,提示找不到a.txt文件。

我想问一下,我应该把public目录和a.txt文件放在哪里?

英文:

I have a simple web application, the code file which is named HttpServer.go is:

package main

import (
	"net/http"
)

func main() {
	mux := http.NewServeMux()
	files := http.FileServer(http.Dir("/public"))
	mux.Handle("/static/", http.StripPrefix("/static/", files))
	server := &http.Server{
		Addr:    "localhost:8080",
		Handler: mux,
	}
	server.ListenAndServe()
}

I have put the this code file under %GOPATH%/src/first_app, and I go install this program, the first_app.exe shows up in %GOPATH%/bin

When I startup the webserver,I accessed

http://localhost:8080/static/a.txt, but 404(NOT FOUND) complains that a.txt is not found.,

I would ask where should I put the directory public and a.txt

答案1

得分: 1

根据你在http.Dir表达式中指定的路径查找。在你的情况下是/public

很可能你的系统上没有名为/public的路径(因为这是我熟悉的所有操作系统中的非标准目录路径,我猜你还没有创建它)。

/public更改为与你放置文件的路径匹配。

英文:

It looks in the path you specify in your http.Dir expression. /public in your case.

Most likely you don't have a path called /public on your system (since this is a non-standard directory path on all OSes I'm familiar with, and I suspect you haven't created it).

Change /public to match the path where you put your files.

huangapple
  • 本文由 发表于 2017年9月7日 17:51:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/46093251.html
匿名

发表评论

匿名网友

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

确定