过去两周我一直在玩 Golang,终于可以制作一个真正的应用程序了。它使用 NGINX 提供的静态 HTML 文件,API 使用 Goji Web Framework 作为后端。我不使用任何 Golang 模板,因为一切都是 Angular.Js,所以静态可以满足我的需要。
我希望可以选择是在生产环境中使用 NGINX,还是让 Go 使用应用程序使用的相同端口 (8000) 在根目录下提供静态内容。这样开发环境就不需要安装 NGINX。
因此,尝试像这样向默认多路复用器添加句柄
goji.DefaultMux.Handle("/*", serveStatic)
func serveStatic(w http.ResponseWriter, r *http.Request) {
//http.ServeFile(w, r, r.URL.Path[1:])
//http.FileServer(http.Dir("static"))
http.StripPrefix("/static/", http.FileServer(http.Dir("static")))
此句柄在所有 API 路径都已注册后立即执行(否则 API 将无法工作)。
我已经尝试过任何一种组合,它要么将我重定向到 HTTP 404,要么将 HTML 内容显示为文本。两者都不好。我想知道是否有人来过这里,可以提醒我我做错了什么。
谢谢。
虽然这与我的问题无关,但这是我使用的 NGINX 配置:
server {
listen 80;
# enable gzip compression
gzip on;
gzip_min_length 1100;
gzip_buffers 4 32k;
gzip_types text/plain application/x-javascript text/xml text/css;
gzip_vary on;
# end gzip configuration
location / {
root /home/mleyzaola/go/src/bitbucket.org/mauleyzaola/goerp/static;
try_files $uri $uri/ /index.html = 404;
}
location /api {
proxy_pass http://localhost:8000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
最佳答案
我遇到过类似的问题,所以以下几点可能会有所帮助。
请记住将提供静态内容的处理程序注册为最终路由。否则,它可能会匹配所有内容。
也许尝试使用绝对路径而不是相对路径。
这是我如何使用 Goji 设置路线的简化版本。
func apiExampleHandler(context web.C, resp http.ResponseWriter, req *http.Request) {
fmt.Fprint(resp, "You've hit the API!")
}
func main() {
goji.Handle("/api", apiExampleHandler)
// Static file handler should generally be the last handler registered. Otherwise, it'll match every path.
// Be sure to use an absolute path.
staticFilesLocation := "Some absolute to the directory with your static content."
goji.Handle("/*", http.FileServer(http.Dir(staticFilesLocation)))
goji.Serve()
}
关于Golang 枸杞 : How to serve static content and api at the same time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26320144/