markbates / pkger

Embed static files in Go binaries (replacement for gobuffalo/packr)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is it possible to use embedded asset in variable initialisation?

sbellus opened this issue · comments

I am not able to open embedded file during variable assignment. I get file not found error.
I use pkger.Open during var homeTemplate initialisation.

package web

import (
	"html/template"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/markbates/pkger"
)

type homeData struct {
	Address         string
	ApplicationName string
}

func webHome(w http.ResponseWriter, r *http.Request) {
	homeTemplate.Execute(w, homeData{"ws://" + r.Host + "/devices", WebName})
}

var homeTemplate = template.Must(template.New("").Parse(readHomeTemplate()))

func readHomeTemplate() string {
	f, eo := pkger.Open("/web/home.gohtml")
	if eo != nil {
		log.Printf("No possible to open template %v : %v", "name", eo)
		return ""
	}

	d, er := ioutil.ReadAll(f)
	if eo != nil {
		log.Printf("No possible to read template %v : %v", "name", er)
		return ""
	}

	return string(d)
}

I handled this by creating another package called pkger in my project, passing the real pkger's types through it, then writing the generated output to internal/pkger/pkged.go.

Since the static analysis just checks for the package name, this means pkger doesn't know it's some other package. And, since the output is going to this new package, it's guaranteed to have fully initialized before its importers, so any embedded data will be there to use.

// Package pkger wraps pkger to ensure a common package contains the embedded data.
// It abuses the fact that pkger's static analysis only cares that the package name matches.
package pkger

import "github.com/markbates/pkger"

type Dir = pkger.Dir

Thank you, I will try