templatefile/cmd/templater/main.go

77 lines
1.8 KiB
Go
Raw Normal View History

package main
import (
"fmt"
"os"
"forge.cadoles.com/pcaseiro/templatefile/api"
"forge.cadoles.com/pcaseiro/templatefile/pkg/templater"
"github.com/alexflint/go-arg"
"github.com/gin-gonic/gin"
)
func Daemon(port int) (err error) {
r := gin.Default()
r.POST("/generate", api.Generate)
err = r.Run(fmt.Sprintf("0.0.0.0:%d", port)) // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
if err != nil {
return (err)
}
return nil
}
func main() {
var args struct {
Daemon bool `arg:"-d,--daemon,env:TEMPLATER_DAEMON" default:"false" help:"Enable api server"`
Port int `arg:"-p,--port,env:TEMPLATER_PORT" default:"8080" help:"Listening port for the api server"`
Type string `arg:"-t,--type,env:TEMPLATE_TYPE" default:"hcl" help:"Template type (go/template or hcl)"`
Output string `arg:"-o,--output,env:TEMPLATER_OUTPUT" default:"stdout" help:"Destination of the result (stdout or file path)"`
Config string `arg:"-c,--config,env:TEMPLATE_CONFIG" help:"Configuration values"`
File string `arg:"-f,--template-file,env:TEMPLATE_FILE" help:"Template file path"`
}
arg.MustParse(&args)
if args.Daemon {
err := Daemon(args.Port)
if err != nil {
panic(err)
}
} else {
var config []byte
templateType := args.Type
templateFile := args.File
output := args.Output
if _, err := os.Stat(args.Config); err == nil {
config, err = os.ReadFile(args.Config)
if err != nil {
panic(err)
}
} else {
config = []byte(args.Config)
}
var file templater.ConfigFile
file.Source = templateFile
file.TemplateType = templateType
result, err := file.ProcessTemplate(templateFile, config)
if err != nil {
panic(err)
}
if output == "stdout" {
fmt.Printf("%s", result)
} else {
err := os.WriteFile(output, []byte(result), 0644)
if err != nil {
panic(err)
}
}
}
}