私も同じ問題に直面していましたが、Gorilla mux を使用すれば、これに対する明確な解決策があります。
Angular は単一ページのアプリケーションであるため、そのように処理する必要があります。クライアントとサーバーの2つのフォルダーがあります。クライアントフォルダー内にすべてのAngularコードを保持し、サーバーフォルダー内にすべてのサーバーコードを保持するため、index.htmlをレンダリングする静的パスは「client/dist」です。ここで dist フォルダーは角度のあるビルド フォルダーです。
Go ルーターのコードを以下に示します。
func main {
router := mux.NewRouter()
spa := spaHandler{staticPath: "client/dist", indexPath: "index.html"}
router.PathPrefix("/").Handler(spa)
}
spaHandler は http.Handler インターフェースを実装しているため、これを使用して HTTP 要求に応答できます。静的ディレクトリへのパスとその静的ディレクトリ内のインデックス ファイルへのパスは、特定の静的ディレクトリで SPA を提供するために使用されます。
type spaHandler struct {
staticPath string
indexPath string
}
ServeHTTP は、URL パスを調べて、SPA ハンドラーの静的ディレクトリ内のファイルを見つけます。ファイルが見つかった場合は、それが提供されます。そうでない場合は、SPA ハンドラーのインデックス パスにあるファイルが提供されます。これは、SPA (シングル ページ アプリケーション) を提供するのに適した動作です。
func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// get the absolute path to prevent directory traversal
path, err := filepath.Abs(r.URL.Path)
if err != nil {
// if we failed to get the absolute path respond with a 400 bad request
// and stop
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// prepend the path with the path to the static directory
path = filepath.Join(h.staticPath, path)
// check whether a file exists at the given path
_, err = os.Stat(path)
if os.IsNotExist(err) {
// file does not exist, serve index.html
http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
return
} else if err != nil {
// if we got an error (that wasn't that the file doesn't exist) stating the
// file, return a 500 internal server error and stop
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// otherwise, use http.FileServer to serve the static dir
http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)
}