protoc-gen-go-template

command module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2018 License: MIT Imports: 3 Imported by: 0

README

Build Status Go Report Card Coverage Status

protoc-gen-go-template

Protocol Buffer generator using go templates

Install

Install protoc and go get github.com/jrmarkle/protoc-gen-go-template. $(go env GOPATH)/bin must be in your PATH.

Example code generation

Suppose you have the file example.proto from which you want to generate custom code:

syntax = "proto3";
package example;
option go_package = "example";

enum MyEnum {
	foo = 0;
	bar = 1;
	baz = 2;
}

Using this template file enums.tmpl:

{{ if .EnumType }}
package {{ .Package }}

import "github.com/golang/protobuf/proto"

{{ range .EnumType }}

func (m {{ .Name }}) Enum() *{{ .Name }} {
	p := new({{ .Name }})
	*p = m
	return p
}

func (m *{{ .Name }}) UnmarshalJSON(data []byte) error {
	value, err := proto.UnmarshalJSONEnum({{ .Name }}_value, data, "{{ .Name }}")
	if err != nil {
		return err
	}
	*m = {{ .Name }}(value)
	return nil
}
{{ end }}
{{ end }}

Run protoc --go-template_out=enums.tmpl,format:. example.proto to generate example.pb.enums.go:

package example

import "github.com/golang/protobuf/proto"

func (m MyEnum) Enum() *MyEnum {
	p := new(MyEnum)
	*p = m
	return p
}

func (m *MyEnum) UnmarshalJSON(data []byte) error {
	value, err := proto.UnmarshalJSONEnum(MyEnum_value, data, "MyEnum")
	if err != nil {
		return err
	}
	*m = MyEnum(value)
	return nil
}

You can use this example as a workaround for protobuf issue #256.

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL