※2019/10/13追記
1行で書くことも可能なようですが、拡張性がなくなるので2行としています。
間違っていたら教えていただけると幸いです。
本題
net/http
パッケージのhttp.FileServer
を使う。
main.go
package main
import "net/http"
func main() {
http.Handle("/", http.FileServer(http.Dir("./img")))
http.ListenAndServe("localhost:8080", nil)
}
以下のディレクトリ構造で実行した。
ディレクトリ構造
.
├── img
│ └── rabbit.jpg
└── main.go
ディレクトリ構造が複雑な場合
- ディレクトリ構造が複雑な場合
- URLのPATHを変えたい場合
などはhttp.StripPrefix
で対応できる。
main.go
package main
import "net/http"
func main() {
http.Handle("/resources/", http.StripPrefix("/resources", http.FileServer(http.Dir("./files/hoge/fuga/img"))))
http.ListenAndServe("localhost:8080", nil)
}
ディレクトリ構造
.
├── files
│ └── hoge
│ └── fuga
│ └── img
│ └── rabbit.jpg
└── main.go