-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgoka.go
61 lines (50 loc) · 1.55 KB
/
goka.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package schemagen
import (
"bytes"
"text/template"
"gopkg.in/alanctgardner/gogen-avro.v5/generator"
"gopkg.in/alanctgardner/gogen-avro.v5/types"
)
var (
gokaCodecTpl = template.Must(template.New("codec").Parse(`type {{.CodecType}} struct{}`))
gokaEncoderTpl = template.Must(template.New("encoder").Parse(`
func ({{.CodecGoType}}) Encode(value interface{}) ([]byte, error) {
v := value.({{.BaseGoType}})
var b bytes.Buffer
if err := v.Serialize(&b); err != nil {
return nil, err
}
return b.Bytes(), nil
}
`))
gokaDecoderTpl = template.Must(template.New("decoder").Parse(`
func ({{.CodecGoType}}) Decode(data []byte) (interface{}, error) {
return Deserialize{{.BaseType}}(bytes.NewReader(data))
}
`))
)
func generateGoka(filename string, r *types.RecordDefinition, pkg *generator.Package) {
params := struct {
BaseType string
BaseGoType string
CodecType string
CodecGoType string
}{
BaseType: r.Name(),
BaseGoType: "*" + r.Name(),
CodecType: r.Name() + "Codec",
CodecGoType: "*" + r.Name() + "Codec",
}
pkg.AddImport(filename, "bytes")
pkg.AddStruct(filename, params.CodecType, renderTemplate(gokaCodecTpl, params))
pkg.AddFunction(filename, params.CodecGoType, "Encode", renderTemplate(gokaEncoderTpl, params))
pkg.AddFunction(filename, params.CodecGoType, "Decode", renderTemplate(gokaDecoderTpl, params))
}
func renderTemplate(t *template.Template, params interface{}) string {
var b bytes.Buffer
if err := t.Execute(&b, params); err != nil {
// Templates should never fail.
panic(err)
}
return b.String()
}