2 回答

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

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")
})
- 2 回答
- 0 關注
- 181 瀏覽
添加回答
舉報