Golang Goji:如何同时提供静态内容和api

过去两周我一直在玩Golang,最后可以开始真正的应用程序.它使用NGINX提供的静态 HTML文件,API使用Goji Web Framework作为后端.我不使用任何Golang模板,因为一切都是Angular.Js,所以静态可以满足我的需求.

我想选择是否在生产中使用NGINX,或者让Go使用应用程序使用的相同端口在root上提供静态内容(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()
}

我用一个示例项目创建了以下GitHub存储库.我可以访问静态内容和API.

https://github.com/Retired/26320144

相关文章

Golang的文档和社区资源:为什么它可以帮助开发人员快速上手...
Golang:AI 开发者的实用工具
Golang的标准库:为什么它可以大幅度提高开发效率?
Golang的部署和运维:如何将应用程序部署到生产环境中?
高性能AI开发:Golang的优势所在
本篇文章和大家了解一下go语言开发优雅得关闭协程的方法。有...