2016-03-09 08:01
浏览 114


I want to create RESTful API with Golang and frontend with Angular2. Communication will be made with http requests. Angular2 will send requests to Golang API's. I know for Angular2 I should run own http server for routing and services.

Can I run Golang server on one host and Angular2 server on another one and connect them together?

图片转代码服务由CSDN问答提供 功能建议

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

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dsoxcj7276 2016-03-09 08:05

    Angular2 applications correspond to a set of static files (dependencies and application code). To have your application served by Go, you need to add some code to serve these files.

    It seems possible. See this link:


    Following your comment:

    If you want to host Angular2 and golang in one server. For example i will have access to web site with link mywebsite.com and access to golang api api.mywebsite.com

    I can't see any reason not to do that. Just be careful to support CORS in your API (send the CORS headers in the response and support prefligthed requests). See these links:

    点赞 打赏 评论
  • dongyun9120 2016-07-25 22:27

    Actual implementation with the stadand library

    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),
    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")
    点赞 打赏 评论

相关推荐 更多相似问题