LoginSignup
12
6

More than 3 years have passed since last update.

[statik] Goで静的ファイルもバイナリに内包してデプロイする

Last updated at Posted at 2019-07-13

Intro

Goでアプリケーションを作っている場合、ビルドしたバイナリを配布するだけで簡単にアプリケーションをデプロイできます。

ただ、Goファイルでない静的ファイルなども一緒にリリースしたいといったユースケースの場合、バイナリとは別にファイルも一緒にリリースする必要があり、ひと手間増えてしまいます。

例えば toml などで記述したアプリケーションの設定ファイルも一緒にリリースしたいといったユースケースなどが想像できます。

そんな時 statik を使えばバイナリにファイルを同梱してワンバイナリでリリースしたいという誰もがやりたいことを簡単に実現することができます。

Usage

基本的には本家の README を参考にしてみてください。
https://github.com/rakyll/statik

以降は少しイメージを膨らませるためのサンプルソースになります。

$ go get github.com/rakyll/statik

例えば、下記のような環境毎に設定ファイルがあるケース

conf
├── develop
│   └── app.toml
├── staging
│   └── app.toml
└── production
    └── app.toml
conf/develop/app.toml
[s3]
bucket = "your_bucket_name"
region = "ap-northeast-1"
endpoint = "http://dev.xxx.jp"

Goバイナリに含めたいファイルディレクトリを指定して以下を実行します

$ statik -src=/path/to/your/project/conf

statik.go という .go ファイルが出来上がります。

statik
└── statik.go

中身は以下のようなイメージです。

statik/statik.go
// Code generated by statik. DO NOT EDIT.

// Package statik contains static assets.
package statik

import (
    "github.com/rakyll/statik/fs"
)

func init() {
    data := "\x03\x04\..."
    fs.Register(data)
}

アプリケーションから下記のようなイメージで読み込んで使用します。

import (
    "path/filepath"

    "github.com/BurntSushi/toml"
    "github.com/rakyll/statik/fs"

  _ "./statik" // TODO: Replace with the absolute import path
)

type Config struct {
    S3  S3 `toml:"s3"`
}

type S3 struct {
    Region   string `toml:"region"`
    Bucket   string `toml:"bucket"`
    Endpoint string `toml:"endpoint"`
}

func New() (*Config, error) {
    conf := &Config{}

    e := "develop" // ← 環境変数なりで動的に変える。サンプルコードなので簡易的に
    fPath := filepath.Join("/", e, "app.toml")
    fileSystem, err := fs.New()
    if err != nil {
        return nil, err
    }

    f, err := fileSystem.Open(fPath)
    if err != nil {
        return nil, err
    }
    defer f.Close()

    _, err = toml.DecodeReader(f, conf)
    if err != nil {
        return nil, err
    }

    return conf, nil
}

.go ファイルとして出力されているので、buildしてしまえば一つのバイナリを配布するだけでデプロイすることが出来ます。便利。

あでゅ。

12
6
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
12
6