LoginSignup
17
13

More than 5 years have passed since last update.

echo 初心者でも簡単!! echo で扱うアセットファイル群を簡単にバイナリにまとめて使ってみる

Posted at

最近 Go の web framework である github.com/labstack/echo を使ってアプリケーションを作ることが多くなってきました。昨日 echo で静的ファイルをバイナリに突っ込みたいなと考えた時、gin なら github.com/gin-contrib/static があるのですが、 echo は自前で書かないとありませんでした。そこで、「パクればええやん」と思いついて出来上がったのがこちらになります。

Static middleware for echo web framework(golang)

https://github.com/Code-Hex/echo-static

早速使ってみましょう。

使ってみる

mkdir echo && cd echo

を実行した後、このようなディレクトリ構造を用意します。

.
├── assets
│   ├── gopher.png
│   └── index.html
└── main.go

index.html はこんな感じです。

index.html
<!doctype html>

<html>
<head>
  <meta charset="utf-8">
  <title>Echo!!</title>
</head>
<body>
<p>Hello, World gophers!!</p>
<img src="/static/gopher.png">
</body>

gopher.png です。
gopher.png
か、かわいい!!!!!

ここで 次のような main.go を作成しましょう。

main.go
package main

import (
    static "github.com/Code-Hex/echo-static"

    assetfs "github.com/elazarl/go-bindata-assetfs"
    "github.com/labstack/echo"
)

func main() {
    e := echo.New()

    e.Use(static.ServeRoot("/static", NewAssets("assets")))
    e.GET("/ping", func(c echo.Context) error {
        return c.String(200, "test")
    })
    // Listen and Server in 0.0.0.0:8080
    e.Start(":8080")
}

func NewAssets(root string) *assetfs.AssetFS {
    return &assetfs.AssetFS{
        Asset:     Asset,
        AssetDir:  AssetDir,
        AssetInfo: AssetInfo,
        Prefix:    root,
    }
}

そして go-bindata を次のように実行してみましょう。

go-bindata -o bindata.go assets/...

こうすると、ディレクトリ構成は次のようになるはずです。

.
├── assets
│   ├── gopher.png
│   └── index.html
├── bindata.go
└── main.go

それでは go build を実行してバイナリを作りましょう。すると echo という名前のバイナリが出来上がるはずです。

実行

./echo

ブラウザで 127.0.0.1:8080 にアクセスしてみましょう。
{"message":"Not Found"} のようなメッセージが表示されるはずです。

しかし、main.go のファイルをもう一度見てみましょう。

e.Use(static.ServeRoot("/static", NewAssets("assets")))

とありますね!
ということは 127.0.0.1:8080/static へブラウザでアクセスしてみましょう!
可愛いページが表示されますね!!

これは 127.0.0.1:8080/static にアクセスした時、 assets ディレクトリ上に置かれているファイルへアクセス可能にするという意味のコードです。
つまり、index.html へアクセスしたい場合は 127.0.0.1:8080/static もしくは 127.0.0.1:8080/static/index.html、gopher.png にアクセスしたい場合は 127.0.0.1:8080/static/gopher.png へアクセスすればいいのです!

まとめ

echo でもめっちゃ簡単にアセットをバイナリにまとめて、ブラウザなどからアクセスすることができる。

17
13
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
17
13