0

I have a Go template that should resolve to a struct. How can I convert the bytes.Bufferresult from template execute function back to the struct. Playground

package main

import (
    "bytes"
    "encoding/gob"
    "fmt"
    "log"
    "text/template"
)

type Data struct {
    Age      int
    Username string
    SubData  SubData
}
type SubData struct {
    Name string
}

func main() {
    s := SubData{Name: "J. Jr"}
    d := Data{Age: 26, Username: "HelloWorld", SubData: s}
    tmpl := "{{ .SubData }}"
    t := template.New("My template")
    t, _ = t.Parse(string(tmpl))
    buffer := new(bytes.Buffer)
    t.Execute(buffer, d)
    fmt.Println(buffer)

    // writing
    enc := gob.NewEncoder(buffer)
    err := enc.Encode(s)
    if err != nil {
        log.Fatal("encode error:", err)
    }

    // reading
    buffer = bytes.NewBuffer(buffer.Bytes())
    e := new(SubData)
    dec := gob.NewDecoder(buffer)
    err = dec.Decode(e)
    if err != nil {
        log.Fatal("decode error:", err)
    }
    fmt.Println(e, err)
}
Matt Harrison
  • 13,381
  • 6
  • 48
  • 66
aminjam
  • 646
  • 9
  • 25

1 Answers1

5

You cannot. This is plain simply impossible.

But why on earth would anybody want to do something like this? Why don't you just send your Data directly via gob and decode it directly? Why creating a textual representation which you gob?

Volker
  • 40,468
  • 7
  • 81
  • 87
  • Thanks. I was hoping it would be possible. I am trying to write a JSON-Go Template layout. so I can do `{x:{i1:"1",i2:"2"},y:"{{ .X }}"}`. This way `y` can have a reference to `X` in template after parsing JSON. – aminjam Aug 07 '14 at 12:32
  • @aminjam: Go templates are entirely the wrong tool for you, then. Just use... a struct. – Jonathan Hall Jul 16 '17 at 11:02