Go模板到结构体

huangapple go评论87阅读模式
英文:

Go template to struct

问题

我有一个Go模板,应该解析为一个结构体。我该如何将模板执行函数的bytes.Buffer结果转换回structPlayground

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)

	// 写入
	enc := gob.NewEncoder(buffer)
	err := enc.Encode(s)
	if err != nil {
		log.Fatal("编码错误:", err)
	}

	// 读取
	buffer = bytes.NewBuffer(buffer.Bytes())
	e := new(SubData)
	dec := gob.NewDecoder(buffer)
	err = dec.Decode(e)
	if err != nil {
		log.Fatal("解码错误:", err)
	}
	fmt.Println(e, err)
}
英文:

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

答案1

得分: 5

你不能这样做。这根本是不可能的。

但是为什么会有人想要做这样的事情呢?为什么不直接通过 gob 发送和解码你的 Data 呢?为什么要创建一个文本表示然后再进行 gob 编码呢?

英文:

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?

huangapple
  • 本文由 发表于 2014年8月7日 19:24:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/25181266.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定