AllIsHackedOff

Just a memo, just a progress

Goで静的ファイルのバイナリ埋め込み

go-bindata が死んでからあんまりやっていなかったけどAWS Lambda上でテンプレートファイルを読んで処理するプログラムを書くことになり、 一時ファイルの置き場やらデプロイやらで面倒なことをしたくなかったのでシングルバイナリにまとめることに

github.com

悪くない。テンプレートはParseするときに普通のstringを受け取れるので、テンプレートファイルを扱うときも適当にかけば動く

main.go
templates/
    admin/
          index.html
import (
    "fmt"
    "html/template"
    "os"

    "github.com/gobuffalo/packr"
)

func main() {
    box := packr.NewBox("./templates")

    s := box.String("admin/index.html")
    t := template.New("admin/index")
    t, err := t.Parse(s)
    if err != nil {
        panic(err)
    }
    err = t.Execute(os.Stdout, map[string]string{
        "Hoge": "Variable hoge",
    })
    if err != nil {
        panic(err)
    }
    fmt.Println("______________")
    fmt.Println(s)
    fmt.Println("--------------")
<html>
    <head>
        <title>admin</title>
    </head>
    <body>
        Variable {{ .Hoge }}
        amdin dayo ---- aaaaaaaaa
    </body>
</html>