I am interested in appending content to a Go template but within a certain section of the template. Since the template has a structure defined, whenever I try to append new content on executing the template, it appends the new content to the previously executed template content:
Example template:
type Client struct {
Opts *ClientOpts
Schemas *Schemas
Types map[string]Schema
Container *{{.schema.Id}}Client
}
Actual output:
type Client struct {
Opts *ClientOpts
Schemas *Schemas
Types map[string]Schema
Container *abcClient
}
type Client struct {
Opts *ClientOpts
Schemas *Schemas
Types map[string]Schema
Container *xyzClient
}
}
Desired output:
type Client struct {
Opts *ClientOpts
Schemas *Schemas
Types map[string]Schema
Container *abcClient
Container *xyzClient
}
My current Go code looks like this:
func appendToFile(filename string, template *template.Template, schema client.Schema) error {
output, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
panic(err)
}
defer output.Close()
data := map[string]interface{}{
"schema": schema,
}
err = template.Execute(output, data)
return err
}
One solution I can think of is to make a seek every time to the previous appended content and write the new content there. But I am not sure how to do that in Go. Could someone provide me with a code snippet for that or suggest a better strategy?
Instead of appending the data, generate the output with one execution of the template:
package main
import (
"fmt"
"os"
"text/template"
)
var t = template.Must(template.New("").Parse(` type Client struct {
Opts *ClientOpts
Schemas *Schemas
Types map[string]Schema
{{range .}}
Container *{{.schema.Id}}Client{{end}}
}
`))
type schema struct {
Id string
}
func main() {
data := []map[string]interface{}{
{"schema": schema{Id: "abcClient"}},
{"schema": schema{Id: "xyzClient"}},
}
if err := t.Execute(os.Stdout, data); err != nil {
fmt.Println(err)
}
}