LoginSignup
3
0

More than 5 years have passed since last update.

Go言語のhttp.StripPrefix()等をひとつずつ確認

Last updated at Posted at 2017-08-23

よくわからなかったので1つずつコメント書いてみた。考え方の補助に。

package main

import (
    "net/http"
)

func main() {
    // string型のディレクトリ名 "html" を http.Dir型 にキャストする
    dir := http.Dir("html")

    // http.Dir型 は FileSystemインターフェースを満たすので
    // これを http.FileServer() に渡して 静的ファイルを返すハンドラ html_hdlr を得る
    html_hdlr := http.FileServer(dir)

    // html_hdlr を元に、先頭の "/file/" を除外するハンドラ split_prefix_hdlr を作成する
    split_prefix_hdlr := http.StripPrefix("/file/", html_hdlr)

    // DefaultServeMux に URLパス "/file/" と split_prefix_hdlr のペアを追加する
    http.Handle("/file/", hdlr)

    // サーバーを起動する
    // nilを指定すると DefaultServeMux が使われる
    http.ListenAndServe(":8081", nil)

    // -> ブラウザで http://localhost:8081/file/index.html にアクセスすると
    //    静的ファイル html/index.html が得られる
}
3
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
3
0