aminjam
aminjam

Reputation: 646

Go template to struct

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)
}

Upvotes: 0

Views: 581

Answers (1)

Volker
Volker

Reputation: 42413

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?

Upvotes: 5

Related Questions