LoginSignup
2
0

More than 3 years have passed since last update.

gorilla/muxでルートパスに静的ファイルを公開する方法

Posted at

Goのgorilla/muxにて、ルートパスで静的ファイルを公開する方法です。

ルートパス以外で静的ファイルを公開する場合

まずは、ルートパス以外で公開する方法です。今回は web フォルダにHTML/CSS/JavaScriptなどの静的ファイルを配備しているとします。

お手軽な方法は以下のように http.FileServer を用いる方法です。

r := mux.NewRouter()

// publish static file 
r.Handle("/web/", http.StripPrefix("/web/", http.FileServer(http.Dir("web/"))))
// or
r.PathPrefix("/web/").Handler(http.StripPrefix("/web/", http.FileServer(http.Dir("web/"))))

log.Fatal(http.ListenAndServe(":8000", r))

簡単ですね。

ルートパスで静的ファイルを公開する場合

/web/ 部分を / にしても上手く認識されないため、NotFoundHandlerに記載します。

r := mux.NewRouter()

r.NotFoundHandler = http.StripPrefix("/", http.FileServer(http.Dir("web/")))

log.Fatal(http.ListenAndServe(":8000", r))

これで、その他のルーティングが存在しない場合のみ、静的ファイルを提供できます。

参考

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0