2 回答

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超16個(gè)贊
Angular2 應(yīng)用程序?qū)?yīng)一組靜態(tài)文件(依賴項(xiàng)和應(yīng)用程序代碼)。要讓 Go 為您的應(yīng)用程序提供服務(wù),您需要添加一些代碼來(lái)提供這些文件。
似乎有可能。請(qǐng)參閱此鏈接:
編輯
關(guān)注您的評(píng)論:
如果您想在一臺(tái)服務(wù)器上托管 Angular2 和 golang。例如,我將可以通過(guò)鏈接 mywebsite.com 訪問(wèn)網(wǎng)站并訪問(wèn) golang api api.mywebsite.com
我看不出有什么理由不這樣做。請(qǐng)注意在您的 API 中支持 CORS(在響應(yīng)中發(fā)送 CORS 標(biāo)頭并支持預(yù)檢請(qǐng)求)。請(qǐng)參閱這些鏈接:
http://restlet.com/blog/2015/12/15/understanding-and-using-cors
http://restlet.com/blog/2016/09/27/how-to-fix-cors-problems/

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
使用標(biāo)準(zhǔn)庫(kù)實(shí)際實(shí)現(xiàn)
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")
})
- 2 回答
- 0 關(guān)注
- 170 瀏覽
添加回答
舉報(bào)