feat(api): adding api server code
templater can be used as a commmand line tool or as an api server.
This commit is contained in:
76
cmd/templater.go
Normal file
76
cmd/templater.go
Normal file
@ -0,0 +1,76 @@
|
||||
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)
|
||||
}
|
||||
|
||||
result := ""
|
||||
if templateType == "go" {
|
||||
result = templater.ProcessGoTemplate(templateFile, config)
|
||||
} else if templateType == "hcl" {
|
||||
result = templater.ProcessHCLTemplate(templateFile, config)
|
||||
} else {
|
||||
panic(fmt.Errorf("Unsupported template type"))
|
||||
}
|
||||
if output == "stdout" {
|
||||
fmt.Printf("%s", result)
|
||||
} else {
|
||||
err := os.WriteFile(output, []byte(result), 0644)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user