Home > Software design >  Is there any way to run custom commands with go install command?
Is there any way to run custom commands with go install command?

Time:03-21

I've written a simple code generation tool. I've used text/template package in this tool. When I installed it with go build command, it installed successfully. The only problem I'm facing is how to install templates when you install the program. Currently It is unable to get templates.

Shall I use template text in .go files or Is there any other way we can give instructions to install binary and templates at a particular location? I think it's good to have template text in between code as a raw string. But is there any particular way to doing the same?

CodePudding user response:

You can use the embed package.

Package embed provides access to files embedded in the running Go program.

Go source files that import "embed" can use the //go:embed directive to initialize a variable of type string, []byte, or FS with the contents of files read from the package directory or subdirectories at compile time.

import (
    "embed"
    "text/template"
)

//go:embed templates/*
var mytemplateFS embed.FS

func main() {
    t := template.New("")
    t = template.Must(t.ParseFS(mytemplateFS, "*"))
}
  • Related