Extract ProtoHelpersFuncMap in its own file

This commit is contained in:
Mathieu Acthernoene 2016-12-15 13:28:57 +01:00
parent d7c3d1a32b
commit add7ae7237
2 changed files with 36 additions and 31 deletions

View File

@ -2,7 +2,6 @@ package main
import ( import (
"bytes" "bytes"
"encoding/json"
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
@ -10,39 +9,10 @@ import (
"text/template" "text/template"
"time" "time"
"github.com/Masterminds/sprig"
"github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/golang/protobuf/protoc-gen-go/plugin" "github.com/golang/protobuf/protoc-gen-go/plugin"
) )
var ProtoHelpersFuncMap = template.FuncMap{
"string": func(i interface {
String() string
}) string {
return i.String()
},
"json": func(v interface{}) string {
a, _ := json.Marshal(v)
return string(a)
},
"prettyjson": func(v interface{}) string {
a, _ := json.MarshalIndent(v, "", " ")
return string(a)
},
"first": func(a []string) string {
return a[0]
},
"last": func(a []string) string {
return a[len(a)-1]
},
}
func init() {
for k, v := range sprig.TxtFuncMap() {
ProtoHelpersFuncMap[k] = v
}
}
type GenericTemplateBasedEncoder struct { type GenericTemplateBasedEncoder struct {
templateDir string templateDir string
service *descriptor.ServiceDescriptorProto service *descriptor.ServiceDescriptorProto
@ -146,7 +116,6 @@ func (e *GenericTemplateBasedEncoder) buildContent(templateFilename string) (str
// initialize template engine // initialize template engine
fullPath := filepath.Join(e.templateDir, templateFilename) fullPath := filepath.Join(e.templateDir, templateFilename)
templateName := filepath.Base(fullPath) templateName := filepath.Base(fullPath)
tmpl, err := template.New(templateName).Funcs(ProtoHelpersFuncMap).ParseFiles(fullPath) tmpl, err := template.New(templateName).Funcs(ProtoHelpersFuncMap).ParseFiles(fullPath)
if err != nil { if err != nil {
return "", "", err return "", "", err

36
helpers.go Normal file
View File

@ -0,0 +1,36 @@
package main
import (
"encoding/json"
"text/template"
"github.com/Masterminds/sprig"
)
var ProtoHelpersFuncMap = template.FuncMap{
"string": func(i interface {
String() string
}) string {
return i.String()
},
"json": func(v interface{}) string {
a, _ := json.Marshal(v)
return string(a)
},
"prettyjson": func(v interface{}) string {
a, _ := json.MarshalIndent(v, "", " ")
return string(a)
},
"first": func(a []string) string {
return a[0]
},
"last": func(a []string) string {
return a[len(a)-1]
},
}
func init() {
for k, v := range sprig.TxtFuncMap() {
ProtoHelpersFuncMap[k] = v
}
}