为了账号安全,请及时绑定邮箱和手机立即绑定

我可以在一台服务器上托管 Angular2 前端和 Golang 后端吗

我可以在一台服务器上托管 Angular2 前端和 Golang 后端吗

Go
守候你守候我 2021-12-20 15:56:30
我想用 Golang 创建 RESTful API,用 Angular2 创建前端。将通过 http 请求进行通信。Angular2 将向 Golang API 发送请求。我知道对于 Angular2,我应该运行自己的 http 服务器来进行路由和服务。我可以在一台主机上运行 Golang 服务器,在另一台主机上运行 Angular2 服务器并将它们连接在一起吗?
查看完整描述

2 回答

?
侃侃尔雅

TA贡献1801条经验 获得超16个赞

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

似乎有可能。请参阅此链接:

编辑

关注您的评论:

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

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


查看完整回答
反对 回复 2021-12-20
?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

使用标准库实际实现


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")

})


查看完整回答
反对 回复 2021-12-20
  • 2 回答
  • 0 关注
  • 183 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号