0

ルーティングを正しく取得できないようです。私はGorilla Muxを使用しており、Angularアプリを提供しようとしているため、基本的には「/ foo」で始まるURL以外のすべてのURLからindex.htmlを提供しています。

これは機能します:

func StaticFileServer(w http.ResponseWriter, r *http.Request) {
  http.ServeFile(w, r, config.dir)
}

func main() {

  fs := http.Dir(config.dir)
  fileHandler := http.FileServer(fs)

  router = mux.NewRouter()

  router.Handle("/foo/page", PublicHandler(handler(getAll)).Methods("GET")
  router.Handle("/foo/page/{id}", PublicHandler(handler(getOne)).Methods("GET")

  router.PathPrefix("/{blaah}/{blaah}/").Handler(fileHandler)
  router.PathPrefix("/").HandlerFunc(StaticFileServer)

  ...
}

しかし、この PathPrefix("/{blaah}/{blaah}/") のように、可能なすべてのルートを明示的に宣言するよりも簡単な方法があるはずです...これを使用すると、/{blaah}/{blaah 以外の URL }/ は、index.html の代わりに 404 page not found を返します。

したがって、見つかった限りすべて (静的ファイルなど) を提供したいと思いますが、それ以外はすべて /public/index.html を返す必要があります。

4

2 に答える 2

1

私も同じ問題に直面していましたが、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)
}
于 2020-05-19T21:01:14.380 に答える