【问题标题】:Can I host Angular2 frontend and Golang backend in one server我可以在一台服务器上托管 Angular2 前端和 Golang 后端吗
【发布时间】:2016-06-23 11:59:31
【问题描述】:

我想用 Golang 创建 RESTful API,用 Angular2 创建前端。 将通过 http 请求进行通信。 Angular2 将向 Golang API 发送请求。我知道对于 Angular2,我应该为路由和服务运行自己的 http 服务器。

我可以在一台主机上运行 Golang 服务器,在另一台主机上运行 Angular2 服务器并将它们连接在一起吗?

【问题讨论】:

    标签: go angular frontend backend


    【解决方案1】:

    Angular2 应用程序对应一组静态文件(依赖项和应用程序代码)。要让 Go 为您的应用程序提供服务,您需要添加一些代码来提供这些文件。

    这似乎是可能的。看这个链接:

    编辑

    根据您的评论:

    如果你想在一台服务器上托管 Angular2 和 golang。例如,我可以通过链接 mywebsite.com 访问网站并访问 golang api api.mywebsite.com

    我看不出有什么理由不这样做。请注意在您的 API 中支持 CORS(在响应中发送 CORS 标头并支持预请求请求)。请参阅以下链接:

    【讨论】:

    • 甚至可以使用bindata-assetfsgo.rice 之类的东西将这些资产包含到二进制文件中。
    • 我想分别使用 golang 和 angular2。 Golang 服务器将只发送 json 数据。 Angular 将从 golang 服务器 api 请求数据并呈现网页。我可以在一台服务器上托管 angular 和 golang 吗?例如,我将可以访问带有链接 mywebsite.com 的网站并访问 golang api api.mywebsite.com
    • 我看不出有什么理由不这样做。请注意在您的 API 中支持 CORS。见restlet.com/blog/2015/12/15/understanding-and-using-cors
    【解决方案2】:

    使用标准库的实际实现

    type Adapter func(http.Handler) http.Handler
    
    // Adapt function to enable middlewares on the standard library
    func Adapt(h http.Handler, adapters ...Adapter) http.Handler {
        for _, adapter := range adapters {
            h = adapter(h)
        }
        return h
    }
    
    // Creates a new serve mux
    mux := http.NewServeMux()
    
    // Create room for static files serving
    mux.Handle("/node_modules/", http.StripPrefix("/node_modules", http.FileServer(http.Dir("./node_modules"))))
    mux.Handle("/html/", http.StripPrefix("/html", http.FileServer(http.Dir("./html"))))
    mux.Handle("/js/", http.StripPrefix("/js", http.FileServer(http.Dir("./js"))))
    mux.Handle("/ts/", http.StripPrefix("/ts", http.FileServer(http.Dir("./ts"))))
    mux.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("./css"))))
    
    // Do your api stuff**
    mux.Handle("/api/register", Adapt(api.RegisterHandler(mux),
        api.GetMongoConnection(),
        api.CheckEmptyUserForm(),
        api.EncodeUserJson(),
        api.ExpectBody(),
        api.ExpectPOST(),
    
    ))
    mux.HandleFunc("/api/login", api.Login)
    mux.HandleFunc("/api/authenticate", api.Authenticate)
    
    // Any other request, we should render our SPA's only html file,
    // Allowing angular to do the routing on anything else other then the api    
    // and the files it needs for itself to work.
    // Order here is critical. This html should contain the base tag like
    // <base href="/"> *href here should match the HandleFunc path below 
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "html/index.html")
    })
    

    【讨论】:

      猜你喜欢
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-08
      • 1970-01-01
      • 2016-02-18
      • 2022-11-29
      相关资源
      最近更新 更多