LoginSignup
0
0

More than 3 years have passed since last update.

たった2行のGoでファイルサーバを立てる

Last updated at Posted at 2019-10-12

※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

実行結果
01.gif

ディレクトリ構造が複雑な場合

  • ディレクトリ構造が複雑な場合
  • 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

実行結果
02.gif

0
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
0
0