├── examples ├── go.mod ├── go-kit │ ├── services │ │ ├── user │ │ │ ├── gen │ │ │ │ ├── README.md │ │ │ │ ├── endpoints │ │ │ │ │ └── endpoints.go │ │ │ │ ├── client │ │ │ │ │ └── grpc │ │ │ │ │ │ └── client.go │ │ │ │ ├── transports │ │ │ │ │ ├── http │ │ │ │ │ │ └── http.go │ │ │ │ │ └── grpc │ │ │ │ │ │ └── grpc.go │ │ │ │ └── pb │ │ │ │ │ └── pb.go │ │ │ ├── user.proto │ │ │ └── service.go │ │ ├── session │ │ │ ├── gen │ │ │ │ ├── README.md │ │ │ │ ├── endpoints │ │ │ │ │ └── endpoints.go │ │ │ │ ├── client │ │ │ │ │ └── grpc │ │ │ │ │ │ └── client.go │ │ │ │ ├── transports │ │ │ │ │ ├── http │ │ │ │ │ │ └── http.go │ │ │ │ │ └── grpc │ │ │ │ │ │ └── grpc.go │ │ │ │ └── pb │ │ │ │ │ └── pb.go │ │ │ ├── session.proto │ │ │ └── service.go │ │ └── sprint │ │ │ ├── gen │ │ │ ├── README.md │ │ │ ├── transports │ │ │ │ ├── http │ │ │ │ │ └── http.go │ │ │ │ └── grpc │ │ │ │ │ └── grpc.go │ │ │ ├── endpoints │ │ │ │ └── endpoints.go │ │ │ └── client │ │ │ │ └── grpc │ │ │ │ └── client.go │ │ │ ├── service.go │ │ │ └── sprint.proto │ ├── .gitignore │ ├── templates │ │ └── {{.File.Package}} │ │ │ └── gen │ │ │ ├── README.md.tmpl │ │ │ ├── transports │ │ │ ├── http │ │ │ │ └── http.go.tmpl │ │ │ └── grpc │ │ │ │ └── grpc.go.tmpl │ │ │ ├── client │ │ │ └── grpc │ │ │ │ └── client.go.tmpl │ │ │ └── endpoints │ │ │ └── endpoints.go.tmpl │ ├── glide.yaml │ ├── Makefile │ ├── glide.lock │ └── main.go ├── dummy │ ├── output │ │ └── static.txt │ ├── templates │ │ ├── export.json.tmpl │ │ └── static.txt.tmpl │ ├── Makefile │ └── dummy.proto ├── go-generate │ ├── Makefile │ ├── example.go │ ├── gen │ │ ├── doc.gen.go │ │ └── example.pb.go │ ├── example.proto │ └── templates │ │ └── doc.gen.go.tmpl ├── concat │ ├── templates │ │ ├── static.txt.tmpl │ │ └── concat.txt.tmpl │ ├── proto │ │ ├── Eric.proto │ │ ├── arnold.proto │ │ └── Francis.proto │ ├── output │ │ ├── concat.txt │ │ └── static.txt │ └── Makefile ├── arithmetics │ ├── proto │ │ └── arithmetics.proto │ ├── output │ │ └── arithmetics │ ├── templates │ │ └── arithmetics.tmpl │ └── Makefile ├── enum │ ├── templates │ │ └── enum.txt.tmpl │ ├── output │ │ └── enum.txt │ ├── proto │ │ └── sample.proto │ └── Makefile ├── sitemap │ ├── Makefile │ ├── sitemap.proto │ ├── sitemap.xml.tmpl │ └── sitemap.xml ├── k8s │ ├── gen │ │ └── nginx │ │ │ ├── svc.yaml │ │ │ └── dpl.yaml │ ├── nginx.proto │ ├── templates │ │ └── {{.File.Package}} │ │ │ ├── svc.yaml.tmpl │ │ │ └── dpl.yaml.tmpl │ └── Makefile ├── import │ ├── proto │ │ ├── common.proto │ │ └── article.proto │ ├── Makefile │ ├── output │ │ ├── output.go │ │ └── models │ │ │ ├── common │ │ │ └── common.pb.go │ │ │ └── article │ │ │ └── article.pb.go │ └── templates │ │ └── output.go.tmpl ├── helpers │ ├── Makefile │ ├── helpers.proto │ ├── example.txt │ └── example.txt.tmpl ├── time │ ├── Makefile │ ├── output │ │ └── time.go │ ├── proto │ │ └── time.proto │ └── templates │ │ └── time.go.tmpl ├── flow │ ├── Makefile │ ├── protos │ │ └── test.proto │ ├── templates │ │ └── %7B%7B.File.Package%7D%7D │ │ │ └── %7B%7B.File.Package%7D%7D_grpc_js.js.tmpl │ └── output │ │ └── test │ │ └── test_grpc_js.js └── single-package-mode │ ├── proto │ ├── aaa │ │ └── aaa.proto │ └── bbb │ │ └── bbb.proto │ ├── output │ ├── bbb │ │ ├── service.go │ │ └── bbb.pb.go │ └── aaa │ │ └── aaa.pb.go │ ├── Makefile │ └── templates │ └── %7B%7B.File.Name%7Cdir%7D%7D │ └── service.go.tmpl ├── .bazelignore ├── renovate.json ├── slides ├── slides.pdf ├── assets │ ├── wc.png │ └── session-wc.png └── README.md ├── assets ├── web-editor.jpg └── assets ├── .kazelcfg.json ├── .gitignore ├── external ├── BUILD.bazel └── grpc-gateway-visibility.patch ├── Dockerfile ├── .golangci.yml ├── .travis.yml ├── contrib └── homebrew │ └── protoc-gen-gotemplate.rb ├── cmd └── web-editor │ ├── BUILD.bazel │ ├── main.go │ └── static │ └── index.html ├── Makefile ├── WORKSPACE ├── helpers └── BUILD.bazel ├── go.mod ├── LICENSE ├── BUILD.bazel ├── load.bzl ├── go.sum ├── main.go ├── README.md ├── encoder.go └── repos.bzl /examples/go.mod: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.bazelignore: -------------------------------------------------------------------------------- 1 | examples 2 | -------------------------------------------------------------------------------- /examples/go-kit/services/user/gen/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/go-kit/services/session/gen/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/go-kit/services/sprint/gen/README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/dummy/output/static.txt: -------------------------------------------------------------------------------- 1 | This is static text -------------------------------------------------------------------------------- /examples/go-kit/.gitignore: -------------------------------------------------------------------------------- 1 | /vendor/ 2 | /server 3 | -------------------------------------------------------------------------------- /examples/go-generate/Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | go generate 3 | -------------------------------------------------------------------------------- /examples/concat/templates/static.txt.tmpl: -------------------------------------------------------------------------------- 1 | This is static text. -------------------------------------------------------------------------------- /examples/dummy/templates/export.json.tmpl: -------------------------------------------------------------------------------- 1 | {{ . | prettyjson }} -------------------------------------------------------------------------------- /examples/dummy/templates/static.txt.tmpl: -------------------------------------------------------------------------------- 1 | This is static text -------------------------------------------------------------------------------- /examples/go-kit/templates/{{.File.Package}}/gen/README.md.tmpl: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/concat/templates/concat.txt.tmpl: -------------------------------------------------------------------------------- 1 | I'm {{.File.Package}} 2 | -------------------------------------------------------------------------------- /examples/concat/proto/Eric.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package Eric; 3 | -------------------------------------------------------------------------------- /examples/concat/output/concat.txt: -------------------------------------------------------------------------------- 1 | I'm Eric 2 | I'm Francis 3 | I'm Arnold 4 | -------------------------------------------------------------------------------- /examples/concat/proto/arnold.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package Arnold; 3 | -------------------------------------------------------------------------------- /examples/concat/proto/Francis.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package Francis; 3 | -------------------------------------------------------------------------------- /examples/arithmetics/proto/arithmetics.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package Arithmetics; 3 | -------------------------------------------------------------------------------- /examples/concat/output/static.txt: -------------------------------------------------------------------------------- 1 | This is static text.This is static text.This is static text. -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base" 4 | ], 5 | "groupName": "all" 6 | } 7 | -------------------------------------------------------------------------------- /slides/slides.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multiply/protoc-gen-gotemplate/master/slides/slides.pdf -------------------------------------------------------------------------------- /examples/enum/templates/enum.txt.tmpl: -------------------------------------------------------------------------------- 1 | {{range $m := "colors" | getEnumValue .Enum }}-{{$m.Name}} 2 | {{end}} -------------------------------------------------------------------------------- /slides/assets/wc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multiply/protoc-gen-gotemplate/master/slides/assets/wc.png -------------------------------------------------------------------------------- /assets/web-editor.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multiply/protoc-gen-gotemplate/master/assets/web-editor.jpg -------------------------------------------------------------------------------- /examples/sitemap/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | build: 3 | protoc -I. --gotemplate_out=template_dir=.:. sitemap.proto 4 | -------------------------------------------------------------------------------- /examples/arithmetics/output/arithmetics: -------------------------------------------------------------------------------- 1 | 2 | add(1,2) = 3 3 | subtract(1,2) = -1 4 | multiply(1,2) = 2 5 | divide(2,1) = 2 6 | -------------------------------------------------------------------------------- /slides/assets/session-wc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multiply/protoc-gen-gotemplate/master/slides/assets/session-wc.png -------------------------------------------------------------------------------- /examples/enum/output/enum.txt: -------------------------------------------------------------------------------- 1 | -red 2 | -blue 3 | -black 4 | -yellow 5 | -green 6 | -dark 7 | -white 8 | -gray 9 | -orange 10 | -------------------------------------------------------------------------------- /.kazelcfg.json: -------------------------------------------------------------------------------- 1 | { 2 | "AddSourcesRules": true, 3 | "GoPrefix": "moul.io/protoc-gen-gotemplate", 4 | "SkippedPaths": ["^examples/"] 5 | } 6 | -------------------------------------------------------------------------------- /examples/go-generate/example.go: -------------------------------------------------------------------------------- 1 | package example 2 | 3 | //go:generate protoc --go_out=./gen/ example.proto 4 | //go:generate protoc --gotemplate_out=./gen/ example.proto 5 | -------------------------------------------------------------------------------- /examples/k8s/gen/nginx/svc.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: nginx 5 | spec: 6 | selector: 7 | app: nginx 8 | ports: 9 | - name: http 10 | port: 80 -------------------------------------------------------------------------------- /examples/k8s/nginx.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package nginx; 4 | 5 | message Empty { 6 | } 7 | 8 | service Nginx { 9 | rpc Hello(Empty) returns (Empty) {} 10 | rpc World(Empty) returns (Empty) {} 11 | } -------------------------------------------------------------------------------- /examples/import/proto/common.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package common; 4 | 5 | option go_package = "models/common;common"; 6 | 7 | message GetArticle{ 8 | string id = 1; 9 | string tenant = 2; 10 | } 11 | -------------------------------------------------------------------------------- /examples/arithmetics/templates/arithmetics.tmpl: -------------------------------------------------------------------------------- 1 | {{with $a := 1}}{{with $b := 2}} 2 | add(1,2) = {{add $a $b}} 3 | subtract(1,2) = {{subtract $a $b}} 4 | multiply(1,2) = {{multiply $a $b}} 5 | divide(2,1) = {{divide $b $a}} 6 | {{end}}{{end}} -------------------------------------------------------------------------------- /examples/k8s/templates/{{.File.Package}}/svc.yaml.tmpl: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: {{.File.Package}} 5 | spec: 6 | selector: 7 | app: {{.File.Package}} 8 | ports: 9 | - name: http 10 | port: 80 -------------------------------------------------------------------------------- /examples/go-generate/gen/doc.gen.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-gotemplate 2 | package example 3 | 4 | // Methods 5 | // ------- 6 | // * Sum 7 | // 8 | // Message types 9 | // ------------- 10 | // * SumRequest 11 | // * SumReply 12 | -------------------------------------------------------------------------------- /examples/helpers/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | build: 3 | mkdir -p output 4 | protoc -I. --gotemplate_out=template_dir=.,debug=true:. *.proto 5 | 6 | 7 | .PHONY: re 8 | re: clean build 9 | 10 | 11 | .PHONY: clean 12 | clean: 13 | rm -rf output 14 | -------------------------------------------------------------------------------- /examples/dummy/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | build: 3 | mkdir -p output 4 | protoc -I. --gotemplate_out=template_dir=templates,debug=true:output *.proto 5 | 6 | 7 | .PHONY: re 8 | re: clean build 9 | 10 | 11 | .PHONY: clean 12 | clean: 13 | rm -rf output 14 | -------------------------------------------------------------------------------- /examples/time/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | build: 3 | mkdir -p output 4 | protoc -I. --gotemplate_out=template_dir=templates,debug=true:output proto/*.proto 5 | 6 | 7 | .PHONY: re 8 | re: clean build 9 | 10 | 11 | .PHONY: clean 12 | clean: 13 | rm -rf output 14 | -------------------------------------------------------------------------------- /examples/enum/proto/sample.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package Sample; 3 | 4 | enum Colors { 5 | red = 0; 6 | blue = 1; 7 | black = 2; 8 | yellow = 3; 9 | green = 4; 10 | dark = 5; 11 | white = 6; 12 | gray = 7; 13 | orange = 8; 14 | } -------------------------------------------------------------------------------- /examples/flow/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | build: 3 | mkdir -p output 4 | protoc -I. --gotemplate_out=template_dir=templates,debug=true:output ./protos/*.proto 5 | 6 | 7 | .PHONY: re 8 | re: clean build 9 | 10 | 11 | .PHONY: clean 12 | clean: 13 | rm -rf output 14 | -------------------------------------------------------------------------------- /examples/concat/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | build: 3 | mkdir -p output 4 | protoc -I. --gotemplate_out=template_dir=templates,debug=true,all=true:output proto/*.proto 5 | 6 | 7 | .PHONY: re 8 | re: clean build 9 | 10 | 11 | .PHONY: clean 12 | clean: 13 | rm -rf output 14 | -------------------------------------------------------------------------------- /examples/enum/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | build: 3 | mkdir -p output 4 | protoc -I. --gotemplate_out=template_dir=templates,debug=true,all=true:output proto/*.proto 5 | 6 | 7 | .PHONY: re 8 | re: clean build 9 | 10 | 11 | .PHONY: clean 12 | clean: 13 | rm -rf output 14 | -------------------------------------------------------------------------------- /examples/arithmetics/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | build: 3 | mkdir -p output 4 | protoc -I. --gotemplate_out=template_dir=templates,debug=true,all=true:output proto/*.proto 5 | 6 | 7 | .PHONY: re 8 | re: clean build 9 | 10 | 11 | .PHONY: clean 12 | clean: 13 | rm -rf output 14 | -------------------------------------------------------------------------------- /examples/time/output/time.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-gotemplate 2 | package foo 3 | 4 | import ( 5 | "github.com/golang/protobuf/ptypes/timestamp" 6 | ) 7 | 8 | type Repository interface { 9 | GetFoo(timestamp *timestamp.Timestamp) (*timestamp.Timestamp, error) 10 | } 11 | -------------------------------------------------------------------------------- /examples/go-generate/example.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package example; 4 | 5 | service Sum { 6 | rpc Sum(SumRequest) returns (SumReply) {}; 7 | } 8 | 9 | message SumRequest { 10 | int32 a = 1; 11 | int32 b = 2; 12 | } 13 | 14 | message SumReply { 15 | int32 c = 1; 16 | } -------------------------------------------------------------------------------- /examples/sitemap/sitemap.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package sitemap; 4 | 5 | service DummyService { 6 | rpc Posts(Request) returns (Response) {} 7 | rpc Authors(Request) returns (Response) {} 8 | rpc Comments(Request) returns (Response) {} 9 | } 10 | 11 | message Request {} 12 | message Response {} -------------------------------------------------------------------------------- /examples/single-package-mode/proto/aaa/aaa.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | option go_package = "moul.io/protoc-gen-gotemplate/examples/single-package-mode/output/aaa"; 4 | 5 | package the.aaa.package; 6 | 7 | message AaaRequest { 8 | string blah = 1; 9 | } 10 | message AaaReply { 11 | string error = 1; 12 | } 13 | -------------------------------------------------------------------------------- /examples/time/proto/time.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package foo; 4 | 5 | import "google/protobuf/timestamp.proto"; 6 | 7 | message GetFooRequest { google.protobuf.Timestamp timestamp = 1;} 8 | message GetFooResponse { string result = 1;} 9 | 10 | service foosvc { 11 | rpc GetFoo (GetFooRequest) returns (GetFooResponse){} 12 | } -------------------------------------------------------------------------------- /examples/go-generate/templates/doc.gen.go.tmpl: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-gotemplate 2 | package {{.File.Package}} 3 | 4 | // Methods 5 | // ------- 6 | {{- range .Service.Method}} 7 | // * {{.Name}} 8 | {{- end}} 9 | // 10 | // Message types 11 | // ------------- 12 | {{- range .File.MessageType}} 13 | // * {{.Name}} 14 | {{- end}} 15 | -------------------------------------------------------------------------------- /examples/k8s/Makefile: -------------------------------------------------------------------------------- 1 | SOURCES := $(shell find . -name "*.proto" -not -path ./vendor/\*) 2 | 3 | TARGETS_K8S := $(foreach source, $(SOURCES), $(source)_k8s) 4 | 5 | .PHONY: build 6 | build: $(TARGETS_K8S) 7 | 8 | $(TARGETS_K8S): %_k8s: 9 | @mkdir -p $(dir $*)gen 10 | protoc $(PROTOC_OPTS) --gotemplate_out=debug=true,template_dir=./templates:$(dir $*)gen "$*" -------------------------------------------------------------------------------- /examples/go-kit/services/session/session.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package session; 4 | 5 | service SessionService { 6 | rpc Login(LoginRequest) returns (LoginResponse) {} 7 | } 8 | 9 | message LoginRequest { 10 | string username = 1; 11 | string password = 2; 12 | } 13 | 14 | message LoginResponse { 15 | string token = 1; 16 | string err_msg = 2; 17 | } 18 | -------------------------------------------------------------------------------- /examples/sitemap/sitemap.xml.tmpl: -------------------------------------------------------------------------------- 1 | 2 | {{range .Service.Method}} 3 | 4 | /{{.Name | lower}} 5 | 0.5 6 | monthly 7 | {{now | date "2006-01-02"}} 8 | {{end}} 9 | 10 | -------------------------------------------------------------------------------- /examples/k8s/gen/nginx/dpl.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: extensions/v1beta1 2 | kind: Deployment 3 | metadata: 4 | name: nginx 5 | labels: 6 | method: Hello-World-nginx 7 | spec: 8 | replicas: 3 9 | template: 10 | metadata: 11 | labels: 12 | app: nginx 13 | spec: 14 | containers: 15 | - name: nginx 16 | image: nginx 17 | ports: 18 | - containerPort: 80 -------------------------------------------------------------------------------- /assets/assets: -------------------------------------------------------------------------------- 1 | /Users/moul/go/src/moul.io/protoc-gen-gotemplate/assets: 2 | total used in directory 552 available 9223372036849978910 3 | drwxr-xr-x 4 moul staff 128 Dec 9 11:31 . 4 | lrwxr-xr-x 1 moul staff 33 Dec 9 11:31 .#web-editor.jpg -> moul@manfred-spacegray.local.9471 5 | drwxr-xr-x 21 moul staff 672 Sep 13 18:05 .. 6 | -rw-r--r--@ 1 moul staff 280357 Oct 26 2017 web-editor.jpg 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | vendor/**/.travis.yml 2 | 3 | /protoc-gen-gotemplate 4 | 5 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 6 | *.o 7 | *.a 8 | *.so 9 | 10 | # Folders 11 | _obj 12 | _test 13 | 14 | # Architecture specific extensions/prefixes 15 | *.[568vq] 16 | [568vq].out 17 | 18 | *.cgo1.go 19 | *.cgo2.c 20 | _cgo_defun.c 21 | _cgo_gotypes.go 22 | _cgo_export.* 23 | 24 | _testmain.go 25 | 26 | *.exe 27 | *.test 28 | *.prof 29 | 30 | bazel-* 31 | -------------------------------------------------------------------------------- /external/BUILD.bazel: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files([ 4 | "grpc-gateway-visibility.patch", 5 | ]) 6 | 7 | filegroup( 8 | name = "package-srcs", 9 | srcs = glob(["**"]), 10 | tags = ["automanaged"], 11 | visibility = ["//visibility:private"], 12 | ) 13 | 14 | filegroup( 15 | name = "all-srcs", 16 | srcs = [":package-srcs"], 17 | tags = ["automanaged"], 18 | visibility = ["//visibility:public"], 19 | ) 20 | -------------------------------------------------------------------------------- /examples/go-kit/services/session/service.go: -------------------------------------------------------------------------------- 1 | package sessionsvc 2 | 3 | import ( 4 | "fmt" 5 | 6 | "golang.org/x/net/context" 7 | 8 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/session/gen/pb" 9 | ) 10 | 11 | type Service struct{} 12 | 13 | func New() pb.SessionServiceServer { 14 | return &Service{} 15 | } 16 | 17 | func (svc *Service) Login(ctx context.Context, in *pb.LoginRequest) (*pb.LoginResponse, error) { 18 | return nil, fmt.Errorf("not implemented") 19 | } 20 | -------------------------------------------------------------------------------- /examples/k8s/templates/{{.File.Package}}/dpl.yaml.tmpl: -------------------------------------------------------------------------------- 1 | apiVersion: extensions/v1beta1 2 | kind: Deployment 3 | metadata: 4 | name: {{.File.Package}} 5 | labels: 6 | method: {{range .Service.Method}}{{.Name}}-{{end}}{{.File.Package}} 7 | spec: 8 | replicas: 3 9 | template: 10 | metadata: 11 | labels: 12 | app: {{.File.Package}} 13 | spec: 14 | containers: 15 | - name: nginx 16 | image: nginx 17 | ports: 18 | - containerPort: 80 -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM znly/protoc:0.3.0 2 | 3 | ENV GOPATH=/go \ 4 | PATH=/go/bin:${PATH} 5 | 6 | # Install deps and common tools 7 | RUN apk --update add make git go rsync libc-dev \ 8 | && go get -u golang.org/x/tools/cmd/goimports 9 | 10 | # Install protoc-gen-gotemplate 11 | COPY . /go/src/moul.io/protoc-gen-gotemplate 12 | WORKDIR /go/src/moul.io/protoc-gen-gotemplate 13 | RUN git remote set-url origin https://github.com/moul/protoc-gen-gotemplate 14 | RUN go install . ./cmd/web-editor 15 | -------------------------------------------------------------------------------- /examples/single-package-mode/proto/bbb/bbb.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package the.bbb.package; 4 | 5 | option go_package = "moul.io/protoc-gen-gotemplate/examples/single-package-mode/output/bbb"; 6 | 7 | import "aaa/aaa.proto"; 8 | 9 | service BbbService { 10 | rpc Aaa(the.aaa.package.AaaRequest) returns (the.aaa.package.AaaReply); 11 | rpc Bbb(BbbRequest) returns (BbbReply); 12 | } 13 | 14 | message BbbRequest { 15 | bool enable = 1; 16 | } 17 | message BbbReply { 18 | bool done = 1; 19 | } 20 | -------------------------------------------------------------------------------- /examples/helpers/helpers.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package dummy; 4 | 5 | option go_package = "moul.io/protoc-gen-gotemplate/examples/helpers"; 6 | 7 | message Dummy1 { 8 | float aaa = 1; 9 | string bbb = 2; 10 | int32 ccc = 3; 11 | int64 ddd = 4; 12 | repeated string eee = 5; 13 | } 14 | 15 | message Dummy2 { 16 | float fff = 1; 17 | Dummy1 ggg = 2; 18 | } 19 | 20 | message Dummy3 {} 21 | 22 | service DummyService { 23 | rpc Hhh(Dummy1) returns (Dummy2) {} 24 | rpc Iii(Dummy2) returns (Dummy1) {} 25 | } 26 | -------------------------------------------------------------------------------- /external/grpc-gateway-visibility.patch: -------------------------------------------------------------------------------- 1 | diff --git protoc-gen-grpc-gateway/descriptor/BUILD.bazel protoc-gen-grpc-gateway/descriptor/BUILD.bazel 2 | index cfbdc27..631f5c8 100644 3 | --- protoc-gen-grpc-gateway/descriptor/BUILD.bazel 4 | +++ protoc-gen-grpc-gateway/descriptor/BUILD.bazel 5 | @@ -1,6 +1,6 @@ 6 | load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") 7 | 8 | -package(default_visibility = ["//:generators"]) 9 | +package(default_visibility = ["//visibility:public"]) 10 | 11 | go_library( 12 | name = "go_default_library", 13 | -------------------------------------------------------------------------------- /examples/time/templates/time.go.tmpl: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-gotemplate 2 | package {{.File.Package}} 3 | 4 | import ( 5 | "github.com/golang/protobuf/ptypes/timestamp" 6 | ) 7 | 8 | type Repository interface { 9 | {{range $m := .Service.Method}}{{with $t := $m.InputType | getMessageType $.File}} {{$m.Name}}({{range $f := $t.Field}}{{$f.Name|lowerCamelCase}} {{$f| goTypeWithPackage }} {{end}}) ({{with $out := $m.OutputType | getMessageType $.File}}{{range $f := $out.Field}}{{$f | goTypeWithPackage}}, {{end}}{{end}} error){{end}}{{end}} 10 | } -------------------------------------------------------------------------------- /examples/import/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | build: 3 | mkdir -p output 4 | 5 | # generate pb.go inluding imported proto 6 | protoc --go_out=Mproto/common.proto=moul.io/protoc-gen-gotemplate/examples/import/output/models/common:./output proto/article.proto 7 | protoc --go_out=,plugins=grpc:./output proto/common.proto 8 | 9 | # build our go file based on our template 10 | protoc -I. --gotemplate_out=template_dir=templates,debug=true:output proto/article.proto 11 | 12 | .PHONY: re 13 | re: clean build 14 | 15 | 16 | .PHONY: clean 17 | clean: 18 | rm -rf output 19 | -------------------------------------------------------------------------------- /examples/dummy/dummy.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package dummy; 4 | 5 | message Dummy1 { 6 | float aaa = 1; 7 | string bbb = 2; 8 | int32 ccc = 3; 9 | int64 ddd = 4; 10 | repeated string eee = 5; 11 | } 12 | 13 | message Dummy2 { 14 | float fff = 1; 15 | Dummy1 ggg = 2; 16 | } 17 | 18 | message Dummy3 {} 19 | 20 | service DummyService { 21 | rpc Hhh(Dummy1) returns (Dummy2) {} 22 | rpc Iii(Dummy2) returns (Dummy1) {} 23 | } 24 | 25 | /* 26 | service DummyService2 { 27 | rpc Jjj(Dummy2) returns (Dummy2) {} 28 | } 29 | 30 | service DummyService3 { 31 | } 32 | */ -------------------------------------------------------------------------------- /examples/go-kit/glide.yaml: -------------------------------------------------------------------------------- 1 | package: moul.io/protoc-gen-gotemplate/examples/go-kit 2 | import: 3 | - package: github.com/go-kit/kit 4 | subpackages: 5 | - auth/jwt 6 | - endpoint 7 | - log 8 | - transport/grpc 9 | - transport/http 10 | - package: github.com/golang/protobuf 11 | subpackages: 12 | - proto 13 | version: c9c7427a2a70d2eb3bafa0ab2dc163e45f143317 14 | - package: github.com/gorilla/handlers 15 | - package: golang.org/x/net 16 | subpackages: 17 | - context 18 | - http2 19 | version: a6577fac2d73be281a500b310739095313165611 20 | - package: google.golang.org/grpc 21 | -------------------------------------------------------------------------------- /examples/single-package-mode/output/bbb/service.go: -------------------------------------------------------------------------------- 1 | // file generated with protoc-gen-gotemplate 2 | package bbb 3 | 4 | import ( 5 | "fmt" 6 | 7 | "golang.org/x/net/context" 8 | "moul.io/protoc-gen-gotemplate/examples/single-package-mode/output/aaa" 9 | ) 10 | 11 | type Service struct{} 12 | 13 | func (service Service) Aaa(ctx context.Context, input *aaa.AaaRequest) (*aaa.AaaReply, error) { 14 | return nil, fmt.Errorf("method not implemented") 15 | } 16 | 17 | func (service Service) Bbb(ctx context.Context, input *BbbRequest) (*BbbReply, error) { 18 | return nil, fmt.Errorf("method not implemented") 19 | } 20 | -------------------------------------------------------------------------------- /examples/go-kit/services/user/user.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package user; 4 | 5 | service UserService { 6 | rpc CreateUser(CreateUserRequest) returns (CreateUserResponse) {} 7 | rpc GetUser(GetUserRequest) returns (GetUserResponse) {} 8 | } 9 | 10 | message CreateUserRequest { 11 | string name = 1; 12 | } 13 | message CreateUserResponse { 14 | User user = 1; 15 | string err_msg = 2; 16 | } 17 | 18 | message GetUserRequest { 19 | string id = 1; 20 | } 21 | message GetUserResponse { 22 | User user = 1; 23 | string err_msg = 2; 24 | } 25 | 26 | message User { 27 | string id = 1; 28 | string name = 2; 29 | } -------------------------------------------------------------------------------- /examples/sitemap/sitemap.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | /posts 5 | 0.5 6 | monthly 7 | 2017-05-19 8 | 9 | 10 | /authors 11 | 0.5 12 | monthly 13 | 2017-05-19 14 | 15 | 16 | /comments 17 | 0.5 18 | monthly 19 | 2017-05-19 20 | 21 | 22 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | run: 2 | deadline: 1m 3 | tests: false 4 | #skip-files: 5 | # - ".*\\.gen\\.go" 6 | 7 | linters-settings: 8 | golint: 9 | min-confidence: 0 10 | maligned: 11 | suggest-new: true 12 | goconst: 13 | min-len: 5 14 | min-occurrences: 4 15 | misspell: 16 | locale: US 17 | 18 | linters: 19 | disable-all: true 20 | enable: 21 | - goconst 22 | - misspell 23 | - deadcode 24 | - misspell 25 | - structcheck 26 | - errcheck 27 | - unused 28 | - varcheck 29 | - staticcheck 30 | - unconvert 31 | - gofmt 32 | - goimports 33 | - golint 34 | - ineffassign 35 | -------------------------------------------------------------------------------- /examples/go-kit/services/user/service.go: -------------------------------------------------------------------------------- 1 | package usersvc 2 | 3 | import ( 4 | "fmt" 5 | 6 | "golang.org/x/net/context" 7 | 8 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/user/gen/pb" 9 | ) 10 | 11 | type Service struct{} 12 | 13 | func New() pb.UserServiceServer { return &Service{} } 14 | 15 | func (svc *Service) CreateUser(ctx context.Context, in *pb.CreateUserRequest) (*pb.CreateUserResponse, error) { 16 | return nil, fmt.Errorf("not implemented") 17 | } 18 | 19 | func (svc *Service) GetUser(ctx context.Context, in *pb.GetUserRequest) (*pb.GetUserResponse, error) { 20 | return nil, fmt.Errorf("not implemented") 21 | } 22 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | go: 1.11.x 3 | go_import_path: moul.io/protoc-gen-gotemplate 4 | install: 5 | - go get github.com/Masterminds/glide 6 | - wget https://raw.githubusercontent.com/grpc-ecosystem/grpc-gateway/v1.5.0/.travis/install-protoc.sh && chmod +x install-protoc.sh && ./install-protoc.sh 3.4.0 7 | - go get -u github.com/golang/protobuf/protoc-gen-go 8 | - go get github.com/securego/gosec/cmd/gosec/... 9 | - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s v1.12.2 10 | script: 11 | - make install 12 | - make test 13 | - PATH=$PATH:$(pwd)/bin make lint 14 | cache: 15 | directories: 16 | - $HOME/local 17 | env: 18 | global: 19 | - "PATH=$PATH:$HOME/local/bin" -------------------------------------------------------------------------------- /examples/import/proto/article.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package company; 4 | 5 | option go_package = "models/article;article"; 6 | 7 | import "proto/common.proto"; 8 | 9 | message GetArticleRequest { 10 | common.GetArticle getarticle = 1; 11 | } 12 | 13 | 14 | message GetArticleResponse { 15 | Article article = 1; 16 | 17 | message Storage { 18 | string code = 1; 19 | } 20 | // The generated output should write []*GetArticleResponse_Storage.Storage for this field. 21 | repeated Storage storages = 2; 22 | } 23 | 24 | message Article{ 25 | string id = 1; 26 | string name = 2; 27 | } 28 | 29 | service articlesvc { 30 | rpc GetArticle (GetArticleRequest) returns (GetArticleResponse){} 31 | } -------------------------------------------------------------------------------- /examples/single-package-mode/Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: re 2 | re: clean build test 3 | 4 | .PHONY: build 5 | build: 6 | @mkdir -p output 7 | 8 | @# proto-gen-go 9 | protoc -I./proto --go_out=plugins=grpc:output proto/aaa/aaa.proto 10 | protoc -I./proto --go_out=plugins=grpc:output proto/bbb/bbb.proto 11 | @rm -rf output/aaa output/bbb 12 | @mv output/moul.io/protoc-gen-gotemplate/examples/single-package-mode/output/* output/ 13 | @rm -rf output/github.com 14 | 15 | @# protoc-gen-gotemplate 16 | protoc -I./proto --gotemplate_out=template_dir=templates,single-package-mode=true:output proto/bbb/bbb.proto 17 | gofmt -w . 18 | 19 | .PHONY: test 20 | test: 21 | go test -i ./output/... 22 | go test -v ./output/... 23 | 24 | .PHONY: clean 25 | clean: 26 | rm -rf output 27 | -------------------------------------------------------------------------------- /contrib/homebrew/protoc-gen-gotemplate.rb: -------------------------------------------------------------------------------- 1 | require "language/go" 2 | 3 | class ProtocGenGotemplate < Formula 4 | desc "protocol generator + golang text/template (protobuf)" 5 | homepage "https://github.com/moul/protoc-gen-gotemplate" 6 | url "https://github.com/moul/protoc-gen-gotemplate/archive/v1.0.0.tar.gz" 7 | sha256 "1ff57cd8513f1e871cf71dc8f2099bf64204af0df1b7397370827083e95bbb82" 8 | head "https://github.com/moul/protoc-gen-gotemplate.git" 9 | 10 | depends_on "go" => :build 11 | 12 | def install 13 | ENV["GOPATH"] = buildpath 14 | ENV["GOBIN"] = buildpath 15 | ENV["GO15VENDOREXPERIMENT"] = "1" 16 | (buildpath/"src/github.com/moul/protoc-gen-gotemplate").install Dir["*"] 17 | 18 | system "go", "build", "-o", "#{bin}/protoc-gen-gotemplate", "-v", "github.com/moul/protoc-gen-gotemplate" 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /examples/go-kit/services/sprint/service.go: -------------------------------------------------------------------------------- 1 | package sprintsvc 2 | 3 | import ( 4 | "fmt" 5 | 6 | "golang.org/x/net/context" 7 | 8 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/sprint/gen/pb" 9 | ) 10 | 11 | type Service struct{} 12 | 13 | func New() pb.SprintServiceServer { 14 | return &Service{} 15 | } 16 | 17 | func (svc *Service) AddSprint(ctx context.Context, in *pb.AddSprintRequest) (*pb.AddSprintResponse, error) { 18 | return nil, fmt.Errorf("not implemented") 19 | } 20 | 21 | func (svc *Service) CloseSprint(ctx context.Context, in *pb.CloseSprintRequest) (*pb.CloseSprintResponse, error) { 22 | return nil, fmt.Errorf("not implemented") 23 | } 24 | 25 | func (svc *Service) GetSprint(ctx context.Context, in *pb.GetSprintRequest) (*pb.GetSprintResponse, error) { 26 | return nil, fmt.Errorf("not implemented") 27 | } 28 | -------------------------------------------------------------------------------- /examples/single-package-mode/templates/%7B%7B.File.Name%7Cdir%7D%7D/service.go.tmpl: -------------------------------------------------------------------------------- 1 | // file generated with protoc-gen-gotemplate 2 | package {{.File.Name | dir}} 3 | 4 | {{- $file := .File}} 5 | {{- $currentFile := $file.Name | getProtoFile}} 6 | 7 | import ( 8 | "fmt" 9 | 10 | "golang.org/x/net/context" 11 | 12 | {{- range .File.Dependency}} 13 | {{- $dependency := . | getProtoFile}} 14 | {{$dependency.GoPkg}} 15 | {{end}} 16 | ) 17 | 18 | type Service struct {} 19 | 20 | {{- range .Service.Method}} 21 | {{- $in := .InputType | getMessageType $file}} 22 | {{- $out := .OutputType | getMessageType $file}} 23 | func (service Service) {{.Name}}(ctx context.Context, input *{{$in.GoType $currentFile.GoPkg.Path}}) (*{{$out.GoType $currentFile.GoPkg.Path}}, error) { 24 | return nil, fmt.Errorf("method not implemented") 25 | } 26 | {{end}} 27 | -------------------------------------------------------------------------------- /examples/go-kit/services/sprint/sprint.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package sprint; 4 | 5 | service SprintService { 6 | rpc AddSprint(AddSprintRequest) returns (AddSprintResponse) {} 7 | rpc CloseSprint(CloseSprintRequest) returns (CloseSprintResponse) {} 8 | rpc GetSprint(GetSprintRequest) returns (GetSprintResponse) {} 9 | } 10 | 11 | message AddSprintRequest { 12 | string name = 1; 13 | } 14 | message AddSprintResponse { 15 | Sprint sprint = 1; 16 | string err_msg = 2; 17 | } 18 | 19 | message CloseSprintRequest { 20 | string id = 1; 21 | } 22 | message CloseSprintResponse { 23 | string err_msg = 1; 24 | } 25 | 26 | message GetSprintRequest { 27 | string id = 1; 28 | } 29 | message GetSprintResponse { 30 | Sprint sprint = 1; 31 | string err_msg = 2; 32 | } 33 | 34 | message Sprint { 35 | string id = 1; 36 | uint32 created_at = 2; 37 | string name = 3; 38 | } -------------------------------------------------------------------------------- /examples/import/output/output.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-gotemplate 2 | package company 3 | 4 | import ( 5 | "context" 6 | 7 | "moul.io/protoc-gen-gotemplate/examples/import/output/models/article" 8 | "moul.io/protoc-gen-gotemplate/examples/import/output/models/common" 9 | ) 10 | 11 | type Repository interface { 12 | GetArticle(getarticle *common.GetArticle) (*company.Article, []*company.Storage, error) 13 | } 14 | 15 | // ------------------------- Public SDK ----------------------------- 16 | 17 | // GetArticle : proto: missing extension proto: missing extension 18 | func (sdk *Sdk) GetArticle(ctx context.Context, 19 | getarticle *article.GetArticle, token, requestID string) (article *article.Article, storages []*article.GetArticleResponse_Storage, err error) { 20 | 21 | out := &pb.GetArticleResponse{} 22 | _ = out 23 | 24 | return out.Article, out.Storages, nil 25 | 26 | } 27 | -------------------------------------------------------------------------------- /cmd/web-editor/BUILD.bazel: -------------------------------------------------------------------------------- 1 | load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") 2 | 3 | go_library( 4 | name = "go_default_library", 5 | srcs = ["main.go"], 6 | importpath = "moul.io/protoc-gen-gotemplate/cmd/web-editor", 7 | visibility = ["//visibility:private"], 8 | deps = [ 9 | "@com_github_gorilla_handlers//:go_default_library", 10 | "@com_github_gorilla_mux//:go_default_library", 11 | ], 12 | ) 13 | 14 | go_binary( 15 | name = "web-editor", 16 | embed = [":go_default_library"], 17 | visibility = ["//visibility:public"], 18 | ) 19 | 20 | filegroup( 21 | name = "package-srcs", 22 | srcs = glob(["**"]), 23 | tags = ["automanaged"], 24 | visibility = ["//visibility:private"], 25 | ) 26 | 27 | filegroup( 28 | name = "all-srcs", 29 | srcs = [":package-srcs"], 30 | tags = ["automanaged"], 31 | visibility = ["//visibility:public"], 32 | ) 33 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | build: 3 | go build -v -i -o protoc-gen-gotemplate . 4 | 5 | .PHONY: install 6 | install: 7 | go install . 8 | go install ./cmd/web-editor 9 | 10 | .PHONY: test 11 | test: install 12 | cd examples/time && make 13 | cd examples/enum && make 14 | cd examples/import && make 15 | cd examples/dummy && make 16 | cd examples/flow && make 17 | cd examples/concat && make 18 | cd examples/flow && make 19 | cd examples/sitemap && make 20 | cd examples/go-generate && make 21 | # cd examples/single-package-mode && make 22 | cd examples/helpers && make 23 | cd examples/arithmetics && make 24 | # cd examples/go-kit && make 25 | 26 | .PHONY: docker.build 27 | docker.build: 28 | docker build --pull -t moul/protoc-gen-gotemplate . 29 | 30 | .PHONY: docker.push 31 | docker.push: docker.build 32 | docker push moul/protoc-gen-gotemplate 33 | 34 | .PHONY: lint 35 | lint: 36 | golangci-lint run --verbose . ./helpers ./cmd/... 37 | -------------------------------------------------------------------------------- /examples/go-kit/Makefile: -------------------------------------------------------------------------------- 1 | SOURCES := $(shell find . -name "*.proto" -not -path ./vendor/\*) 2 | 3 | TARGETS_GO := $(foreach source, $(SOURCES), $(source)_go) 4 | TARGETS_TMPL := $(foreach source, $(SOURCES), $(source)_tmpl) 5 | 6 | service_name = $(word 2,$(subst /, ,$1)) 7 | 8 | .PHONY: build 9 | build: server 10 | 11 | server: $(TARGETS_GO) $(TARGETS_TMPL) 12 | glide install 13 | go build -o server . 14 | 15 | $(TARGETS_GO): %_go: 16 | protoc --go_out=plugins=grpc:. "$*" 17 | @mkdir -p services/$(call service_name,$*)/gen/pb 18 | @mv ./services/$(call service_name,$*)/$(call service_name,$*).pb.go ./services/$(call service_name,$*)/gen/pb/pb.go 19 | 20 | $(TARGETS_TMPL): %_tmpl: 21 | @mkdir -p $(dir $*)gen 22 | protoc -I. --gotemplate_out=destination_dir=services/$(call service_name,$*)/gen,template_dir=templates:services "$*" 23 | @rm -rf services/services # need to investigate why this directory is created 24 | gofmt -w $(dir $*)gen 25 | -------------------------------------------------------------------------------- /WORKSPACE: -------------------------------------------------------------------------------- 1 | workspace(name = "protoc_gen_gotemplate") 2 | 3 | load("//:load.bzl", "repositories") 4 | 5 | repositories() 6 | 7 | load("@io_k8s_repo_infra//:load.bzl", _repo_infra_repos = "repositories") 8 | 9 | _repo_infra_repos() 10 | 11 | load("@io_k8s_repo_infra//:repos.bzl", "configure") 12 | 13 | configure( 14 | go_version = "1.13.4", 15 | ) 16 | 17 | load("//:repos.bzl", "go_repositories") 18 | 19 | go_repositories() 20 | 21 | load("@rules_proto//proto:repositories.bzl", "rules_proto_dependencies", "rules_proto_toolchains") 22 | 23 | rules_proto_dependencies() 24 | 25 | rules_proto_toolchains() 26 | 27 | load("@com_google_protobuf//:protobuf_deps.bzl", "protobuf_deps") 28 | 29 | protobuf_deps() 30 | 31 | load("@io_bazel_rules_docker//repositories:repositories.bzl", container_repositories = "repositories") 32 | 33 | container_repositories() 34 | 35 | load("@io_bazel_rules_docker//go:image.bzl", _go_image_repos = "repositories") 36 | 37 | _go_image_repos() 38 | -------------------------------------------------------------------------------- /helpers/BUILD.bazel: -------------------------------------------------------------------------------- 1 | load("@io_bazel_rules_go//go:def.bzl", "go_library") 2 | 3 | go_library( 4 | name = "go_default_library", 5 | srcs = ["helpers.go"], 6 | importpath = "moul.io/protoc-gen-gotemplate/helpers", 7 | visibility = ["//visibility:public"], 8 | deps = [ 9 | "@com_github_golang_protobuf//proto:go_default_library", 10 | "@com_github_grpc_ecosystem_grpc_gateway//protoc-gen-grpc-gateway/descriptor:go_default_library", 11 | "@com_github_huandu_xstrings//:go_default_library", 12 | "@com_github_masterminds_sprig//:go_default_library", 13 | "@go_googleapis//google/api:annotations_go_proto", 14 | "@io_bazel_rules_go//proto/wkt:descriptor_go_proto", 15 | ], 16 | ) 17 | 18 | filegroup( 19 | name = "package-srcs", 20 | srcs = glob(["**"]), 21 | tags = ["automanaged"], 22 | visibility = ["//visibility:private"], 23 | ) 24 | 25 | filegroup( 26 | name = "all-srcs", 27 | srcs = [":package-srcs"], 28 | tags = ["automanaged"], 29 | visibility = ["//visibility:public"], 30 | ) 31 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module moul.io/protoc-gen-gotemplate 2 | 3 | go 1.13 4 | 5 | require ( 6 | github.com/Masterminds/semver v1.2.2 // indirect 7 | github.com/Masterminds/sprig v2.14.1+incompatible 8 | github.com/aokoli/goutils v0.0.0-20170502144750-e57d01ace047 // indirect 9 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b // indirect 10 | github.com/golang/protobuf v0.0.0-20161117033126-8ee79997227b 11 | github.com/gorilla/context v0.0.0-20160226214623-1ea25387ff6f // indirect 12 | github.com/gorilla/handlers v0.0.0-20161028133215-e1b2144f2167 13 | github.com/gorilla/mux v1.5.0 14 | github.com/grpc-ecosystem/grpc-gateway v1.2.2 15 | github.com/huandu/xstrings v0.0.0-20151130125119-3959339b3335 16 | github.com/imdario/mergo v0.0.0-20171009183408-7fe0c75c13ab // indirect 17 | github.com/satori/go.uuid v1.1.0 // indirect 18 | github.com/stretchr/testify v1.3.0 // indirect 19 | golang.org/x/crypto v0.0.0-20170516161655-0fe963104e9d // indirect 20 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 // indirect 21 | google.golang.org/genproto v0.0.0-20170517234824-bb3573be0c48 22 | gopkg.in/yaml.v2 v2.2.2 // indirect 23 | ) 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Manfred Touron 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /examples/go-kit/services/session/gen/endpoints/endpoints.go: -------------------------------------------------------------------------------- 1 | package session_endpoints 2 | 3 | import ( 4 | context "context" 5 | "fmt" 6 | 7 | "github.com/go-kit/kit/endpoint" 8 | oldcontext "golang.org/x/net/context" 9 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/session/gen/pb" 10 | ) 11 | 12 | var _ = endpoint.Chain 13 | var _ = fmt.Errorf 14 | var _ = context.Background 15 | 16 | type StreamEndpoint func(server interface{}, req interface{}) (err error) 17 | 18 | type Endpoints struct { 19 | LoginEndpoint endpoint.Endpoint 20 | } 21 | 22 | func (e *Endpoints) Login(ctx oldcontext.Context, in *pb.LoginRequest) (*pb.LoginResponse, error) { 23 | out, err := e.LoginEndpoint(ctx, in) 24 | if err != nil { 25 | return &pb.LoginResponse{ErrMsg: err.Error()}, err 26 | } 27 | return out.(*pb.LoginResponse), err 28 | } 29 | 30 | func MakeLoginEndpoint(svc pb.SessionServiceServer) endpoint.Endpoint { 31 | return func(ctx context.Context, request interface{}) (interface{}, error) { 32 | req := request.(*pb.LoginRequest) 33 | rep, err := svc.Login(ctx, req) 34 | if err != nil { 35 | return &pb.LoginResponse{ErrMsg: err.Error()}, err 36 | } 37 | return rep, nil 38 | } 39 | } 40 | 41 | func MakeEndpoints(svc pb.SessionServiceServer) Endpoints { 42 | return Endpoints{ 43 | 44 | LoginEndpoint: MakeLoginEndpoint(svc), 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /examples/go-kit/services/session/gen/client/grpc/client.go: -------------------------------------------------------------------------------- 1 | package session_clientgrpc 2 | 3 | import ( 4 | context "context" 5 | 6 | jwt "github.com/go-kit/kit/auth/jwt" 7 | "github.com/go-kit/kit/endpoint" 8 | "github.com/go-kit/kit/log" 9 | grpctransport "github.com/go-kit/kit/transport/grpc" 10 | "google.golang.org/grpc" 11 | 12 | endpoints "moul.io/protoc-gen-gotemplate/examples/go-kit/services/session/gen/endpoints" 13 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/session/gen/pb" 14 | ) 15 | 16 | func New(conn *grpc.ClientConn, logger log.Logger) pb.SessionServiceServer { 17 | 18 | var loginEndpoint endpoint.Endpoint 19 | { 20 | loginEndpoint = grpctransport.NewClient( 21 | conn, 22 | "session.SessionService", 23 | "Login", 24 | EncodeLoginRequest, 25 | DecodeLoginResponse, 26 | pb.LoginResponse{}, 27 | append([]grpctransport.ClientOption{}, grpctransport.ClientBefore(jwt.FromGRPCContext()))..., 28 | ).Endpoint() 29 | } 30 | 31 | return &endpoints.Endpoints{ 32 | 33 | LoginEndpoint: loginEndpoint, 34 | } 35 | } 36 | 37 | func EncodeLoginRequest(_ context.Context, request interface{}) (interface{}, error) { 38 | req := request.(*pb.LoginRequest) 39 | return req, nil 40 | } 41 | 42 | func DecodeLoginResponse(_ context.Context, grpcResponse interface{}) (interface{}, error) { 43 | response := grpcResponse.(*pb.LoginResponse) 44 | return response, nil 45 | } 46 | -------------------------------------------------------------------------------- /examples/go-kit/glide.lock: -------------------------------------------------------------------------------- 1 | hash: e225ab17b49f8d6601b2bd813d43ad34ee04380d29c278c11919efd454c7b2d7 2 | updated: 2017-03-16T17:03:34.437968115+01:00 3 | imports: 4 | - name: github.com/dgrijalva/jwt-go 5 | version: 2268707a8f0843315e2004ee4f1d021dc08baedf 6 | - name: github.com/go-kit/kit 7 | version: fadad6fffe0466b19df9efd9acde5c9a52df5fa4 8 | subpackages: 9 | - auth/jwt 10 | - endpoint 11 | - log 12 | - transport/grpc 13 | - transport/http 14 | - name: github.com/go-logfmt/logfmt 15 | version: 390ab7935ee28ec6b286364bba9b4dd6410cb3d5 16 | - name: github.com/go-stack/stack 17 | version: 100eb0c0a9c5b306ca2fb4f165df21d80ada4b82 18 | - name: github.com/golang/protobuf 19 | version: c9c7427a2a70d2eb3bafa0ab2dc163e45f143317 20 | subpackages: 21 | - proto 22 | - name: github.com/gorilla/handlers 23 | version: 3a5767ca75ece5f7f1440b1d16975247f8d8b221 24 | - name: github.com/kr/logfmt 25 | version: b84e30acd515aadc4b783ad4ff83aff3299bdfe0 26 | - name: golang.org/x/net 27 | version: a6577fac2d73be281a500b310739095313165611 28 | subpackages: 29 | - context 30 | - context/ctxhttp 31 | - http2 32 | - http2/hpack 33 | - idna 34 | - internal/timeseries 35 | - lex/httplex 36 | - trace 37 | - name: google.golang.org/grpc 38 | version: 777daa17ff9b5daef1cfdf915088a2ada3332bf0 39 | subpackages: 40 | - codes 41 | - credentials 42 | - grpclog 43 | - internal 44 | - metadata 45 | - naming 46 | - peer 47 | - transport 48 | testImports: [] 49 | -------------------------------------------------------------------------------- /examples/go-kit/services/session/gen/transports/http/http.go: -------------------------------------------------------------------------------- 1 | package session_httptransport 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "log" 7 | "net/http" 8 | 9 | gokit_endpoint "github.com/go-kit/kit/endpoint" 10 | httptransport "github.com/go-kit/kit/transport/http" 11 | endpoints "moul.io/protoc-gen-gotemplate/examples/go-kit/services/session/gen/endpoints" 12 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/session/gen/pb" 13 | ) 14 | 15 | var _ = log.Printf 16 | var _ = gokit_endpoint.Chain 17 | var _ = httptransport.NewClient 18 | 19 | func MakeLoginHandler(svc pb.SessionServiceServer, endpoint gokit_endpoint.Endpoint) *httptransport.Server { 20 | return httptransport.NewServer( 21 | endpoint, 22 | decodeLoginRequest, 23 | encodeResponse, 24 | []httptransport.ServerOption{}..., 25 | ) 26 | } 27 | 28 | func decodeLoginRequest(ctx context.Context, r *http.Request) (interface{}, error) { 29 | var req pb.LoginRequest 30 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil { 31 | return nil, err 32 | } 33 | return &req, nil 34 | } 35 | 36 | func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { 37 | return json.NewEncoder(w).Encode(response) 38 | } 39 | 40 | func RegisterHandlers(svc pb.SessionServiceServer, mux *http.ServeMux, endpoints endpoints.Endpoints) error { 41 | 42 | log.Println("new HTTP endpoint: \"/Login\" (service=Session)") 43 | mux.Handle("/Login", MakeLoginHandler(svc, endpoints.LoginEndpoint)) 44 | 45 | return nil 46 | } 47 | -------------------------------------------------------------------------------- /BUILD.bazel: -------------------------------------------------------------------------------- 1 | # gazelle:exclude examples 2 | # gazelle:prefix moul.io/protoc-gen-gotemplate 3 | 4 | load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library") 5 | 6 | package(default_visibility = ["//visibility:public"]) 7 | 8 | exports_files([ 9 | "README.md", 10 | "go.mod", 11 | "go.sum", 12 | ]) 13 | 14 | filegroup( 15 | name = "package-srcs", 16 | srcs = glob( 17 | ["**"], 18 | exclude = [ 19 | "bazel-*/**", 20 | ".git/**", 21 | ], 22 | ), 23 | tags = ["automanaged"], 24 | visibility = ["//visibility:private"], 25 | ) 26 | 27 | filegroup( 28 | name = "all-srcs", 29 | srcs = [ 30 | ":package-srcs", 31 | "//cmd/web-editor:all-srcs", 32 | "//external:all-srcs", 33 | "//helpers:all-srcs", 34 | ], 35 | tags = ["automanaged"], 36 | visibility = ["//visibility:public"], 37 | ) 38 | 39 | go_library( 40 | name = "go_default_library", 41 | srcs = [ 42 | "encoder.go", 43 | "main.go", 44 | ], 45 | importpath = "moul.io/protoc-gen-gotemplate", 46 | deps = [ 47 | "//helpers:go_default_library", 48 | "@com_github_golang_protobuf//proto:go_default_library", 49 | "@com_github_golang_protobuf//protoc-gen-go/generator:go_default_library_gen", 50 | "@com_github_grpc_ecosystem_grpc_gateway//protoc-gen-grpc-gateway/descriptor:go_default_library", 51 | "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto", 52 | "@io_bazel_rules_go//proto/wkt:descriptor_go_proto", 53 | ], 54 | ) 55 | 56 | go_binary( 57 | name = "protoc-gen-gotemplate", 58 | embed = [":go_default_library"], 59 | ) 60 | -------------------------------------------------------------------------------- /examples/flow/protos/test.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package test; 4 | 5 | option go_package = "github.com/united-drivers/models/go/test;testpb"; 6 | 7 | service TestService { 8 | rpc TestNoStream(TestNoStreamRequest) returns (TestNoStreamReply); 9 | rpc TestStreamRequest(stream TestStreamRequestRequest) returns (TestStreamRequestReply); 10 | rpc TestStreamReply(TestStreamReplyRequest) returns (stream TestStreamReplyReply); 11 | rpc TestStreamBoth(stream TestStreamBothRequest) returns (stream TestStreamBothReply); 12 | } 13 | 14 | enum TestEnum { 15 | ELEMENT_A = 0; 16 | ELEMENT_B = 1; 17 | } 18 | 19 | message TestMessage { 20 | string a = 1; 21 | int32 b = 2; 22 | int64 c = 3; 23 | float d = 4; 24 | double e = 5; 25 | repeated string n = 14; 26 | repeated int32 o = 15; 27 | repeated int64 p = 16; 28 | repeated float q = 17; 29 | repeated double r = 18; 30 | 31 | message TestNestedMessage { 32 | string s = 1; 33 | int32 t = 2; 34 | } 35 | enum TestNestedEnum { 36 | ELEMENT_C = 0; 37 | ELEMENT_D = 1; 38 | } 39 | 40 | TestEnum u = 19; 41 | TestNestedEnum v = 20; 42 | repeated TestNestedMessage w = 21; 43 | } 44 | 45 | message TestNoStreamRequest { TestMessage message = 1; } 46 | message TestNoStreamReply { TestMessage message = 1; string err_msg = 2; } 47 | message TestStreamRequestRequest { TestMessage message = 1; } 48 | message TestStreamRequestReply { TestMessage message = 1; string err_msg = 2; } 49 | message TestStreamReplyRequest { TestMessage message = 1; } 50 | message TestStreamReplyReply { TestMessage message = 1; string err_msg = 2; } 51 | message TestStreamBothRequest { TestMessage message = 1; } 52 | message TestStreamBothReply { TestMessage message = 1; string err_msg = 2; } 53 | -------------------------------------------------------------------------------- /examples/go-kit/services/session/gen/transports/grpc/grpc.go: -------------------------------------------------------------------------------- 1 | package session_grpctransport 2 | 3 | import ( 4 | context "context" 5 | "fmt" 6 | 7 | grpctransport "github.com/go-kit/kit/transport/grpc" 8 | oldcontext "golang.org/x/net/context" 9 | 10 | endpoints "moul.io/protoc-gen-gotemplate/examples/go-kit/services/session/gen/endpoints" 11 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/session/gen/pb" 12 | ) 13 | 14 | // avoid import errors 15 | var _ = fmt.Errorf 16 | 17 | func MakeGRPCServer(endpoints endpoints.Endpoints) pb.SessionServiceServer { 18 | var options []grpctransport.ServerOption 19 | _ = options 20 | return &grpcServer{ 21 | 22 | login: grpctransport.NewServer( 23 | endpoints.LoginEndpoint, 24 | decodeRequest, 25 | encodeLoginResponse, 26 | options..., 27 | ), 28 | } 29 | } 30 | 31 | type grpcServer struct { 32 | login grpctransport.Handler 33 | } 34 | 35 | func (s *grpcServer) Login(ctx oldcontext.Context, req *pb.LoginRequest) (*pb.LoginResponse, error) { 36 | _, rep, err := s.login.ServeGRPC(ctx, req) 37 | if err != nil { 38 | return nil, err 39 | } 40 | return rep.(*pb.LoginResponse), nil 41 | } 42 | 43 | func encodeLoginResponse(ctx context.Context, response interface{}) (interface{}, error) { 44 | resp := response.(*pb.LoginResponse) 45 | return resp, nil 46 | } 47 | 48 | func decodeRequest(ctx context.Context, grpcReq interface{}) (interface{}, error) { 49 | return grpcReq, nil 50 | } 51 | 52 | type streamHandler interface { 53 | Do(server interface{}, req interface{}) (err error) 54 | } 55 | 56 | type server struct { 57 | e endpoints.StreamEndpoint 58 | } 59 | 60 | func (s server) Do(server interface{}, req interface{}) (err error) { 61 | if err := s.e(server, req); err != nil { 62 | return err 63 | } 64 | return nil 65 | } 66 | -------------------------------------------------------------------------------- /examples/import/templates/output.go.tmpl: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-gotemplate 2 | {{- $file := .File}} 3 | package {{.File.Package}} 4 | 5 | import ( 6 | "moul.io/protoc-gen-gotemplate/examples/import/output/models/article" 7 | "moul.io/protoc-gen-gotemplate/examples/import/output/models/common" 8 | ) 9 | 10 | type Repository interface { 11 | {{range $m := .Service.Method}}{{with $t := $m.InputType | getMessageType $.File}} {{$m.Name}}({{range $f := $t.Field}}{{$f.Name|lowerCamelCase}} {{$f| goTypeWithPackage }} {{end}}) ({{with $out := $m.OutputType | getMessageType $.File}}{{range $f := $out.Field}}{{$f | goTypeWithPackage}}, {{end}}{{end}} error){{end}}{{end}} 12 | } 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | // ------------------------- Public SDK ----------------------------- 21 | {{$pkg := "pb"}} 22 | 23 | 24 | {{range $m := .Service.Method}} 25 | {{with $t := $m.InputType | getMessageType $.File}} 26 | {{if and (not $m.ServerStreaming) (not $m.ClientStreaming)}} 27 | {{/* ----------------------------- nominal case ---------------------------- */}} 28 | // {{$m.Name}} : {{$m | httpVerb}} {{$m | httpPath}} 29 | func (sdk *Sdk) {{$m.Name}}(ctx context.Context, {{if $t.OneofDecl}} req *{{$pkg}}.{{$m.Name}}Request,{{else}}{{range $f := $t.Field}} 30 | {{$f.Name|lowerCamelCase}} {{$f| goTypeWithGoPackage $.File}},{{end}}{{end}} token, requestID string)({{with $out := $m.OutputType | getMessageType $.File}}{{range $f := $out.Field}}{{$f.Name|lowerCamelCase}} {{$f | goTypeWithGoPackage $.File}}, {{end}}{{end}}err error) { 31 | 32 | out := &{{$pkg}}.{{$m.Name}}Response{} 33 | _ = out 34 | 35 | {{with $out := $m.OutputType | getMessageType $.File}} 36 | return {{range $f := $out.Field}}out.{{$f.Name|camelCase}}, {{end}}nil 37 | {{end}} {{/* with */}} 38 | } 39 | 40 | {{end}} {{/* streaming ifs */}} 41 | {{end}}{{end}} {{/* range with */}} 42 | -------------------------------------------------------------------------------- /examples/go-kit/templates/{{.File.Package}}/gen/transports/http/http.go.tmpl: -------------------------------------------------------------------------------- 1 | package {{.File.Package}}_httptransport 2 | 3 | {{$file := .File}} 4 | 5 | import ( 6 | "log" 7 | "net/http" 8 | "encoding/json" 9 | "context" 10 | 11 | pb "{{cat .GoPWD "/" .DestinationDir | nospace | clean}}/pb" 12 | gokit_endpoint "github.com/go-kit/kit/endpoint" 13 | httptransport "github.com/go-kit/kit/transport/http" 14 | endpoints "{{cat .GoPWD "/" .DestinationDir | nospace | clean}}/endpoints" 15 | ) 16 | 17 | var _ = log.Printf 18 | var _ = gokit_endpoint.Chain 19 | var _ = httptransport.NewClient 20 | 21 | 22 | {{range .Service.Method}} 23 | {{if and (not .ServerStreaming) (not .ClientStreaming)}} 24 | func Make{{.Name}}Handler(svc pb.{{$file.Package | title}}ServiceServer, endpoint gokit_endpoint.Endpoint) *httptransport.Server { 25 | return httptransport.NewServer( 26 | endpoint, 27 | decode{{.Name}}Request, 28 | encodeResponse, 29 | []httptransport.ServerOption{}..., 30 | ) 31 | } 32 | 33 | func decode{{.Name}}Request(ctx context.Context, r *http.Request) (interface{}, error) { 34 | var req pb.{{.InputType | splitArray "." | last}} 35 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil { 36 | return nil, err 37 | } 38 | return &req, nil 39 | } 40 | {{end}} 41 | {{end}} 42 | 43 | func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { 44 | return json.NewEncoder(w).Encode(response) 45 | } 46 | 47 | func RegisterHandlers(svc pb.{{$file.Package | title}}ServiceServer, mux *http.ServeMux, endpoints endpoints.Endpoints) error { 48 | {{range .Service.Method}} 49 | {{if and (not .ServerStreaming) (not .ClientStreaming)}} 50 | log.Println("new HTTP endpoint: \"/{{.Name}}\" (service={{$file.Package | title}})") 51 | mux.Handle("/{{.Name}}", Make{{.Name}}Handler(svc, endpoints.{{.Name}}Endpoint)) 52 | {{end}} 53 | {{end}} 54 | return nil 55 | } 56 | -------------------------------------------------------------------------------- /examples/go-kit/templates/{{.File.Package}}/gen/client/grpc/client.go.tmpl: -------------------------------------------------------------------------------- 1 | package {{.File.Package}}_clientgrpc 2 | 3 | import ( 4 | context "context" 5 | 6 | "github.com/go-kit/kit/log" 7 | "google.golang.org/grpc" 8 | grpctransport "github.com/go-kit/kit/transport/grpc" 9 | "github.com/go-kit/kit/endpoint" 10 | jwt "github.com/go-kit/kit/auth/jwt" 11 | 12 | pb "{{cat .GoPWD "/" .DestinationDir | nospace | clean}}/pb" 13 | endpoints "{{cat .GoPWD "/" .DestinationDir | nospace | clean}}/endpoints" 14 | ) 15 | 16 | {{$file:=.File}} 17 | 18 | func New(conn *grpc.ClientConn, logger log.Logger) pb.{{.File.Package | title}}ServiceServer { 19 | {{range .Service.Method}} 20 | {{if and (not .ServerStreaming) (not .ClientStreaming)}} 21 | var {{.Name | lower}}Endpoint endpoint.Endpoint 22 | { 23 | {{.Name | lower}}Endpoint = grpctransport.NewClient( 24 | conn, 25 | "{{$file.Package}}.{{$file.Package | title}}Service", 26 | "{{.Name}}", 27 | Encode{{.Name}}Request, 28 | Decode{{.Name}}Response, 29 | pb.{{.Name}}Response{}, 30 | append([]grpctransport.ClientOption{}, grpctransport.ClientBefore(jwt.FromGRPCContext()))..., 31 | ).Endpoint() 32 | } 33 | {{end}} 34 | {{end}} 35 | 36 | return &endpoints.Endpoints { 37 | {{range .Service.Method}} 38 | {{if and (not .ServerStreaming) (not .ClientStreaming)}} 39 | {{.Name | title}}Endpoint: {{.Name | lower}}Endpoint, 40 | {{end}} 41 | {{end}} 42 | } 43 | } 44 | 45 | {{range .Service.Method}} 46 | {{if and (not .ServerStreaming) (not .ClientStreaming)}} 47 | func Encode{{.Name}}Request(_ context.Context, request interface{}) (interface{}, error) { 48 | req := request.(*pb.{{.Name}}Request) 49 | return req, nil 50 | } 51 | 52 | func Decode{{.Name}}Response(_ context.Context, grpcResponse interface{}) (interface{}, error) { 53 | response := grpcResponse.(*pb.{{.Name}}Response) 54 | return response, nil 55 | } 56 | {{end}} 57 | {{end}} 58 | -------------------------------------------------------------------------------- /examples/go-kit/services/user/gen/endpoints/endpoints.go: -------------------------------------------------------------------------------- 1 | package user_endpoints 2 | 3 | import ( 4 | context "context" 5 | "fmt" 6 | 7 | "github.com/go-kit/kit/endpoint" 8 | oldcontext "golang.org/x/net/context" 9 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/user/gen/pb" 10 | ) 11 | 12 | var _ = endpoint.Chain 13 | var _ = fmt.Errorf 14 | var _ = context.Background 15 | 16 | type StreamEndpoint func(server interface{}, req interface{}) (err error) 17 | 18 | type Endpoints struct { 19 | CreateUserEndpoint endpoint.Endpoint 20 | 21 | GetUserEndpoint endpoint.Endpoint 22 | } 23 | 24 | func (e *Endpoints) CreateUser(ctx oldcontext.Context, in *pb.CreateUserRequest) (*pb.CreateUserResponse, error) { 25 | out, err := e.CreateUserEndpoint(ctx, in) 26 | if err != nil { 27 | return &pb.CreateUserResponse{ErrMsg: err.Error()}, err 28 | } 29 | return out.(*pb.CreateUserResponse), err 30 | } 31 | 32 | func (e *Endpoints) GetUser(ctx oldcontext.Context, in *pb.GetUserRequest) (*pb.GetUserResponse, error) { 33 | out, err := e.GetUserEndpoint(ctx, in) 34 | if err != nil { 35 | return &pb.GetUserResponse{ErrMsg: err.Error()}, err 36 | } 37 | return out.(*pb.GetUserResponse), err 38 | } 39 | 40 | func MakeCreateUserEndpoint(svc pb.UserServiceServer) endpoint.Endpoint { 41 | return func(ctx context.Context, request interface{}) (interface{}, error) { 42 | req := request.(*pb.CreateUserRequest) 43 | rep, err := svc.CreateUser(ctx, req) 44 | if err != nil { 45 | return &pb.CreateUserResponse{ErrMsg: err.Error()}, err 46 | } 47 | return rep, nil 48 | } 49 | } 50 | 51 | func MakeGetUserEndpoint(svc pb.UserServiceServer) endpoint.Endpoint { 52 | return func(ctx context.Context, request interface{}) (interface{}, error) { 53 | req := request.(*pb.GetUserRequest) 54 | rep, err := svc.GetUser(ctx, req) 55 | if err != nil { 56 | return &pb.GetUserResponse{ErrMsg: err.Error()}, err 57 | } 58 | return rep, nil 59 | } 60 | } 61 | 62 | func MakeEndpoints(svc pb.UserServiceServer) Endpoints { 63 | return Endpoints{ 64 | 65 | CreateUserEndpoint: MakeCreateUserEndpoint(svc), 66 | 67 | GetUserEndpoint: MakeGetUserEndpoint(svc), 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /examples/go-kit/services/user/gen/client/grpc/client.go: -------------------------------------------------------------------------------- 1 | package user_clientgrpc 2 | 3 | import ( 4 | context "context" 5 | 6 | jwt "github.com/go-kit/kit/auth/jwt" 7 | "github.com/go-kit/kit/endpoint" 8 | "github.com/go-kit/kit/log" 9 | grpctransport "github.com/go-kit/kit/transport/grpc" 10 | "google.golang.org/grpc" 11 | 12 | endpoints "moul.io/protoc-gen-gotemplate/examples/go-kit/services/user/gen/endpoints" 13 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/user/gen/pb" 14 | ) 15 | 16 | func New(conn *grpc.ClientConn, logger log.Logger) pb.UserServiceServer { 17 | 18 | var createuserEndpoint endpoint.Endpoint 19 | { 20 | createuserEndpoint = grpctransport.NewClient( 21 | conn, 22 | "user.UserService", 23 | "CreateUser", 24 | EncodeCreateUserRequest, 25 | DecodeCreateUserResponse, 26 | pb.CreateUserResponse{}, 27 | append([]grpctransport.ClientOption{}, grpctransport.ClientBefore(jwt.FromGRPCContext()))..., 28 | ).Endpoint() 29 | } 30 | 31 | var getuserEndpoint endpoint.Endpoint 32 | { 33 | getuserEndpoint = grpctransport.NewClient( 34 | conn, 35 | "user.UserService", 36 | "GetUser", 37 | EncodeGetUserRequest, 38 | DecodeGetUserResponse, 39 | pb.GetUserResponse{}, 40 | append([]grpctransport.ClientOption{}, grpctransport.ClientBefore(jwt.FromGRPCContext()))..., 41 | ).Endpoint() 42 | } 43 | 44 | return &endpoints.Endpoints{ 45 | 46 | CreateUserEndpoint: createuserEndpoint, 47 | 48 | GetUserEndpoint: getuserEndpoint, 49 | } 50 | } 51 | 52 | func EncodeCreateUserRequest(_ context.Context, request interface{}) (interface{}, error) { 53 | req := request.(*pb.CreateUserRequest) 54 | return req, nil 55 | } 56 | 57 | func DecodeCreateUserResponse(_ context.Context, grpcResponse interface{}) (interface{}, error) { 58 | response := grpcResponse.(*pb.CreateUserResponse) 59 | return response, nil 60 | } 61 | 62 | func EncodeGetUserRequest(_ context.Context, request interface{}) (interface{}, error) { 63 | req := request.(*pb.GetUserRequest) 64 | return req, nil 65 | } 66 | 67 | func DecodeGetUserResponse(_ context.Context, grpcResponse interface{}) (interface{}, error) { 68 | response := grpcResponse.(*pb.GetUserResponse) 69 | return response, nil 70 | } 71 | -------------------------------------------------------------------------------- /examples/go-kit/services/user/gen/transports/http/http.go: -------------------------------------------------------------------------------- 1 | package user_httptransport 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "log" 7 | "net/http" 8 | 9 | gokit_endpoint "github.com/go-kit/kit/endpoint" 10 | httptransport "github.com/go-kit/kit/transport/http" 11 | endpoints "moul.io/protoc-gen-gotemplate/examples/go-kit/services/user/gen/endpoints" 12 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/user/gen/pb" 13 | ) 14 | 15 | var _ = log.Printf 16 | var _ = gokit_endpoint.Chain 17 | var _ = httptransport.NewClient 18 | 19 | func MakeCreateUserHandler(svc pb.UserServiceServer, endpoint gokit_endpoint.Endpoint) *httptransport.Server { 20 | return httptransport.NewServer( 21 | endpoint, 22 | decodeCreateUserRequest, 23 | encodeResponse, 24 | []httptransport.ServerOption{}..., 25 | ) 26 | } 27 | 28 | func decodeCreateUserRequest(ctx context.Context, r *http.Request) (interface{}, error) { 29 | var req pb.CreateUserRequest 30 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil { 31 | return nil, err 32 | } 33 | return &req, nil 34 | } 35 | 36 | func MakeGetUserHandler(svc pb.UserServiceServer, endpoint gokit_endpoint.Endpoint) *httptransport.Server { 37 | return httptransport.NewServer( 38 | endpoint, 39 | decodeGetUserRequest, 40 | encodeResponse, 41 | []httptransport.ServerOption{}..., 42 | ) 43 | } 44 | 45 | func decodeGetUserRequest(ctx context.Context, r *http.Request) (interface{}, error) { 46 | var req pb.GetUserRequest 47 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil { 48 | return nil, err 49 | } 50 | return &req, nil 51 | } 52 | 53 | func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { 54 | return json.NewEncoder(w).Encode(response) 55 | } 56 | 57 | func RegisterHandlers(svc pb.UserServiceServer, mux *http.ServeMux, endpoints endpoints.Endpoints) error { 58 | 59 | log.Println("new HTTP endpoint: \"/CreateUser\" (service=User)") 60 | mux.Handle("/CreateUser", MakeCreateUserHandler(svc, endpoints.CreateUserEndpoint)) 61 | 62 | log.Println("new HTTP endpoint: \"/GetUser\" (service=User)") 63 | mux.Handle("/GetUser", MakeGetUserHandler(svc, endpoints.GetUserEndpoint)) 64 | 65 | return nil 66 | } 67 | -------------------------------------------------------------------------------- /examples/go-kit/services/user/gen/transports/grpc/grpc.go: -------------------------------------------------------------------------------- 1 | package user_grpctransport 2 | 3 | import ( 4 | context "context" 5 | "fmt" 6 | 7 | grpctransport "github.com/go-kit/kit/transport/grpc" 8 | oldcontext "golang.org/x/net/context" 9 | 10 | endpoints "moul.io/protoc-gen-gotemplate/examples/go-kit/services/user/gen/endpoints" 11 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/user/gen/pb" 12 | ) 13 | 14 | // avoid import errors 15 | var _ = fmt.Errorf 16 | 17 | func MakeGRPCServer(endpoints endpoints.Endpoints) pb.UserServiceServer { 18 | var options []grpctransport.ServerOption 19 | _ = options 20 | return &grpcServer{ 21 | 22 | createuser: grpctransport.NewServer( 23 | endpoints.CreateUserEndpoint, 24 | decodeRequest, 25 | encodeCreateUserResponse, 26 | options..., 27 | ), 28 | 29 | getuser: grpctransport.NewServer( 30 | endpoints.GetUserEndpoint, 31 | decodeRequest, 32 | encodeGetUserResponse, 33 | options..., 34 | ), 35 | } 36 | } 37 | 38 | type grpcServer struct { 39 | createuser grpctransport.Handler 40 | 41 | getuser grpctransport.Handler 42 | } 43 | 44 | func (s *grpcServer) CreateUser(ctx oldcontext.Context, req *pb.CreateUserRequest) (*pb.CreateUserResponse, error) { 45 | _, rep, err := s.createuser.ServeGRPC(ctx, req) 46 | if err != nil { 47 | return nil, err 48 | } 49 | return rep.(*pb.CreateUserResponse), nil 50 | } 51 | 52 | func encodeCreateUserResponse(ctx context.Context, response interface{}) (interface{}, error) { 53 | resp := response.(*pb.CreateUserResponse) 54 | return resp, nil 55 | } 56 | 57 | func (s *grpcServer) GetUser(ctx oldcontext.Context, req *pb.GetUserRequest) (*pb.GetUserResponse, error) { 58 | _, rep, err := s.getuser.ServeGRPC(ctx, req) 59 | if err != nil { 60 | return nil, err 61 | } 62 | return rep.(*pb.GetUserResponse), nil 63 | } 64 | 65 | func encodeGetUserResponse(ctx context.Context, response interface{}) (interface{}, error) { 66 | resp := response.(*pb.GetUserResponse) 67 | return resp, nil 68 | } 69 | 70 | func decodeRequest(ctx context.Context, grpcReq interface{}) (interface{}, error) { 71 | return grpcReq, nil 72 | } 73 | 74 | type streamHandler interface { 75 | Do(server interface{}, req interface{}) (err error) 76 | } 77 | 78 | type server struct { 79 | e endpoints.StreamEndpoint 80 | } 81 | 82 | func (s server) Do(server interface{}, req interface{}) (err error) { 83 | if err := s.e(server, req); err != nil { 84 | return err 85 | } 86 | return nil 87 | } 88 | -------------------------------------------------------------------------------- /examples/import/output/models/common/common.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: proto/common.proto 3 | 4 | /* 5 | Package common is a generated protocol buffer package. 6 | 7 | It is generated from these files: 8 | proto/common.proto 9 | 10 | It has these top-level messages: 11 | GetArticle 12 | */ 13 | package common 14 | 15 | import proto "github.com/golang/protobuf/proto" 16 | import fmt "fmt" 17 | import math "math" 18 | 19 | // Reference imports to suppress errors if they are not otherwise used. 20 | var _ = proto.Marshal 21 | var _ = fmt.Errorf 22 | var _ = math.Inf 23 | 24 | // This is a compile-time assertion to ensure that this generated file 25 | // is compatible with the proto package it is being compiled against. 26 | // A compilation error at this line likely means your copy of the 27 | // proto package needs to be updated. 28 | const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package 29 | 30 | type GetArticle struct { 31 | Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` 32 | Tenant string `protobuf:"bytes,2,opt,name=tenant" json:"tenant,omitempty"` 33 | } 34 | 35 | func (m *GetArticle) Reset() { *m = GetArticle{} } 36 | func (m *GetArticle) String() string { return proto.CompactTextString(m) } 37 | func (*GetArticle) ProtoMessage() {} 38 | func (*GetArticle) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } 39 | 40 | func (m *GetArticle) GetId() string { 41 | if m != nil { 42 | return m.Id 43 | } 44 | return "" 45 | } 46 | 47 | func (m *GetArticle) GetTenant() string { 48 | if m != nil { 49 | return m.Tenant 50 | } 51 | return "" 52 | } 53 | 54 | func init() { 55 | proto.RegisterType((*GetArticle)(nil), "common.GetArticle") 56 | } 57 | 58 | func init() { proto.RegisterFile("proto/common.proto", fileDescriptor0) } 59 | 60 | var fileDescriptor0 = []byte{ 61 | // 110 bytes of a gzipped FileDescriptorProto 62 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x2a, 0x28, 0xca, 0x2f, 63 | 0xc9, 0xd7, 0x4f, 0xce, 0xcf, 0xcd, 0xcd, 0xcf, 0xd3, 0x03, 0x73, 0x84, 0xd8, 0x20, 0x3c, 0x25, 64 | 0x13, 0x2e, 0x2e, 0xf7, 0xd4, 0x12, 0xc7, 0xa2, 0x92, 0xcc, 0xe4, 0x9c, 0x54, 0x21, 0x3e, 0x2e, 65 | 0xa6, 0xcc, 0x14, 0x09, 0x46, 0x05, 0x46, 0x0d, 0xce, 0x20, 0xa6, 0xcc, 0x14, 0x21, 0x31, 0x2e, 66 | 0xb6, 0x92, 0xd4, 0xbc, 0xc4, 0xbc, 0x12, 0x09, 0x26, 0xb0, 0x18, 0x94, 0xe7, 0x24, 0x16, 0x25, 67 | 0x92, 0x9b, 0x9f, 0x92, 0x9a, 0x53, 0x0c, 0x35, 0xd4, 0x1a, 0x42, 0x25, 0xb1, 0x81, 0x0d, 0x37, 68 | 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x89, 0x5a, 0x1d, 0x73, 0x72, 0x00, 0x00, 0x00, 69 | } 70 | -------------------------------------------------------------------------------- /examples/go-kit/services/sprint/gen/transports/http/http.go: -------------------------------------------------------------------------------- 1 | package sprint_httptransport 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "log" 7 | "net/http" 8 | 9 | gokit_endpoint "github.com/go-kit/kit/endpoint" 10 | httptransport "github.com/go-kit/kit/transport/http" 11 | endpoints "moul.io/protoc-gen-gotemplate/examples/go-kit/services/sprint/gen/endpoints" 12 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/sprint/gen/pb" 13 | ) 14 | 15 | var _ = log.Printf 16 | var _ = gokit_endpoint.Chain 17 | var _ = httptransport.NewClient 18 | 19 | func MakeAddSprintHandler(svc pb.SprintServiceServer, endpoint gokit_endpoint.Endpoint) *httptransport.Server { 20 | return httptransport.NewServer( 21 | endpoint, 22 | decodeAddSprintRequest, 23 | encodeResponse, 24 | []httptransport.ServerOption{}..., 25 | ) 26 | } 27 | 28 | func decodeAddSprintRequest(ctx context.Context, r *http.Request) (interface{}, error) { 29 | var req pb.AddSprintRequest 30 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil { 31 | return nil, err 32 | } 33 | return &req, nil 34 | } 35 | 36 | func MakeCloseSprintHandler(svc pb.SprintServiceServer, endpoint gokit_endpoint.Endpoint) *httptransport.Server { 37 | return httptransport.NewServer( 38 | endpoint, 39 | decodeCloseSprintRequest, 40 | encodeResponse, 41 | []httptransport.ServerOption{}..., 42 | ) 43 | } 44 | 45 | func decodeCloseSprintRequest(ctx context.Context, r *http.Request) (interface{}, error) { 46 | var req pb.CloseSprintRequest 47 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil { 48 | return nil, err 49 | } 50 | return &req, nil 51 | } 52 | 53 | func MakeGetSprintHandler(svc pb.SprintServiceServer, endpoint gokit_endpoint.Endpoint) *httptransport.Server { 54 | return httptransport.NewServer( 55 | endpoint, 56 | decodeGetSprintRequest, 57 | encodeResponse, 58 | []httptransport.ServerOption{}..., 59 | ) 60 | } 61 | 62 | func decodeGetSprintRequest(ctx context.Context, r *http.Request) (interface{}, error) { 63 | var req pb.GetSprintRequest 64 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil { 65 | return nil, err 66 | } 67 | return &req, nil 68 | } 69 | 70 | func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error { 71 | return json.NewEncoder(w).Encode(response) 72 | } 73 | 74 | func RegisterHandlers(svc pb.SprintServiceServer, mux *http.ServeMux, endpoints endpoints.Endpoints) error { 75 | 76 | log.Println("new HTTP endpoint: \"/AddSprint\" (service=Sprint)") 77 | mux.Handle("/AddSprint", MakeAddSprintHandler(svc, endpoints.AddSprintEndpoint)) 78 | 79 | log.Println("new HTTP endpoint: \"/CloseSprint\" (service=Sprint)") 80 | mux.Handle("/CloseSprint", MakeCloseSprintHandler(svc, endpoints.CloseSprintEndpoint)) 81 | 82 | log.Println("new HTTP endpoint: \"/GetSprint\" (service=Sprint)") 83 | mux.Handle("/GetSprint", MakeGetSprintHandler(svc, endpoints.GetSprintEndpoint)) 84 | 85 | return nil 86 | } 87 | -------------------------------------------------------------------------------- /examples/go-kit/templates/{{.File.Package}}/gen/transports/grpc/grpc.go.tmpl: -------------------------------------------------------------------------------- 1 | package {{.File.Package}}_grpctransport 2 | 3 | {{$file := .File}} 4 | 5 | import ( 6 | context "context" 7 | "fmt" 8 | 9 | oldcontext "golang.org/x/net/context" 10 | grpctransport "github.com/go-kit/kit/transport/grpc" 11 | 12 | pb "{{cat .GoPWD "/" .DestinationDir | nospace | clean}}/pb" 13 | endpoints "{{cat .GoPWD "/" .DestinationDir | nospace | clean}}/endpoints" 14 | ) 15 | 16 | // avoid import errors 17 | var _ = fmt.Errorf 18 | 19 | func MakeGRPCServer(endpoints endpoints.Endpoints) pb.{{.File.Package | title}}ServiceServer { 20 | var options []grpctransport.ServerOption 21 | _ = options 22 | return &grpcServer{ 23 | {{range .Service.Method}} 24 | {{if or (.ClientStreaming) (.ServerStreaming)}} 25 | {{.Name | lower}}: &server{ 26 | e: endpoints.{{.Name}}Endpoint, 27 | }, 28 | {{else}} 29 | {{.Name | lower}}: grpctransport.NewServer( 30 | endpoints.{{.Name}}Endpoint, 31 | decodeRequest, 32 | encode{{.Name}}Response, 33 | options..., 34 | ), 35 | {{end}} 36 | {{end}} 37 | } 38 | } 39 | 40 | type grpcServer struct { 41 | {{range .Service.Method}} 42 | {{if or (.ClientStreaming) (.ServerStreaming)}} 43 | {{.Name | lower}} streamHandler 44 | {{else}} 45 | {{.Name | lower}} grpctransport.Handler 46 | {{end}} 47 | {{end}} 48 | } 49 | 50 | {{range .Service.Method}} 51 | {{if .ClientStreaming}} 52 | func (s *grpcServer) {{.Name}}(server pb.{{$file.Package | title}}Service_{{.Name}}Server) error { 53 | return s.{{.Name | lower}}.Do(server, nil) 54 | } 55 | {{else if .ServerStreaming}} 56 | func (s *grpcServer) {{.Name}}(req *pb.{{.Name}}Request, server pb.{{$file.Package | title}}Service_{{.Name}}Server) error { 57 | return s.{{.Name | lower}}.Do(server, req) 58 | } 59 | {{else}} 60 | func (s *grpcServer) {{.Name}}(ctx oldcontext.Context, req *pb.{{.InputType | splitArray "." | last}}) (*pb.{{.OutputType | splitArray "." | last}}, error) { 61 | _, rep, err := s.{{.Name | lower}}.ServeGRPC(ctx, req) 62 | if err != nil { 63 | return nil, err 64 | } 65 | return rep.(*pb.{{.OutputType | splitArray "." | last}}), nil 66 | } 67 | 68 | func encode{{.Name}}Response(ctx context.Context, response interface{}) (interface{}, error) { 69 | resp := response.(*pb.{{.OutputType | splitArray "." | last}}) 70 | return resp, nil 71 | } 72 | {{end}} 73 | {{end}} 74 | 75 | func decodeRequest(ctx context.Context, grpcReq interface{}) (interface{}, error) { 76 | return grpcReq, nil 77 | } 78 | 79 | type streamHandler interface{ 80 | Do(server interface{}, req interface{}) (err error) 81 | } 82 | 83 | type server struct { 84 | e endpoints.StreamEndpoint 85 | } 86 | 87 | func (s server) Do(server interface{}, req interface{}) (err error) { 88 | if err := s.e(server, req); err != nil { 89 | return err 90 | } 91 | return nil 92 | } 93 | -------------------------------------------------------------------------------- /examples/go-kit/services/sprint/gen/endpoints/endpoints.go: -------------------------------------------------------------------------------- 1 | package sprint_endpoints 2 | 3 | import ( 4 | context "context" 5 | "fmt" 6 | 7 | "github.com/go-kit/kit/endpoint" 8 | oldcontext "golang.org/x/net/context" 9 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/sprint/gen/pb" 10 | ) 11 | 12 | var _ = endpoint.Chain 13 | var _ = fmt.Errorf 14 | var _ = context.Background 15 | 16 | type StreamEndpoint func(server interface{}, req interface{}) (err error) 17 | 18 | type Endpoints struct { 19 | AddSprintEndpoint endpoint.Endpoint 20 | 21 | CloseSprintEndpoint endpoint.Endpoint 22 | 23 | GetSprintEndpoint endpoint.Endpoint 24 | } 25 | 26 | func (e *Endpoints) AddSprint(ctx oldcontext.Context, in *pb.AddSprintRequest) (*pb.AddSprintResponse, error) { 27 | out, err := e.AddSprintEndpoint(ctx, in) 28 | if err != nil { 29 | return &pb.AddSprintResponse{ErrMsg: err.Error()}, err 30 | } 31 | return out.(*pb.AddSprintResponse), err 32 | } 33 | 34 | func (e *Endpoints) CloseSprint(ctx oldcontext.Context, in *pb.CloseSprintRequest) (*pb.CloseSprintResponse, error) { 35 | out, err := e.CloseSprintEndpoint(ctx, in) 36 | if err != nil { 37 | return &pb.CloseSprintResponse{ErrMsg: err.Error()}, err 38 | } 39 | return out.(*pb.CloseSprintResponse), err 40 | } 41 | 42 | func (e *Endpoints) GetSprint(ctx oldcontext.Context, in *pb.GetSprintRequest) (*pb.GetSprintResponse, error) { 43 | out, err := e.GetSprintEndpoint(ctx, in) 44 | if err != nil { 45 | return &pb.GetSprintResponse{ErrMsg: err.Error()}, err 46 | } 47 | return out.(*pb.GetSprintResponse), err 48 | } 49 | 50 | func MakeAddSprintEndpoint(svc pb.SprintServiceServer) endpoint.Endpoint { 51 | return func(ctx context.Context, request interface{}) (interface{}, error) { 52 | req := request.(*pb.AddSprintRequest) 53 | rep, err := svc.AddSprint(ctx, req) 54 | if err != nil { 55 | return &pb.AddSprintResponse{ErrMsg: err.Error()}, err 56 | } 57 | return rep, nil 58 | } 59 | } 60 | 61 | func MakeCloseSprintEndpoint(svc pb.SprintServiceServer) endpoint.Endpoint { 62 | return func(ctx context.Context, request interface{}) (interface{}, error) { 63 | req := request.(*pb.CloseSprintRequest) 64 | rep, err := svc.CloseSprint(ctx, req) 65 | if err != nil { 66 | return &pb.CloseSprintResponse{ErrMsg: err.Error()}, err 67 | } 68 | return rep, nil 69 | } 70 | } 71 | 72 | func MakeGetSprintEndpoint(svc pb.SprintServiceServer) endpoint.Endpoint { 73 | return func(ctx context.Context, request interface{}) (interface{}, error) { 74 | req := request.(*pb.GetSprintRequest) 75 | rep, err := svc.GetSprint(ctx, req) 76 | if err != nil { 77 | return &pb.GetSprintResponse{ErrMsg: err.Error()}, err 78 | } 79 | return rep, nil 80 | } 81 | } 82 | 83 | func MakeEndpoints(svc pb.SprintServiceServer) Endpoints { 84 | return Endpoints{ 85 | 86 | AddSprintEndpoint: MakeAddSprintEndpoint(svc), 87 | 88 | CloseSprintEndpoint: MakeCloseSprintEndpoint(svc), 89 | 90 | GetSprintEndpoint: MakeGetSprintEndpoint(svc), 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /examples/go-kit/services/sprint/gen/client/grpc/client.go: -------------------------------------------------------------------------------- 1 | package sprint_clientgrpc 2 | 3 | import ( 4 | context "context" 5 | 6 | jwt "github.com/go-kit/kit/auth/jwt" 7 | "github.com/go-kit/kit/endpoint" 8 | "github.com/go-kit/kit/log" 9 | grpctransport "github.com/go-kit/kit/transport/grpc" 10 | "google.golang.org/grpc" 11 | 12 | endpoints "moul.io/protoc-gen-gotemplate/examples/go-kit/services/sprint/gen/endpoints" 13 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/sprint/gen/pb" 14 | ) 15 | 16 | func New(conn *grpc.ClientConn, logger log.Logger) pb.SprintServiceServer { 17 | 18 | var addsprintEndpoint endpoint.Endpoint 19 | { 20 | addsprintEndpoint = grpctransport.NewClient( 21 | conn, 22 | "sprint.SprintService", 23 | "AddSprint", 24 | EncodeAddSprintRequest, 25 | DecodeAddSprintResponse, 26 | pb.AddSprintResponse{}, 27 | append([]grpctransport.ClientOption{}, grpctransport.ClientBefore(jwt.FromGRPCContext()))..., 28 | ).Endpoint() 29 | } 30 | 31 | var closesprintEndpoint endpoint.Endpoint 32 | { 33 | closesprintEndpoint = grpctransport.NewClient( 34 | conn, 35 | "sprint.SprintService", 36 | "CloseSprint", 37 | EncodeCloseSprintRequest, 38 | DecodeCloseSprintResponse, 39 | pb.CloseSprintResponse{}, 40 | append([]grpctransport.ClientOption{}, grpctransport.ClientBefore(jwt.FromGRPCContext()))..., 41 | ).Endpoint() 42 | } 43 | 44 | var getsprintEndpoint endpoint.Endpoint 45 | { 46 | getsprintEndpoint = grpctransport.NewClient( 47 | conn, 48 | "sprint.SprintService", 49 | "GetSprint", 50 | EncodeGetSprintRequest, 51 | DecodeGetSprintResponse, 52 | pb.GetSprintResponse{}, 53 | append([]grpctransport.ClientOption{}, grpctransport.ClientBefore(jwt.FromGRPCContext()))..., 54 | ).Endpoint() 55 | } 56 | 57 | return &endpoints.Endpoints{ 58 | 59 | AddSprintEndpoint: addsprintEndpoint, 60 | 61 | CloseSprintEndpoint: closesprintEndpoint, 62 | 63 | GetSprintEndpoint: getsprintEndpoint, 64 | } 65 | } 66 | 67 | func EncodeAddSprintRequest(_ context.Context, request interface{}) (interface{}, error) { 68 | req := request.(*pb.AddSprintRequest) 69 | return req, nil 70 | } 71 | 72 | func DecodeAddSprintResponse(_ context.Context, grpcResponse interface{}) (interface{}, error) { 73 | response := grpcResponse.(*pb.AddSprintResponse) 74 | return response, nil 75 | } 76 | 77 | func EncodeCloseSprintRequest(_ context.Context, request interface{}) (interface{}, error) { 78 | req := request.(*pb.CloseSprintRequest) 79 | return req, nil 80 | } 81 | 82 | func DecodeCloseSprintResponse(_ context.Context, grpcResponse interface{}) (interface{}, error) { 83 | response := grpcResponse.(*pb.CloseSprintResponse) 84 | return response, nil 85 | } 86 | 87 | func EncodeGetSprintRequest(_ context.Context, request interface{}) (interface{}, error) { 88 | req := request.(*pb.GetSprintRequest) 89 | return req, nil 90 | } 91 | 92 | func DecodeGetSprintResponse(_ context.Context, grpcResponse interface{}) (interface{}, error) { 93 | response := grpcResponse.(*pb.GetSprintResponse) 94 | return response, nil 95 | } 96 | -------------------------------------------------------------------------------- /examples/go-kit/templates/{{.File.Package}}/gen/endpoints/endpoints.go.tmpl: -------------------------------------------------------------------------------- 1 | package {{.File.Package}}_endpoints 2 | 3 | {{$file := .File}} 4 | 5 | import ( 6 | context "context" 7 | "fmt" 8 | 9 | oldcontext "golang.org/x/net/context" 10 | pb "{{cat .GoPWD "/" .DestinationDir | nospace | clean}}/pb" 11 | "github.com/go-kit/kit/endpoint" 12 | ) 13 | 14 | var _ = endpoint.Chain 15 | var _ = fmt.Errorf 16 | var _ = context.Background 17 | 18 | type StreamEndpoint func(server interface{}, req interface{}) (err error) 19 | 20 | type Endpoints struct { 21 | {{range .Service.Method}} 22 | {{if or (.ClientStreaming) (.ServerStreaming)}} 23 | {{.Name}}Endpoint StreamEndpoint 24 | {{else}} 25 | {{.Name}}Endpoint endpoint.Endpoint 26 | {{end}} 27 | {{end}} 28 | } 29 | 30 | {{range .Service.Method}} 31 | {{if .ServerStreaming}} 32 | {{if .ClientStreaming}} 33 | func (e *Endpoints){{.Name}}(server pb.{{$file.Package | title}}Service_{{.Name}}Server) error { 34 | return fmt.Errorf("not implemented") 35 | } 36 | {{else}} 37 | func (e *Endpoints){{.Name}}(in *pb.{{.Name}}Request, server pb.{{$file.Package | title}}Service_{{.Name}}Server) error { 38 | return fmt.Errorf("not implemented") 39 | } 40 | {{end}} 41 | {{else}} 42 | {{if .ClientStreaming}} 43 | func (e *Endpoints){{.Name}}(server pb.{{$file.Package | title}}Service_{{.Name}}Server) error { 44 | return fmt.Errorf("not implemented") 45 | } 46 | {{else}} 47 | func (e *Endpoints){{.Name}}(ctx oldcontext.Context, in *pb.{{.InputType | splitArray "." | last}}) (*pb.{{.OutputType | splitArray "." | last}}, error) { 48 | out, err := e.{{.Name}}Endpoint(ctx, in) 49 | if err != nil { 50 | return &pb.{{.OutputType | splitArray "." | last}}{ErrMsg: err.Error()}, err 51 | } 52 | return out.(*pb.{{.OutputType | splitArray "." | last}}), err 53 | } 54 | {{end}} 55 | {{end}} 56 | {{end}} 57 | 58 | {{range .Service.Method}} 59 | {{if or (.ServerStreaming) (.ClientStreaming)}} 60 | func Make{{.Name}}Endpoint(svc pb.{{$file.Package | title}}ServiceServer) StreamEndpoint { 61 | return func(server interface{}, request interface{}) error { 62 | {{if .ClientStreaming}} 63 | return svc.{{.Name}}(server.(pb.{{$file.Package | title}}Service_{{.Name}}Server)) 64 | {{else}} 65 | return svc.{{.Name}}(request.(*pb.{{.Name}}Request), server.(pb.{{$file.Package | title}}Service_{{.Name}}Server)) 66 | {{end}} 67 | } 68 | } 69 | {{else}} 70 | func Make{{.Name}}Endpoint(svc pb.{{$file.Package | title}}ServiceServer) endpoint.Endpoint { 71 | return func(ctx context.Context, request interface{}) (interface{}, error) { 72 | req := request.(*pb.{{.InputType | splitArray "." | last}}) 73 | rep, err := svc.{{.Name}}(ctx, req) 74 | if err != nil { 75 | return &pb.{{.OutputType | splitArray "." | last}}{ErrMsg: err.Error()}, err 76 | } 77 | return rep, nil 78 | } 79 | } 80 | {{end}} 81 | {{end}} 82 | 83 | func MakeEndpoints(svc pb.{{.File.Package | title}}ServiceServer) Endpoints { 84 | return Endpoints{ 85 | {{range .Service.Method}} 86 | {{.Name}}Endpoint: Make{{.Name}}Endpoint(svc), 87 | {{end}} 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /examples/go-generate/gen/example.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. 2 | // source: example.proto 3 | // DO NOT EDIT! 4 | 5 | /* 6 | Package example is a generated protocol buffer package. 7 | 8 | It is generated from these files: 9 | example.proto 10 | 11 | It has these top-level messages: 12 | SumRequest 13 | SumReply 14 | */ 15 | package example 16 | 17 | import proto "github.com/golang/protobuf/proto" 18 | import fmt "fmt" 19 | import math "math" 20 | 21 | // Reference imports to suppress errors if they are not otherwise used. 22 | var _ = proto.Marshal 23 | var _ = fmt.Errorf 24 | var _ = math.Inf 25 | 26 | // This is a compile-time assertion to ensure that this generated file 27 | // is compatible with the proto package it is being compiled against. 28 | // A compilation error at this line likely means your copy of the 29 | // proto package needs to be updated. 30 | const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package 31 | 32 | type SumRequest struct { 33 | A int32 `protobuf:"varint,1,opt,name=a" json:"a,omitempty"` 34 | B int32 `protobuf:"varint,2,opt,name=b" json:"b,omitempty"` 35 | } 36 | 37 | func (m *SumRequest) Reset() { *m = SumRequest{} } 38 | func (m *SumRequest) String() string { return proto.CompactTextString(m) } 39 | func (*SumRequest) ProtoMessage() {} 40 | func (*SumRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } 41 | 42 | func (m *SumRequest) GetA() int32 { 43 | if m != nil { 44 | return m.A 45 | } 46 | return 0 47 | } 48 | 49 | func (m *SumRequest) GetB() int32 { 50 | if m != nil { 51 | return m.B 52 | } 53 | return 0 54 | } 55 | 56 | type SumReply struct { 57 | C int32 `protobuf:"varint,1,opt,name=c" json:"c,omitempty"` 58 | } 59 | 60 | func (m *SumReply) Reset() { *m = SumReply{} } 61 | func (m *SumReply) String() string { return proto.CompactTextString(m) } 62 | func (*SumReply) ProtoMessage() {} 63 | func (*SumReply) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } 64 | 65 | func (m *SumReply) GetC() int32 { 66 | if m != nil { 67 | return m.C 68 | } 69 | return 0 70 | } 71 | 72 | func init() { 73 | proto.RegisterType((*SumRequest)(nil), "example.SumRequest") 74 | proto.RegisterType((*SumReply)(nil), "example.SumReply") 75 | } 76 | 77 | func init() { proto.RegisterFile("example.proto", fileDescriptor0) } 78 | 79 | var fileDescriptor0 = []byte{ 80 | // 124 bytes of a gzipped FileDescriptorProto 81 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x4d, 0xad, 0x48, 0xcc, 82 | 0x2d, 0xc8, 0x49, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x87, 0x72, 0x95, 0x34, 0xb8, 83 | 0xb8, 0x82, 0x4b, 0x73, 0x83, 0x52, 0x0b, 0x4b, 0x53, 0x8b, 0x4b, 0x84, 0x78, 0xb8, 0x18, 0x13, 84 | 0x25, 0x18, 0x15, 0x18, 0x35, 0x58, 0x83, 0x18, 0x13, 0x41, 0xbc, 0x24, 0x09, 0x26, 0x08, 0x2f, 85 | 0x49, 0x49, 0x82, 0x8b, 0x03, 0xac, 0xb2, 0x20, 0xa7, 0x12, 0x24, 0x93, 0x0c, 0x53, 0x97, 0x6c, 86 | 0x64, 0xc6, 0xc5, 0x1c, 0x5c, 0x9a, 0x2b, 0xa4, 0x0f, 0xa1, 0x84, 0xf5, 0x60, 0x56, 0x21, 0x0c, 87 | 0x96, 0x12, 0x44, 0x15, 0x2c, 0xc8, 0xa9, 0x54, 0x62, 0x48, 0x62, 0x03, 0xbb, 0xc5, 0x18, 0x10, 88 | 0x00, 0x00, 0xff, 0xff, 0x2b, 0xf1, 0xe9, 0x56, 0x9c, 0x00, 0x00, 0x00, 89 | } 90 | -------------------------------------------------------------------------------- /examples/go-kit/services/sprint/gen/transports/grpc/grpc.go: -------------------------------------------------------------------------------- 1 | package sprint_grpctransport 2 | 3 | import ( 4 | context "context" 5 | "fmt" 6 | 7 | grpctransport "github.com/go-kit/kit/transport/grpc" 8 | oldcontext "golang.org/x/net/context" 9 | 10 | endpoints "moul.io/protoc-gen-gotemplate/examples/go-kit/services/sprint/gen/endpoints" 11 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/sprint/gen/pb" 12 | ) 13 | 14 | // avoid import errors 15 | var _ = fmt.Errorf 16 | 17 | func MakeGRPCServer(endpoints endpoints.Endpoints) pb.SprintServiceServer { 18 | var options []grpctransport.ServerOption 19 | _ = options 20 | return &grpcServer{ 21 | 22 | addsprint: grpctransport.NewServer( 23 | endpoints.AddSprintEndpoint, 24 | decodeRequest, 25 | encodeAddSprintResponse, 26 | options..., 27 | ), 28 | 29 | closesprint: grpctransport.NewServer( 30 | endpoints.CloseSprintEndpoint, 31 | decodeRequest, 32 | encodeCloseSprintResponse, 33 | options..., 34 | ), 35 | 36 | getsprint: grpctransport.NewServer( 37 | endpoints.GetSprintEndpoint, 38 | decodeRequest, 39 | encodeGetSprintResponse, 40 | options..., 41 | ), 42 | } 43 | } 44 | 45 | type grpcServer struct { 46 | addsprint grpctransport.Handler 47 | 48 | closesprint grpctransport.Handler 49 | 50 | getsprint grpctransport.Handler 51 | } 52 | 53 | func (s *grpcServer) AddSprint(ctx oldcontext.Context, req *pb.AddSprintRequest) (*pb.AddSprintResponse, error) { 54 | _, rep, err := s.addsprint.ServeGRPC(ctx, req) 55 | if err != nil { 56 | return nil, err 57 | } 58 | return rep.(*pb.AddSprintResponse), nil 59 | } 60 | 61 | func encodeAddSprintResponse(ctx context.Context, response interface{}) (interface{}, error) { 62 | resp := response.(*pb.AddSprintResponse) 63 | return resp, nil 64 | } 65 | 66 | func (s *grpcServer) CloseSprint(ctx oldcontext.Context, req *pb.CloseSprintRequest) (*pb.CloseSprintResponse, error) { 67 | _, rep, err := s.closesprint.ServeGRPC(ctx, req) 68 | if err != nil { 69 | return nil, err 70 | } 71 | return rep.(*pb.CloseSprintResponse), nil 72 | } 73 | 74 | func encodeCloseSprintResponse(ctx context.Context, response interface{}) (interface{}, error) { 75 | resp := response.(*pb.CloseSprintResponse) 76 | return resp, nil 77 | } 78 | 79 | func (s *grpcServer) GetSprint(ctx oldcontext.Context, req *pb.GetSprintRequest) (*pb.GetSprintResponse, error) { 80 | _, rep, err := s.getsprint.ServeGRPC(ctx, req) 81 | if err != nil { 82 | return nil, err 83 | } 84 | return rep.(*pb.GetSprintResponse), nil 85 | } 86 | 87 | func encodeGetSprintResponse(ctx context.Context, response interface{}) (interface{}, error) { 88 | resp := response.(*pb.GetSprintResponse) 89 | return resp, nil 90 | } 91 | 92 | func decodeRequest(ctx context.Context, grpcReq interface{}) (interface{}, error) { 93 | return grpcReq, nil 94 | } 95 | 96 | type streamHandler interface { 97 | Do(server interface{}, req interface{}) (err error) 98 | } 99 | 100 | type server struct { 101 | e endpoints.StreamEndpoint 102 | } 103 | 104 | func (s server) Do(server interface{}, req interface{}) (err error) { 105 | if err := s.e(server, req); err != nil { 106 | return err 107 | } 108 | return nil 109 | } 110 | -------------------------------------------------------------------------------- /examples/single-package-mode/output/aaa/aaa.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. 2 | // source: aaa/aaa.proto 3 | // DO NOT EDIT! 4 | 5 | /* 6 | Package aaa is a generated protocol buffer package. 7 | 8 | It is generated from these files: 9 | aaa/aaa.proto 10 | 11 | It has these top-level messages: 12 | AaaRequest 13 | AaaReply 14 | */ 15 | package aaa 16 | 17 | import proto "github.com/golang/protobuf/proto" 18 | import fmt "fmt" 19 | import math "math" 20 | 21 | // Reference imports to suppress errors if they are not otherwise used. 22 | var _ = proto.Marshal 23 | var _ = fmt.Errorf 24 | var _ = math.Inf 25 | 26 | // This is a compile-time assertion to ensure that this generated file 27 | // is compatible with the proto package it is being compiled against. 28 | // A compilation error at this line likely means your copy of the 29 | // proto package needs to be updated. 30 | const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package 31 | 32 | type AaaRequest struct { 33 | Blah string `protobuf:"bytes,1,opt,name=blah" json:"blah,omitempty"` 34 | } 35 | 36 | func (m *AaaRequest) Reset() { *m = AaaRequest{} } 37 | func (m *AaaRequest) String() string { return proto.CompactTextString(m) } 38 | func (*AaaRequest) ProtoMessage() {} 39 | func (*AaaRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } 40 | 41 | func (m *AaaRequest) GetBlah() string { 42 | if m != nil { 43 | return m.Blah 44 | } 45 | return "" 46 | } 47 | 48 | type AaaReply struct { 49 | Error string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"` 50 | } 51 | 52 | func (m *AaaReply) Reset() { *m = AaaReply{} } 53 | func (m *AaaReply) String() string { return proto.CompactTextString(m) } 54 | func (*AaaReply) ProtoMessage() {} 55 | func (*AaaReply) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } 56 | 57 | func (m *AaaReply) GetError() string { 58 | if m != nil { 59 | return m.Error 60 | } 61 | return "" 62 | } 63 | 64 | func init() { 65 | proto.RegisterType((*AaaRequest)(nil), "the.aaa.package.AaaRequest") 66 | proto.RegisterType((*AaaReply)(nil), "the.aaa.package.AaaReply") 67 | } 68 | 69 | func init() { proto.RegisterFile("aaa/aaa.proto", fileDescriptor0) } 70 | 71 | var fileDescriptor0 = []byte{ 72 | // 172 bytes of a gzipped FileDescriptorProto 73 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x2c, 0x8e, 0x31, 0x0b, 0xc2, 0x30, 74 | 0x10, 0x46, 0x29, 0xa8, 0x68, 0x40, 0x84, 0xe0, 0xe0, 0x58, 0x3a, 0xb9, 0xa4, 0x19, 0xfc, 0x05, 75 | 0xba, 0x8b, 0xd0, 0xd1, 0xed, 0x5a, 0x8f, 0xb4, 0x78, 0xe9, 0xc5, 0xf4, 0x02, 0xfa, 0xef, 0xc5, 76 | 0xd8, 0xed, 0x1e, 0xbc, 0xe3, 0x7b, 0x6a, 0x0b, 0x00, 0x16, 0x00, 0xea, 0x10, 0x59, 0x58, 0xef, 77 | 0xa4, 0xc7, 0x3a, 0x23, 0x74, 0x4f, 0x70, 0x58, 0x95, 0x4a, 0x9d, 0x01, 0x1a, 0x7c, 0x25, 0x9c, 78 | 0x44, 0x6b, 0xb5, 0x68, 0x09, 0xfa, 0x43, 0x51, 0x16, 0xc7, 0x4d, 0x93, 0xef, 0xaa, 0x54, 0xeb, 79 | 0x6c, 0x04, 0xfa, 0xe8, 0xbd, 0x5a, 0x62, 0x8c, 0x1c, 0x67, 0xe1, 0x0f, 0x97, 0xdb, 0xfd, 0xea, 80 | 0x06, 0xe9, 0x53, 0x5b, 0x77, 0xec, 0xad, 0xe7, 0x44, 0x36, 0xaf, 0x75, 0xc6, 0xe1, 0x68, 0x1c, 81 | 0x0b, 0xfa, 0x40, 0x20, 0x68, 0xf1, 0x0d, 0x3e, 0x10, 0x4e, 0x76, 0x1a, 0x46, 0x47, 0x68, 0xe6, 82 | 0x08, 0xe3, 0xf9, 0x81, 0x96, 0x93, 0x84, 0x24, 0xbf, 0xd6, 0x76, 0x95, 0xdf, 0x4f, 0xdf, 0x00, 83 | 0x00, 0x00, 0xff, 0xff, 0x93, 0x24, 0x48, 0x9c, 0xbd, 0x00, 0x00, 0x00, 84 | } 85 | -------------------------------------------------------------------------------- /cmd/web-editor/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "io/ioutil" 8 | "log" 9 | "net/http" 10 | "os" 11 | "os/exec" 12 | "path/filepath" 13 | 14 | "github.com/gorilla/handlers" 15 | "github.com/gorilla/mux" 16 | ) 17 | 18 | func generate(w http.ResponseWriter, r *http.Request) { 19 | // read input 20 | decoder := json.NewDecoder(r.Body) 21 | type Input struct { 22 | Protobuf string `json:"protobuf"` 23 | Template string `json:"template"` 24 | } 25 | var input Input 26 | if err := decoder.Decode(&input); err != nil { 27 | returnError(w, err) 28 | return 29 | } 30 | 31 | // create workspace 32 | dir, err := ioutil.TempDir("", "pggt") 33 | if err != nil { 34 | returnError(w, err) 35 | } 36 | // clean up 37 | defer func() { 38 | if err = os.RemoveAll(dir); err != nil { 39 | log.Printf("error: failed to remove temporary directory: %v", err) 40 | } 41 | }() 42 | if err = ioutil.WriteFile(filepath.Join(dir, "example.proto"), []byte(input.Protobuf), 0644); err != nil { 43 | returnError(w, err) 44 | return 45 | } 46 | if err = ioutil.WriteFile(filepath.Join(dir, "example.output.tmpl"), []byte(input.Template), 0644); err != nil { 47 | returnError(w, err) 48 | return 49 | } 50 | 51 | // generate 52 | cmd := exec.Command("protoc", "-I"+dir, "--gotemplate_out=template_dir="+dir+",debug=true:"+dir, filepath.Join(dir, "example.proto")) // #nosec 53 | out, err := cmd.CombinedOutput() 54 | if err != nil { 55 | returnError(w, errors.New(string(out))) 56 | return 57 | } 58 | 59 | // read output 60 | content, err := ioutil.ReadFile(filepath.Join(dir, "example.output")) // #nosec 61 | if err != nil { 62 | returnError(w, err) 63 | return 64 | } 65 | 66 | returnContent(w, content) 67 | } 68 | 69 | func returnContent(w http.ResponseWriter, output interface{}) { 70 | payload := map[string]interface{}{ 71 | "output": fmt.Sprintf("%s", output), 72 | } 73 | response, err := json.Marshal(payload) 74 | if err != nil { 75 | http.Error(w, err.Error(), http.StatusInternalServerError) 76 | return 77 | } 78 | w.Header().Set("Content-Type", "application/json") 79 | w.WriteHeader(http.StatusOK) 80 | if _, err := w.Write(response); err != nil { 81 | http.Error(w, err.Error(), http.StatusInternalServerError) 82 | } 83 | } 84 | 85 | func returnError(w http.ResponseWriter, err error) { 86 | payload := map[string]interface{}{ 87 | "error": fmt.Sprintf("%v", err), 88 | } 89 | response, err := json.Marshal(payload) 90 | if err != nil { 91 | http.Error(w, err.Error(), http.StatusInternalServerError) 92 | return 93 | } 94 | w.Header().Set("Content-Type", "application/json") 95 | w.WriteHeader(http.StatusInternalServerError) 96 | if _, err := w.Write(response); err != nil { 97 | http.Error(w, err.Error(), http.StatusInternalServerError) 98 | } 99 | } 100 | 101 | func main() { 102 | r := mux.NewRouter() 103 | 104 | r.Handle("/", http.FileServer(http.Dir("static"))) 105 | r.HandleFunc("/generate", generate) 106 | addr := fmt.Sprintf(":%s", os.Getenv("PORT")) 107 | if addr == ":" { 108 | addr = ":8080" 109 | } 110 | 111 | fmt.Printf("Listening on %s...\n", addr) 112 | h := handlers.LoggingHandler(os.Stderr, r) 113 | h = handlers.CompressHandler(h) 114 | h = handlers.RecoveryHandler()(h) 115 | if err := http.ListenAndServe(addr, h); err != nil { 116 | panic(err) 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /load.bzl: -------------------------------------------------------------------------------- 1 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") 2 | 3 | def repositories(): 4 | http_archive( 5 | name = "io_k8s_repo_infra", 6 | sha256 = "cf6d870dc054fa2bfb769c7a8d2a2f7df593bcbee361ea043a397c7b74d55abd", 7 | strip_prefix = "repo-infra-4f75b5b6e1958c8be9bcbf95a1f3a4010d8687c0", 8 | urls = ["https://github.com/kubernetes/repo-infra/archive/4f75b5b6e1958c8be9bcbf95a1f3a4010d8687c0.tar.gz"], 9 | ) 10 | http_archive( 11 | name = "bazel_toolchains", 12 | sha256 = "c969f09ffb8ca202692c68b17727fe5c1a8d94cd320e6d62e6c06c75e7d2b723", 13 | strip_prefix = "bazel-toolchains-1.2.1", 14 | urls = [ 15 | "https://mirror.bazel.build/github.com/bazelbuild/bazel-toolchains/archive/1.2.1.tar.gz", 16 | "https://github.com/bazelbuild/bazel-toolchains/archive/1.2.1.tar.gz", 17 | ], 18 | ) 19 | http_archive( 20 | name = "bazel_skylib", 21 | sha256 = "97e70364e9249702246c0e9444bccdc4b847bed1eb03c5a3ece4f83dfe6abc44", 22 | urls = [ 23 | "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz", 24 | "https://github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz", 25 | ], 26 | ) 27 | http_archive( 28 | name = "rules_proto", 29 | sha256 = "7994a4587e00b9049fed87390fc0d5ff62e0077c1ae8a0761d618e4dce2c525c", 30 | strip_prefix = "rules_proto-33549b80b8097502de2a966d764c8d23c59f4d08", 31 | urls = [ 32 | "https://mirror.bazel.build/github.com/bazelbuild/rules_proto/archive/33549b80b8097502de2a966d764c8d23c59f4d08.tar.gz", 33 | "https://github.com/bazelbuild/rules_proto/archive/33549b80b8097502de2a966d764c8d23c59f4d08.tar.gz", 34 | ], 35 | ) 36 | http_archive( 37 | name = "io_bazel_rules_go", 38 | sha256 = "b9aa86ec08a292b97ec4591cf578e020b35f98e12173bbd4a921f84f583aebd9", 39 | urls = [ 40 | "https://storage.googleapis.com/bazel-mirror/github.com/bazelbuild/rules_go/releases/download/v0.20.2/rules_go-v0.20.2.tar.gz", 41 | "https://github.com/bazelbuild/rules_go/releases/download/v0.20.2/rules_go-v0.20.2.tar.gz", 42 | ], 43 | ) 44 | http_archive( 45 | name = "bazel_gazelle", 46 | sha256 = "41bff2a0b32b02f20c227d234aa25ef3783998e5453f7eade929704dcff7cd4b", 47 | urls = [ 48 | "https://storage.googleapis.com/bazel-mirror/github.com/bazelbuild/bazel-gazelle/releases/download/v0.19.0/bazel-gazelle-v0.19.0.tar.gz", 49 | "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.19.0/bazel-gazelle-v0.19.0.tar.gz", 50 | ], 51 | ) 52 | http_archive( 53 | name = "io_bazel_rules_docker", 54 | sha256 = "14ac30773fdb393ddec90e158c9ec7ebb3f8a4fd533ec2abbfd8789ad81a284b", 55 | strip_prefix = "rules_docker-0.12.1", 56 | urls = ["https://github.com/bazelbuild/rules_docker/archive/v0.12.1.tar.gz"], 57 | ) 58 | http_archive( 59 | name = "com_github_grpc_ecosystem_grpc_gateway", 60 | sha256 = "35a987bec7b41a8630b2e20d13b2b14d43d41a8ccde4ce26cdc8d5bef9ae4cba", 61 | strip_prefix = "grpc-gateway-50c55a9810a974dc5a9e7dd1a5c0d295d525f283", 62 | urls = ["https://github.com/grpc-ecosystem/grpc-gateway/archive/50c55a9810a974dc5a9e7dd1a5c0d295d525f283.tar.gz"], 63 | patches = ["//external:grpc-gateway-visibility.patch"], 64 | ) 65 | -------------------------------------------------------------------------------- /examples/go-kit/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | "net/http" 7 | "os" 8 | "os/signal" 9 | "syscall" 10 | 11 | "github.com/go-kit/kit/log" 12 | "github.com/gorilla/handlers" 13 | "google.golang.org/grpc" 14 | 15 | session_svc "moul.io/protoc-gen-gotemplate/examples/go-kit/services/session" 16 | session_endpoints "moul.io/protoc-gen-gotemplate/examples/go-kit/services/session/gen/endpoints" 17 | session_pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/session/gen/pb" 18 | session_grpctransport "moul.io/protoc-gen-gotemplate/examples/go-kit/services/session/gen/transports/grpc" 19 | session_httptransport "moul.io/protoc-gen-gotemplate/examples/go-kit/services/session/gen/transports/http" 20 | 21 | sprint_svc "moul.io/protoc-gen-gotemplate/examples/go-kit/services/sprint" 22 | sprint_endpoints "moul.io/protoc-gen-gotemplate/examples/go-kit/services/sprint/gen/endpoints" 23 | sprint_pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/sprint/gen/pb" 24 | sprint_grpctransport "moul.io/protoc-gen-gotemplate/examples/go-kit/services/sprint/gen/transports/grpc" 25 | sprint_httptransport "moul.io/protoc-gen-gotemplate/examples/go-kit/services/sprint/gen/transports/http" 26 | 27 | user_svc "moul.io/protoc-gen-gotemplate/examples/go-kit/services/user" 28 | user_endpoints "moul.io/protoc-gen-gotemplate/examples/go-kit/services/user/gen/endpoints" 29 | user_pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/user/gen/pb" 30 | user_grpctransport "moul.io/protoc-gen-gotemplate/examples/go-kit/services/user/gen/transports/grpc" 31 | user_httptransport "moul.io/protoc-gen-gotemplate/examples/go-kit/services/user/gen/transports/http" 32 | ) 33 | 34 | func main() { 35 | mux := http.NewServeMux() 36 | errc := make(chan error) 37 | s := grpc.NewServer() 38 | var logger log.Logger 39 | { 40 | logger = log.NewLogfmtLogger(os.Stdout) 41 | logger = log.With(logger, "ts", log.DefaultTimestampUTC) 42 | logger = log.With(logger, "caller", log.DefaultCaller) 43 | } 44 | 45 | // initialize services 46 | { 47 | svc := session_svc.New() 48 | endpoints := session_endpoints.MakeEndpoints(svc) 49 | srv := session_grpctransport.MakeGRPCServer(endpoints) 50 | session_pb.RegisterSessionServiceServer(s, srv) 51 | session_httptransport.RegisterHandlers(svc, mux, endpoints) 52 | } 53 | { 54 | svc := sprint_svc.New() 55 | endpoints := sprint_endpoints.MakeEndpoints(svc) 56 | srv := sprint_grpctransport.MakeGRPCServer(endpoints) 57 | sprint_pb.RegisterSprintServiceServer(s, srv) 58 | sprint_httptransport.RegisterHandlers(svc, mux, endpoints) 59 | } 60 | { 61 | svc := user_svc.New() 62 | endpoints := user_endpoints.MakeEndpoints(svc) 63 | srv := user_grpctransport.MakeGRPCServer(endpoints) 64 | user_pb.RegisterUserServiceServer(s, srv) 65 | user_httptransport.RegisterHandlers(svc, mux, endpoints) 66 | } 67 | 68 | // start servers 69 | go func() { 70 | c := make(chan os.Signal, 1) 71 | signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) 72 | errc <- fmt.Errorf("%s", <-c) 73 | }() 74 | 75 | go func() { 76 | logger := log.With(logger, "transport", "HTTP") 77 | logger.Log("addr", ":8000") 78 | errc <- http.ListenAndServe(":8000", handlers.LoggingHandler(os.Stderr, mux)) 79 | }() 80 | 81 | go func() { 82 | logger := log.With(logger, "transport", "gRPC") 83 | ln, err := net.Listen("tcp", ":9000") 84 | if err != nil { 85 | errc <- err 86 | return 87 | } 88 | logger.Log("addr", ":9000") 89 | errc <- s.Serve(ln) 90 | }() 91 | 92 | logger.Log("exit", <-errc) 93 | } 94 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/Masterminds/semver v1.2.2 h1:ptelpryog9A0pR4TGFvIAvw2c8SaNrYkFtfrxhSviss= 2 | github.com/Masterminds/semver v1.2.2/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= 3 | github.com/Masterminds/sprig v2.14.1+incompatible h1:rTHERm50Xp1Cbb8x7xBCeDp//jMMqqR44EWw7KwSXUQ= 4 | github.com/Masterminds/sprig v2.14.1+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= 5 | github.com/aokoli/goutils v0.0.0-20170502144750-e57d01ace047 h1:Bn0iqJ/349f606hR0juIGyheAI6+hyg9XUOLhN9udLo= 6 | github.com/aokoli/goutils v0.0.0-20170502144750-e57d01ace047/go.mod h1:SijmP0QR8LtwsmDs8Yii5Z/S4trXFGFC2oO5g9DP+DQ= 7 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= 8 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 9 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= 10 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= 11 | github.com/golang/protobuf v0.0.0-20161117033126-8ee79997227b h1:fE/yi9pibxGEc0gSJuEShcsBXE2d5FW3OudsjE9tKzQ= 12 | github.com/golang/protobuf v0.0.0-20161117033126-8ee79997227b/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 13 | github.com/gorilla/context v0.0.0-20160226214623-1ea25387ff6f h1:9oNbS1z4rVpbnkHBdPZU4jo9bSmrLpII768arSyMFgk= 14 | github.com/gorilla/context v0.0.0-20160226214623-1ea25387ff6f/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= 15 | github.com/gorilla/handlers v0.0.0-20161028133215-e1b2144f2167 h1:uANqGlSIT3JwuQVokEBcvc9WAu5+v4cVD5szF5k+iIU= 16 | github.com/gorilla/handlers v0.0.0-20161028133215-e1b2144f2167/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ= 17 | github.com/gorilla/mux v1.5.0 h1:mq8bRov+5x+pZNR/uAHyUEgovR9gLgYFwDQIeuYi9TM= 18 | github.com/gorilla/mux v1.5.0/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= 19 | github.com/grpc-ecosystem/grpc-gateway v1.2.2 h1:oR2ZMoJtQccW6NIJ9yFxRqAr2rkmcNsCaZKT66A9zt4= 20 | github.com/grpc-ecosystem/grpc-gateway v1.2.2/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw= 21 | github.com/huandu/xstrings v0.0.0-20151130125119-3959339b3335 h1:KZOP9q7J/P4eMBibPuVwuloXgd2dTbLAHRPqxw7NXOw= 22 | github.com/huandu/xstrings v0.0.0-20151130125119-3959339b3335/go.mod h1:4qWG/gcEcfX4z/mBDHJ++3ReCw9ibxbsNJbcucJdbSo= 23 | github.com/imdario/mergo v0.0.0-20171009183408-7fe0c75c13ab h1:k/Biv+LJL35wkk0Hveko1nj7as4tSHkHdZaNlzn/gcQ= 24 | github.com/imdario/mergo v0.0.0-20171009183408-7fe0c75c13ab/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= 25 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 26 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 27 | github.com/satori/go.uuid v1.1.0 h1:B9KXyj+GzIpJbV7gmr873NsY6zpbxNy24CBtGrk7jHo= 28 | github.com/satori/go.uuid v1.1.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= 29 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 30 | github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= 31 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 32 | golang.org/x/crypto v0.0.0-20170516161655-0fe963104e9d h1:qjfFh1YMn6m60QTGoG+IlwUMhNlXJbDyCa6EkHM/N2w= 33 | golang.org/x/crypto v0.0.0-20170516161655-0fe963104e9d/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= 34 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw= 35 | golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 36 | google.golang.org/genproto v0.0.0-20170517234824-bb3573be0c48 h1:xfoW+Di7qQQUnjptcGb4/rpc701e3RvfNmaywfMxQVI= 37 | google.golang.org/genproto v0.0.0-20170517234824-bb3573be0c48/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= 38 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 39 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 40 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 41 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 42 | -------------------------------------------------------------------------------- /examples/flow/templates/%7B%7B.File.Package%7D%7D/%7B%7B.File.Package%7D%7D_grpc_js.js.tmpl: -------------------------------------------------------------------------------- 1 | // @flow 2 | // GENERATED CODE -- DO NOT EDIT! 3 | 4 | {{- $Package:=.File.Package}} 5 | 6 | import base64 from 'base64-js' 7 | import {{$Package}}_pb from './{{$Package}}_pb' 8 | 9 | {{- range .File.Dependency}} 10 | import {{. | replace "/" "_" | trimSuffix ".proto" }}_pb from '../{{. | trimSuffix ".proto" }}_pb' 11 | {{- end}} 12 | 13 | {{- define "fieldMethods"}} 14 | {{- if isFieldRepeated .}} 15 | get{{.Name | camelCase}}List?: () => {{. | jsType}}; 16 | set{{.Name | camelCase}}List?: ({{.Name}}: {{. | jsType}}) => void; 17 | add{{.Name | camelCase}}?: ({{.Name}}: {{. | jsType | trimPrefix "Array<" | trimSuffix ">"}}) => void; 18 | clear{{.Name | camelCase}}List?: () => void; 19 | {{- else}} 20 | get{{.Name | camelCase}}?: () => {{. | jsType}}; 21 | set{{.Name | camelCase}}?: ({{.Name}}: {{. | jsType}}) => void; 22 | 23 | {{- if isFieldMessage .}} 24 | clear{{.Name | camelCase}}?: () => void; 25 | has{{.Name | camelCase}}?: () => boolean; 26 | {{- end}} 27 | {{- end}} 28 | {{- end}} 29 | 30 | {{range .File.EnumType}} 31 | export type {{.Name}} = {| 32 | {{- range .Value}} 33 | {{.Name}}?: {{.Number}}; 34 | {{- end}} 35 | |}; 36 | {{- end}} 37 | 38 | {{- range .File.MessageType}} 39 | {{- $MessageType := .Name}} 40 | 41 | {{range .EnumType}} 42 | export type {{$MessageType}}${{.Name}} = {| 43 | {{- range .Value}} 44 | {{.Name}}?: {{.Number}}; 45 | {{- end}} 46 | |}; 47 | {{- end}} 48 | 49 | {{range .NestedType}} 50 | export type {{$MessageType}}${{.Name}} = { 51 | {{- range .Field}} 52 | {{- template "fieldMethods" .}} 53 | {{- end}} 54 | }; 55 | {{- end}} 56 | 57 | export type {{.Name}} = { 58 | {{- range .Field}} 59 | {{- template "fieldMethods" .}} 60 | {{- end}} 61 | }; 62 | 63 | {{- end}} 64 | 65 | const serializeToBase64 = (byteArray: Uint8Array): string => base64.fromByteArray(byteArray) 66 | const deserializeFromBase64 = (base64Encoded: string): Uint8Array => new Uint8Array(base64.toByteArray(base64Encoded)) 67 | 68 | {{range .File.Service}}{{range .Method}} 69 | function serialize_{{$Package}}_{{.InputType | shortType}}(arg : {{.InputType | shortType}}): string { 70 | if (!(arg instanceof {{$Package}}_pb.{{.InputType | shortType}})) { 71 | throw new Error('Expected argument of type {{.InputType | shortType}}') 72 | } 73 | return serializeToBase64(arg.serializeBinary()) 74 | } 75 | 76 | function deserialize_{{$Package}}_{{.InputType | shortType}}(base64Encoded: string): {{.InputType | shortType}} { 77 | return {{$Package}}_pb.{{.InputType | shortType}}.deserializeBinary(deserializeFromBase64(base64Encoded)) 78 | } 79 | 80 | function serialize_{{$Package}}_{{.OutputType | shortType}}(arg : {{.OutputType | shortType}}): string { 81 | if (!(arg instanceof {{$Package}}_pb.{{.OutputType | shortType}})) { 82 | throw new Error('Expected argument of type {{.OutputType | shortType}}') 83 | } 84 | return serializeToBase64(arg.serializeBinary()) 85 | } 86 | 87 | function deserialize_{{$Package}}_{{.OutputType | shortType}}(base64Encoded: string): {{.OutputType | shortType}} { 88 | return {{$Package}}_pb.{{.OutputType | shortType}}.deserializeBinary(deserializeFromBase64(base64Encoded)) 89 | } 90 | 91 | {{end}}{{end}} 92 | export default { 93 | {{range .File.Service}} 94 | {{.Name}}: { 95 | {{$serviceName:=.Name}} 96 | {{range .Method}}{{.Name | lowerCamelCase}}: { 97 | path: '/{{$Package}}.{{$serviceName}}/{{.Name}}', 98 | requestStream: {{.ClientStreaming | default "false"}}, 99 | responseStream: {{.ServerStreaming | default "false"}}, 100 | requestType: {{$Package}}_pb.{{.InputType | shortType}}, 101 | responseType: {{$Package}}_pb.{{.OutputType | shortType}}, 102 | requestSerialize: serialize_{{$Package}}_{{.InputType | shortType}}, 103 | requestDeserialize: deserialize_{{$Package}}_{{.InputType | shortType}}, 104 | responseSerialize: serialize_{{$Package}}_{{.OutputType | shortType}}, 105 | responseDeserialize: deserialize_{{$Package}}_{{.OutputType | shortType}}, 106 | }, 107 | {{end}} 108 | } 109 | {{end}} 110 | } 111 | -------------------------------------------------------------------------------- /examples/helpers/example.txt: -------------------------------------------------------------------------------- 1 | # Common variables 2 | {{.File.Name}}: helpers.proto 3 | {{.File.Name | upper}}: HELPERS.PROTO 4 | {{.File.Package | base | replace "." "-"}} dummy 5 | {{$packageDir := .File.Name | dir}}{{$packageDir}} . 6 | {{$packageName := .File.Name | base | replace ".proto" ""}}{{$packageName}} helpers 7 | {{$packageImport := .File.Package | replace "." "_"}}{{$packageImport}} dummy 8 | {{$namespacedPackage := .File.Package}}{{$namespacedPackage}} dummy 9 | {{$currentFile := .File.Name | getProtoFile}}{{$currentFile}} 10 | {{- /*{{- $currentPackageName := $currentFile.GoPkg.Name}}{{$currentPackageName}}*/}} 11 | # TODO: more variables 12 | 13 | # Sprig: strings 14 | {{trim " hello "}}: hello 15 | {{trimAll "$" "$5.00"}}: 5.00 16 | {{trimSuffix "-" "hello-"}}: hello 17 | {{upper "hello"}}: HELLO 18 | {{lower "HELLO"}}: hello 19 | {{title "hello world"}}: Hello World 20 | {{untitle "Hello World"}}: hello world 21 | {{repeat 3 "hello"}}: hellohellohello 22 | {{substr 0 5 "hello world"}}: hello 23 | {{nospace "hello w o r l d"}}: helloworld 24 | {{trunc 5 "hello world"}}: hello 25 | {{abbrev 5 "hello world"}}: he... 26 | {{abbrevboth 5 10 "1234 5678 9123"}}: ...5678... 27 | {{initials "First Try"}}: FT 28 | {{randNumeric 3}}: 528 29 | {{- /*{{wrap 80 $someText}}*/}}: 30 | {{wrapWith 5 "\t" "Hello World"}}: Hello World 31 | {{contains "cat" "catch"}}: true 32 | {{hasPrefix "cat" "catch"}}: true 33 | {{cat "hello" "beautiful" "world"}}: hello beautiful world 34 | {{- /*{{indent 4 $lots_of_text}}*/}}: 35 | {{- /*{{indent 4 $lots_of_text}}*/}}: 36 | {{"I Am Henry VIII" | replace " " "-"}}: I-Am-Henry-VIII 37 | {{len .Service.Method | plural "one anchovy" "many anchovies"}}: many anchovies 38 | {{snakecase "FirstName"}}: first_name 39 | {{camelcase "http_server"}}: HttpServer 40 | {{shuffle "hello"}}: holle 41 | {{regexMatch "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" "test@acme.com"}}: true 42 | {{- /*{{regexFindAll "[2,4,6,8]" "123456789"}}*/}}: 43 | {{regexFind "[a-zA-Z][1-9]" "abcd1234"}}: d1 44 | {{regexReplaceAll "a(x*)b" "-ab-axxb-" "${1}W"}}: -W-xxW- 45 | {{regexReplaceAllLiteral "a(x*)b" "-ab-axxb-" "${1}"}}: -${1}-${1}- 46 | {{regexSplit "z+" "pizza" -1}}: [pi a] 47 | 48 | # Get one specific method on array method using index 49 | {{ index .Service.Method 1 }}: name:"Iii" input_type:".dummy.Dummy2" output_type:".dummy.Dummy1" options:<> 50 | 51 | # Sprig: advanced 52 | {{if contains "cat" "catch"}}yes{{else}}no{{end}}: yes 53 | {{1 | plural "one anchovy" "many anchovies"}}: one anchovy 54 | {{2 | plural "one anchovy" "many anchovies"}}: many anchovies 55 | {{3 | plural "one anchovy" "many anchovies"}}: many anchovies 56 | 57 | # TODO: more sprig examples 58 | # TODO: all built-in examples -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main // import "moul.io/protoc-gen-gotemplate" 2 | 3 | import ( 4 | "io/ioutil" 5 | "log" 6 | "os" 7 | "strings" 8 | 9 | "github.com/golang/protobuf/proto" 10 | "github.com/golang/protobuf/protoc-gen-go/generator" 11 | plugin_go "github.com/golang/protobuf/protoc-gen-go/plugin" 12 | ggdescriptor "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor" 13 | 14 | pgghelpers "moul.io/protoc-gen-gotemplate/helpers" 15 | ) 16 | 17 | var ( 18 | registry *ggdescriptor.Registry // some helpers need access to registry 19 | ) 20 | 21 | const ( 22 | boolTrue = "true" 23 | boolFalse = "false" 24 | ) 25 | 26 | func main() { 27 | g := generator.New() 28 | 29 | data, err := ioutil.ReadAll(os.Stdin) 30 | if err != nil { 31 | g.Error(err, "reading input") 32 | } 33 | 34 | if err = proto.Unmarshal(data, g.Request); err != nil { 35 | g.Error(err, "parsing input proto") 36 | } 37 | 38 | if len(g.Request.FileToGenerate) == 0 { 39 | g.Fail("no files to generate") 40 | } 41 | 42 | g.CommandLineParameters(g.Request.GetParameter()) 43 | 44 | // Parse parameters 45 | var ( 46 | templateDir = "./templates" 47 | destinationDir = "." 48 | debug = false 49 | all = false 50 | singlePackageMode = false 51 | fileMode = false 52 | ) 53 | if parameter := g.Request.GetParameter(); parameter != "" { 54 | for _, param := range strings.Split(parameter, ",") { 55 | parts := strings.Split(param, "=") 56 | if len(parts) != 2 { 57 | log.Printf("Err: invalid parameter: %q", param) 58 | continue 59 | } 60 | switch parts[0] { 61 | case "template_dir": 62 | templateDir = parts[1] 63 | case "destination_dir": 64 | destinationDir = parts[1] 65 | case "single-package-mode": 66 | switch strings.ToLower(parts[1]) { 67 | case boolTrue, "t": 68 | singlePackageMode = true 69 | case boolFalse, "f": 70 | default: 71 | log.Printf("Err: invalid value for single-package-mode: %q", parts[1]) 72 | } 73 | case "debug": 74 | switch strings.ToLower(parts[1]) { 75 | case boolTrue, "t": 76 | debug = true 77 | case boolFalse, "f": 78 | default: 79 | log.Printf("Err: invalid value for debug: %q", parts[1]) 80 | } 81 | case "all": 82 | switch strings.ToLower(parts[1]) { 83 | case boolTrue, "t": 84 | all = true 85 | case boolFalse, "f": 86 | default: 87 | log.Printf("Err: invalid value for debug: %q", parts[1]) 88 | } 89 | case "file-mode": 90 | switch strings.ToLower(parts[1]) { 91 | case boolTrue, "t": 92 | fileMode = true 93 | case boolFalse, "f": 94 | default: 95 | log.Printf("Err: invalid value for file-mode: %q", parts[1]) 96 | } 97 | default: 98 | log.Printf("Err: unknown parameter: %q", param) 99 | } 100 | } 101 | } 102 | 103 | tmplMap := make(map[string]*plugin_go.CodeGeneratorResponse_File) 104 | concatOrAppend := func(file *plugin_go.CodeGeneratorResponse_File) { 105 | if val, ok := tmplMap[file.GetName()]; ok { 106 | *val.Content += file.GetContent() 107 | } else { 108 | tmplMap[file.GetName()] = file 109 | g.Response.File = append(g.Response.File, file) 110 | } 111 | } 112 | 113 | if singlePackageMode { 114 | registry = ggdescriptor.NewRegistry() 115 | pgghelpers.SetRegistry(registry) 116 | if err = registry.Load(g.Request); err != nil { 117 | g.Error(err, "registry: failed to load the request") 118 | } 119 | } 120 | 121 | // Generate the encoders 122 | for _, file := range g.Request.GetProtoFile() { 123 | if all { 124 | if singlePackageMode { 125 | if _, err = registry.LookupFile(file.GetName()); err != nil { 126 | g.Error(err, "registry: failed to lookup file %q", file.GetName()) 127 | } 128 | } 129 | encoder := NewGenericTemplateBasedEncoder(templateDir, file, debug, destinationDir) 130 | for _, tmpl := range encoder.Files() { 131 | concatOrAppend(tmpl) 132 | } 133 | 134 | continue 135 | } 136 | 137 | if fileMode { 138 | if s := file.GetService(); s != nil && len(s) > 0 { 139 | encoder := NewGenericTemplateBasedEncoder(templateDir, file, debug, destinationDir) 140 | for _, tmpl := range encoder.Files() { 141 | concatOrAppend(tmpl) 142 | } 143 | } 144 | 145 | continue 146 | } 147 | 148 | for _, service := range file.GetService() { 149 | encoder := NewGenericServiceTemplateBasedEncoder(templateDir, service, file, debug, destinationDir) 150 | for _, tmpl := range encoder.Files() { 151 | concatOrAppend(tmpl) 152 | } 153 | } 154 | } 155 | 156 | // Generate the protobufs 157 | g.GenerateAllFiles() 158 | 159 | data, err = proto.Marshal(g.Response) 160 | if err != nil { 161 | g.Error(err, "failed to marshal output proto") 162 | } 163 | 164 | _, err = os.Stdout.Write(data) 165 | if err != nil { 166 | g.Error(err, "failed to write output proto") 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /examples/import/output/models/article/article.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: proto/article.proto 3 | 4 | /* 5 | Package article is a generated protocol buffer package. 6 | 7 | It is generated from these files: 8 | proto/article.proto 9 | 10 | It has these top-level messages: 11 | GetArticleRequest 12 | GetArticleResponse 13 | Article 14 | */ 15 | package article 16 | 17 | import proto "github.com/golang/protobuf/proto" 18 | import fmt "fmt" 19 | import math "math" 20 | import common "moul.io/protoc-gen-gotemplate/examples/import/output/models/common" 21 | 22 | // Reference imports to suppress errors if they are not otherwise used. 23 | var _ = proto.Marshal 24 | var _ = fmt.Errorf 25 | var _ = math.Inf 26 | 27 | // This is a compile-time assertion to ensure that this generated file 28 | // is compatible with the proto package it is being compiled against. 29 | // A compilation error at this line likely means your copy of the 30 | // proto package needs to be updated. 31 | const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package 32 | 33 | type GetArticleRequest struct { 34 | Getarticle *common.GetArticle `protobuf:"bytes,1,opt,name=getarticle" json:"getarticle,omitempty"` 35 | } 36 | 37 | func (m *GetArticleRequest) Reset() { *m = GetArticleRequest{} } 38 | func (m *GetArticleRequest) String() string { return proto.CompactTextString(m) } 39 | func (*GetArticleRequest) ProtoMessage() {} 40 | func (*GetArticleRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } 41 | 42 | func (m *GetArticleRequest) GetGetarticle() *common.GetArticle { 43 | if m != nil { 44 | return m.Getarticle 45 | } 46 | return nil 47 | } 48 | 49 | type GetArticleResponse struct { 50 | Article *Article `protobuf:"bytes,1,opt,name=article" json:"article,omitempty"` 51 | // The generated output should write []*GetArticleResponse_Storage.Storage for this field. 52 | Storages []*GetArticleResponse_Storage `protobuf:"bytes,2,rep,name=storages" json:"storages,omitempty"` 53 | } 54 | 55 | func (m *GetArticleResponse) Reset() { *m = GetArticleResponse{} } 56 | func (m *GetArticleResponse) String() string { return proto.CompactTextString(m) } 57 | func (*GetArticleResponse) ProtoMessage() {} 58 | func (*GetArticleResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } 59 | 60 | func (m *GetArticleResponse) GetArticle() *Article { 61 | if m != nil { 62 | return m.Article 63 | } 64 | return nil 65 | } 66 | 67 | func (m *GetArticleResponse) GetStorages() []*GetArticleResponse_Storage { 68 | if m != nil { 69 | return m.Storages 70 | } 71 | return nil 72 | } 73 | 74 | type GetArticleResponse_Storage struct { 75 | Code string `protobuf:"bytes,1,opt,name=code" json:"code,omitempty"` 76 | } 77 | 78 | func (m *GetArticleResponse_Storage) Reset() { *m = GetArticleResponse_Storage{} } 79 | func (m *GetArticleResponse_Storage) String() string { return proto.CompactTextString(m) } 80 | func (*GetArticleResponse_Storage) ProtoMessage() {} 81 | func (*GetArticleResponse_Storage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1, 0} } 82 | 83 | func (m *GetArticleResponse_Storage) GetCode() string { 84 | if m != nil { 85 | return m.Code 86 | } 87 | return "" 88 | } 89 | 90 | type Article struct { 91 | Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` 92 | Name string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` 93 | } 94 | 95 | func (m *Article) Reset() { *m = Article{} } 96 | func (m *Article) String() string { return proto.CompactTextString(m) } 97 | func (*Article) ProtoMessage() {} 98 | func (*Article) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } 99 | 100 | func (m *Article) GetId() string { 101 | if m != nil { 102 | return m.Id 103 | } 104 | return "" 105 | } 106 | 107 | func (m *Article) GetName() string { 108 | if m != nil { 109 | return m.Name 110 | } 111 | return "" 112 | } 113 | 114 | func init() { 115 | proto.RegisterType((*GetArticleRequest)(nil), "company.GetArticleRequest") 116 | proto.RegisterType((*GetArticleResponse)(nil), "company.GetArticleResponse") 117 | proto.RegisterType((*GetArticleResponse_Storage)(nil), "company.GetArticleResponse.Storage") 118 | proto.RegisterType((*Article)(nil), "company.Article") 119 | } 120 | 121 | func init() { proto.RegisterFile("proto/article.proto", fileDescriptor0) } 122 | 123 | var fileDescriptor0 = []byte{ 124 | // 256 bytes of a gzipped FileDescriptorProto 125 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x91, 0x41, 0x4b, 0xc4, 0x30, 126 | 0x10, 0x85, 0x6d, 0x15, 0xab, 0xb3, 0x20, 0x3a, 0x82, 0x94, 0x8a, 0xb0, 0xd4, 0xcb, 0x22, 0x18, 127 | 0xa1, 0x1e, 0x3d, 0x88, 0x5e, 0x7a, 0xaf, 0x78, 0xf1, 0x56, 0xd3, 0x61, 0x29, 0x6c, 0x3a, 0xb5, 128 | 0x89, 0x82, 0xff, 0xc6, 0x9f, 0x2a, 0x9b, 0x4c, 0xd7, 0x8a, 0xb2, 0xa7, 0x4e, 0xf3, 0xbe, 0xf7, 129 | 0xf2, 0xc8, 0xc0, 0x69, 0x3f, 0xb0, 0xe3, 0x9b, 0x7a, 0x70, 0xad, 0x5e, 0x91, 0xf2, 0x7f, 0x98, 130 | 0x68, 0x36, 0x7d, 0xdd, 0x7d, 0x66, 0x18, 0x54, 0xcd, 0xc6, 0x70, 0x17, 0xc4, 0xbc, 0x84, 0x93, 131 | 0x92, 0xdc, 0x43, 0x30, 0x54, 0xf4, 0xf6, 0x4e, 0xd6, 0x61, 0x01, 0xb0, 0x24, 0x27, 0x29, 0x69, 132 | 0x34, 0x8f, 0x16, 0xb3, 0x02, 0x95, 0xf8, 0x26, 0xf8, 0x84, 0xca, 0xbf, 0x22, 0xc0, 0x69, 0x92, 133 | 0xed, 0xb9, 0xb3, 0x84, 0x57, 0x90, 0xfc, 0xce, 0x39, 0x56, 0x52, 0x47, 0x8d, 0xe8, 0x08, 0xe0, 134 | 0x3d, 0x1c, 0x58, 0xc7, 0x43, 0xbd, 0x24, 0x9b, 0xc6, 0xf3, 0xdd, 0xc5, 0xac, 0xb8, 0xdc, 0xc0, 135 | 0x7f, 0xa3, 0xd5, 0x53, 0x60, 0xab, 0x8d, 0x29, 0xbb, 0x80, 0x44, 0x0e, 0x11, 0x61, 0x4f, 0x73, 136 | 0x13, 0x2e, 0x3d, 0xac, 0xfc, 0x9c, 0x5f, 0x43, 0x22, 0x19, 0x78, 0x04, 0x71, 0xdb, 0x88, 0x18, 137 | 0xb7, 0xcd, 0x1a, 0xef, 0x6a, 0x43, 0x69, 0x1c, 0xf0, 0xf5, 0x5c, 0x3c, 0x03, 0x48, 0x33, 0xfb, 138 | 0xa1, 0xb1, 0x04, 0xf8, 0xe9, 0x80, 0xd9, 0xbf, 0xc5, 0xfc, 0xeb, 0x65, 0xe7, 0x5b, 0x4a, 0xe7, 139 | 0x3b, 0x8f, 0xe9, 0xcb, 0x99, 0xe1, 0x86, 0x56, 0x76, 0x5c, 0xd3, 0x9d, 0x7c, 0x5f, 0xf7, 0xfd, 140 | 0x4a, 0x6e, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0x93, 0xb5, 0x4a, 0x95, 0xc6, 0x01, 0x00, 0x00, 141 | } 142 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `protoc-gen-gotemplate` 2 | :open_file_folder: protocol generator + golang text/template (protobuf) 3 | 4 | A generic **code**/script/data generator based on [Protobuf](https://developers.google.com/protocol-buffers/). 5 | 6 | --- 7 | 8 | This project is a generator plugin for the Google Protocol Buffers compiler (`protoc`). 9 | 10 | The plugin parses **protobuf** files, generates an **ast**, and walks a local **templates directory** to generate files using the [Golang's `text/template` engine](https://golang.org/pkg/text/template/). 11 | 12 | ## Philosophy 13 | 14 | * protobuf-first 15 | * no built-in template, only user defined templates 16 | * kiss, *keep it stupid simple* 17 | 18 | ## Under the hood 19 | 20 | 1. the *user* `protobuf` files are parsed by [`protoc`](https://github.com/google/protobuf/releases) 21 | 2. the `ast` is generated by [`protoc-gen-go` helpers](https://github.com/golang/protobuf/tree/master/protoc-gen-go) 22 | 3. the `ast` is given to [Golang's `text/template` engine](https://golang.org/pkg/text/template/) for each *user* template files 23 | 4. the *funcmap* enriching the template engine is based on [Masterminds/sprig](https://github.com/Masterminds/sprig), and contains type-manipulation, iteration and language-specific helpers 24 | 25 | ## Web editor 26 | 27 |  28 | 29 | [Demo server](http://protoc-gen-gotemplate.m.42.am/) 30 | 31 | ## Usage 32 | 33 | `protoc-gen-gotemplate` requires a **template_dir** directory *(by default `./templates`)*. 34 | 35 | Every file ending with `.tmpl` will be processed and written to the destination folder, following the file hierarchy of the `template_dir`, and remove the `.tmpl` extension. 36 | 37 | --- 38 | 39 | ```console 40 | $> ls -R 41 | input.proto templates/doc.txt.tmpl templates/config.json.tmpl 42 | $> protoc --gotemplate_out=. input.proto 43 | $> ls -R 44 | input.proto templates/doc.txt.tmpl templates/config.json.tmpl 45 | doc.txt config.json 46 | ``` 47 | 48 | ### Options 49 | 50 | You can specify custom options, as follow: 51 | 52 | ```console 53 | $> protoc --gotemplate_out=debug=true,template_dir=/path/to/template/directory:. input.proto 54 | ``` 55 | 56 | | Option | Default Value | Accepted Values | Description 57 | |-----------------------|---------------|---------------------------|----------------------- 58 | | `template_dir` | `./template` | absolute or relative path | path to look for templates 59 | | `destination_dir` | `.` | absolute or relative path | base path to write output 60 | | `single-package-mode` | *false* | `true` or `false` | if *true*, `protoc` won't accept multiple packages to be compiled at once (*!= from `all`*), but will support `Message` lookup across the imported protobuf dependencies 61 | | `debug` | *false* | `true` or `false` | if *true*, `protoc` will generate a more verbose output 62 | | `all` | *false* | `true` or `false` | if *true*, protobuf files without `Service` will also be parsed 63 | 64 | ##### Hints 65 | 66 | Shipping the templates with your project is very smart and useful when contributing on git-based projects. 67 | 68 | Another workflow consists in having a dedicated repository for generic templates which is then versioned and vendored with multiple projects (npm package, golang vendor package, ...) 69 | 70 | See [examples](./examples). 71 | 72 | ## Funcmap 73 | 74 | This project uses [Masterminds/sprig](https://github.com/Masterminds/sprig) library and additional functions to extend the builtin [text/template](https://golang.org/pkg/text/template) helpers. 75 | 76 | Non-exhaustive list of new helpers: 77 | 78 | * **all the functions from [sprig](https://github.com/Masterminds/sprig)** 79 | * `add` 80 | * `boolFieldExtension` 81 | * `camelCase` 82 | * `contains` 83 | * `divide` 84 | * `fieldMapKeyType` 85 | * `fieldMapValueType` 86 | * `first` 87 | * `getEnumValue` 88 | * `getMessageType` 89 | * `getProtoFile` 90 | * `goNormalize` 91 | * `goTypeWithPackage` 92 | * `goType` 93 | * `goZeroValue` 94 | * `haskellType` 95 | * `httpBody` 96 | * `httpPath` 97 | * `httpPathsAdditionalBindings` 98 | * `httpVerb` 99 | * `index` 100 | * `int64FieldExtension` 101 | * `isFieldMap` 102 | * `isFieldMessageTimeStamp` 103 | * `isFieldMessage` 104 | * `isFieldRepeated` 105 | * `jsSuffixReserved` 106 | * `jsType` 107 | * `json` 108 | * `kebabCase` 109 | * `last` 110 | * `leadingComment` 111 | * `leadingDetachedComments` 112 | * `lowerCamelCase` 113 | * `lowerFirst` 114 | * `lowerGoNormalize` 115 | * `multiply` 116 | * `namespacedFlowType` 117 | * `prettyjson` 118 | * `replaceDict` 119 | * `shortType` 120 | * `snakeCase` 121 | * `splitArray` 122 | * `stringFieldExtension` 123 | * `stringMethodOptionsExtension` 124 | * `string` 125 | * `subtract` 126 | * `trailingComment` 127 | * `trimstr` 128 | * `upperFirst` 129 | * `urlHasVarsFromMessage` 130 | 131 | See the project helpers for the complete list. 132 | 133 | ## Install 134 | 135 | * Install the **Go** compiler and tools from https://golang.org/doc/install 136 | * Install **protobuf**: `go get -u github.com/golang/protobuf/{proto,protoc-gen-go}` 137 | * Install **protoc-gen-gotemplate**: `go get -u moul.io/protoc-gen-gotemplate` 138 | 139 | ## Docker 140 | 141 | * automated docker hub build: [https://hub.docker.com/r/moul/protoc-gen-gotemplate/](https://hub.docker.com/r/moul/protoc-gen-gotemplate/) 142 | * Based on [http://github.com/znly/protoc](http://github.com/znly/protoc) 143 | 144 | Usage: 145 | 146 | ```console 147 | $> docker run --rm -v "$(pwd):$(pwd)" -w "$(pwd)" moul/protoc-gen-gotemplate -I. --gotemplate_out=./output/ ./*.proto 148 | ``` 149 | 150 | ## Projects using `protoc-gen-gotemplate` 151 | 152 | * [kafka-gateway](https://github.com/moul/kafka-gateway/): Kafka gateway/proxy (gRPC + http) using Go-Kit 153 | * [translator](https://github.com/moul/translator): Translator Micro-service using Gettext and Go-Kit 154 | * [acl](https://github.com/moul/acl): ACL micro-service (gRPC/protobuf + http/json) 155 | 156 | ## See also 157 | 158 | * [pbhbs](https://github.com/gponsinet/pbhbs): protobuf gen based on handlebarjs template 159 | 160 | ## License 161 | 162 | MIT 163 | -------------------------------------------------------------------------------- /examples/helpers/example.txt.tmpl: -------------------------------------------------------------------------------- 1 | # Common variables 2 | {{`{{.File.Name}}`}}: {{.File.Name}} 3 | {{`{{.File.Name | upper}}`}}: {{.File.Name | upper}} 4 | {{`{{.File.Package | base | replace "." "-"}}`}} {{.File.Package | base | replace "." "-"}} 5 | {{- /*{{`{{$file := .File}}{{$file}}`}} {{$file := .File}}{{$file}}*/}} 6 | {{`{{$packageDir := .File.Name | dir}}{{$packageDir}}`}} {{$packageDir := .File.Name | dir}}{{$packageDir}} 7 | {{`{{$packageName := .File.Name | base | replace ".proto" ""}}{{$packageName}}`}} {{$packageName := .File.Name | base | replace ".proto" ""}}{{$packageName}} 8 | {{`{{$packageImport := .File.Package | replace "." "_"}}{{$packageImport}}`}} {{$packageImport := .File.Package | replace "." "_"}}{{$packageImport}} 9 | {{`{{$namespacedPackage := .File.Package}}{{$namespacedPackage}}`}} {{$namespacedPackage := .File.Package}}{{$namespacedPackage}} 10 | {{`{{$currentFile := .File.Name | getProtoFile}}{{$currentFile}}`}} {{$currentFile := .File.Name | getProtoFile}}{{$currentFile}} 11 | {{`{{- /*{{- $currentPackageName := $currentFile.GoPkg.Name}}{{$currentPackageName}}*/}}`}} {{- /*{{- $currentPackageName := $currentFile.GoPkg.Name}}{{$currentPackageName}}*/}} 12 | # TODO: more variables 13 | 14 | # Sprig: strings 15 | {{`{{trim " hello "}}`}}: {{trim " hello "}} 16 | {{`{{trimAll "$" "$5.00"}}`}}: {{trimAll "$" "$5.00"}} 17 | {{`{{trimSuffix "-" "hello-"}}`}}: {{trimSuffix "-" "hello-"}} 18 | {{`{{upper "hello"}}`}}: {{upper "hello"}} 19 | {{`{{lower "HELLO"}}`}}: {{lower "HELLO"}} 20 | {{`{{title "hello world"}}`}}: {{title "hello world"}} 21 | {{`{{untitle "Hello World"}}`}}: {{untitle "Hello World"}} 22 | {{`{{repeat 3 "hello"}}`}}: {{repeat 3 "hello"}} 23 | {{`{{substr 0 5 "hello world"}}`}}: {{substr 0 5 "hello world"}} 24 | {{`{{nospace "hello w o r l d"}}`}}: {{nospace "hello w o r l d"}} 25 | {{`{{trunc 5 "hello world"}}`}}: {{trunc 5 "hello world"}} 26 | {{`{{abbrev 5 "hello world"}}`}}: {{abbrev 5 "hello world"}} 27 | {{`{{abbrevboth 5 10 "1234 5678 9123"}}`}}: {{abbrevboth 5 10 "1234 5678 9123"}} 28 | {{`{{initials "First Try"}}`}}: {{initials "First Try"}} 29 | {{`{{randNumeric 3}}`}}: {{randNumeric 3}} 30 | {{`{{- /*{{wrap 80 $someText}}*/}}`}}: {{- /*{{wrap 80 $someText}}*/}} 31 | {{`{{wrapWith 5 "\t" "Hello World"}}`}}: {{wrapWith 5 "\t" "Hello World"}} 32 | {{`{{contains "cat" "catch"}}`}}: {{contains "cat" "catch"}} 33 | {{`{{hasPrefix "cat" "catch"}}`}}: {{hasPrefix "cat" "catch"}} 34 | {{`{{cat "hello" "beautiful" "world"}}`}}: {{cat "hello" "beautiful" "world"}} 35 | {{`{{- /*{{indent 4 $lots_of_text}}*/}}`}}: {{- /*{{indent 4 $lots_of_text}}*/}} 36 | {{`{{- /*{{indent 4 $lots_of_text}}*/}}`}}: {{- /*{{indent 4 $lots_of_text}}*/}} 37 | {{`{{"I Am Henry VIII" | replace " " "-"}}`}}: {{"I Am Henry VIII" | replace " " "-"}} 38 | {{`{{len .Service.Method | plural "one anchovy" "many anchovies"}}`}}: {{len .Service.Method | plural "one anchovy" "many anchovies"}} 39 | {{`{{snakecase "FirstName"}}`}}: {{snakecase "FirstName"}} 40 | {{`{{camelcase "http_server"}}`}}: {{camelcase "http_server"}} 41 | {{`{{shuffle "hello"}}`}}: {{shuffle "hello"}} 42 | {{`{{regexMatch "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" "test@acme.com"}}`}}: {{regexMatch "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" "test@acme.com"}} 43 | {{`{{- /*{{regexFindAll "[2,4,6,8]" "123456789"}}*/}}`}}: {{- /*{{regexFindAll "[2,4,6,8]" "123456789"}}*/}} 44 | {{`{{regexFind "[a-zA-Z][1-9]" "abcd1234"}}`}}: {{regexFind "[a-zA-Z][1-9]" "abcd1234"}} 45 | {{`{{regexReplaceAll "a(x*)b" "-ab-axxb-" "${1}W"}}`}}: {{regexReplaceAll "a(x*)b" "-ab-axxb-" "${1}W"}} 46 | {{`{{regexReplaceAllLiteral "a(x*)b" "-ab-axxb-" "${1}"}}`}}: {{regexReplaceAllLiteral "a(x*)b" "-ab-axxb-" "${1}"}} 47 | {{`{{regexSplit "z+" "pizza" -1}}`}}: {{regexSplit "z+" "pizza" -1}} 48 | 49 | # Get one specific method on array method using index 50 | {{`{{ index .Service.Method 1 }}`}}: {{ index .Service.Method 1 }} 51 | 52 | # Sprig: advanced 53 | {{`{{if contains "cat" "catch"}}yes{{else}}no{{end}}`}}: {{if contains "cat" "catch"}}yes{{else}}no{{end}} 54 | {{`{{1 | plural "one anchovy" "many anchovies"}}`}}: {{1 | plural "one anchovy" "many anchovies"}} 55 | {{`{{2 | plural "one anchovy" "many anchovies"}}`}}: {{2 | plural "one anchovy" "many anchovies"}} 56 | {{`{{3 | plural "one anchovy" "many anchovies"}}`}}: {{3 | plural "one anchovy" "many anchovies"}} 57 | 58 | # TODO: more sprig examples 59 | # TODO: all built-in examples -------------------------------------------------------------------------------- /slides/README.md: -------------------------------------------------------------------------------- 1 | # [fit] Protobuf & Code Generation 2 | 3 | ### 2016, by Manfred Touron (@moul) 4 | 5 | --- 6 | 7 | # overview 8 | 9 | * go-kit is an amazing framework to develop strong micro services 10 | * but it requires a lot of boilerplate code 11 | * return on experience on go-kit boilerplate code generation 12 | 13 | --- 14 | 15 | # protobuf? 16 | 17 | * limited to exchanges (methods and models) 18 | * extendable with plugins 19 | * contract-based 20 | * universal 21 | 22 | --- 23 | 24 | # code generation? 25 | 26 | * the good old ./generate.sh bash script 27 | * go:generate 28 | * make 29 | * protobuf + [protoc-gen-gotemplate](https://moul.io/protoc-gen-gotemplate) 30 | 31 | --- 32 | 33 | # go-kit 34 | 35 | * protobuf-first, rpc-first service framework in Golang 36 | * abstract services, endpoints, transports 37 | * requires a lot of boilerplate code in multiple packages 38 | 39 | --- 40 | 41 | # example: `session.proto` 42 | 43 | ```protobuf 44 | syntax = "proto3"; 45 | package session; 46 | 47 | service SessionService { 48 | rpc Login(LoginRequest) returns (LoginResponse) {} 49 | } 50 | 51 | message LoginRequest { 52 | string username = 1; 53 | string password = 2; 54 | } 55 | 56 | message LoginResponse { 57 | string token = 1; 58 | string err_msg = 2; 59 | } 60 | ``` 61 | 62 | --- 63 | 64 | # example: `session.go` 65 | 66 | ```go 67 | package sessionsvc 68 | 69 | import ( 70 | "fmt" 71 | "golang.org/x/net/context" 72 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/session/gen/pb" 73 | ) 74 | 75 | type Service struct{} 76 | 77 | func New() pb.SessionServiceServer { 78 | return &Service{} 79 | } 80 | 81 | func (svc *Service) Login(ctx context.Context, in *pb.LoginRequest) (*pb.LoginResponse, error) { 82 | // custon code here 83 | return nil, fmt.Errorf("not implemented") 84 | } 85 | ``` 86 | 87 | --- 88 | 89 | ##### example: `{{.File.Package}}/gen/transports/http/http.go.tmpl` 90 | 91 | ```go 92 | // source: templates/{{.File.Package}}/gen/transports/http/http.go.tmpl 93 | package {{.File.Package}}_httptransport 94 | import ( 95 | gokit_endpoint "github.com/go-kit/kit/endpoint" 96 | httptransport "github.com/go-kit/kit/transport/http" 97 | endpoints "moul.io/protoc-gen-gotemplate/examples/go-kit/services/{{.File.Package}}/gen/endpoints" 98 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/{{.File.Package}}/gen/pb" 99 | ) 100 | ``` 101 | 102 | ```go 103 | // result: services/user/gen/transports/http/http.go 104 | package user_httptransport 105 | import ( 106 | gokit_endpoint "github.com/go-kit/kit/endpoint" 107 | httptransport "github.com/go-kit/kit/transport/http" 108 | endpoints "moul.io/protoc-gen-gotemplate/examples/go-kit/services/user/gen/endpoints" 109 | pb "moul.io/protoc-gen-gotemplate/examples/go-kit/services/user/gen/pb" 110 | ) 111 | ``` 112 | 113 | --- 114 | 115 | ##### example: `{{.File.Package}}/gen/transports/http/http.go.tmpl` 116 | 117 | ```go 118 | // source: templates/{{.File.Package}}/gen/transports/http/http.go.tmpl 119 | {{range .Service.Method}} 120 | func Make{{.Name}}Handler(ctx context.Context, svc pb.{{$file.Package | title}}ServiceServer, endpoint gokit_endpoint.Endpoint) *httptransport.Server { 121 | return httptransport.NewServer( 122 | ctx, 123 | endpoint, 124 | decode{{.Name}}Request, 125 | encode{{.Name}}Response, 126 | []httptransport.ServerOption{}..., 127 | ) 128 | } 129 | {{end}} 130 | ``` 131 | 132 | ```go 133 | // result: services/user/gen/transports/http/http.go 134 | func MakeGetUserHandler(ctx context.Context, svc pb.UserServiceServer, endpoint gokit_endpoint.Endpoint) *httptransport.Server { 135 | return httptransport.NewServer( 136 | ctx, 137 | endpoint, 138 | decodeGetUserRequest, 139 | encodeGetUserResponse, 140 | []httptransport.ServerOption{}..., 141 | ) 142 | } 143 | ``` 144 | 145 | --- 146 | 147 | ##### example: `{{.File.Package}}/gen/transports/http/http.go.tmpl` 148 | 149 | ```go 150 | // source: templates/{{.File.Package}}/gen/transports/http/http.go.tmpl 151 | func RegisterHandlers(ctx context.Context, svc pb.{{$file.Package | title}}ServiceServer, mux *http.ServeMux, endpoints endpoints.Endpoints) error { 152 | {{range .Service.Method}} 153 | log.Println("new HTTP endpoint: \"/{{.Name}}\" (service={{$file.Package | title}})") 154 | mux.Handle("/{{.Name}}", Make{{.Name}}Handler(ctx, svc, endpoints.{{.Name}}Endpoint)) 155 | {{end}} 156 | return nil 157 | } 158 | ``` 159 | 160 | ```go 161 | // result: services/user/gen/transports/http/http.go 162 | func RegisterHandlers(ctx context.Context, svc pb.UserServiceServer, mux *http.ServeMux, endpoints endpoints.Endpoints) error { 163 | 164 | log.Println("new HTTP endpoint: \"/CreateUser\" (service=User)") 165 | mux.Handle("/CreateUser", MakeCreateUserHandler(ctx, svc, endpoints.CreateUserEndpoint)) 166 | 167 | log.Println("new HTTP endpoint: \"/GetUser\" (service=User)") 168 | mux.Handle("/GetUser", MakeGetUserHandler(ctx, svc, endpoints.GetUserEndpoint)) 169 | 170 | return nil 171 | } 172 | ``` 173 | 174 | --- 175 | 176 | #### `protoc --gogo_out=plugins=grpc:. ./services/*/*.proto` 177 | 178 | --- 179 | 180 | #### `protoc --gotemplate_out=template_dir=./templates:services ./services/*/*.proto` 181 | 182 | --- 183 | 184 |  185 | 186 | --- 187 | 188 |  189 | 190 | ## 3 services 191 | ## 6 methods 192 | ## 149 custom lines 193 | ## 1429 generated lines 194 | ## business focus 195 | 196 | --- 197 | 198 | # generation usages 199 | 200 | * go-kit boilerplate (see [examples/go-kit](https://moul.io/protoc-gen-gotemplate/tree/master/examples/go-kit)) 201 | * k8s configuration 202 | * Dockerfile 203 | * documentation 204 | * unit-tests 205 | * fun 206 | 207 | --- 208 | 209 | # pros 210 | 211 | * small custom codebase 212 | * templates shipped with code 213 | * hardly typed, no reflects 214 | * genericity 215 | * contrat terms (protobuf) respected 216 | * not limited to a language 217 | 218 | --- 219 | 220 | # cons 221 | 222 | * the author needs to write its own templates 223 | * sometimes difficult to generate valid code 224 | * not enough helpers around the code generation yet 225 | 226 | --- 227 | 228 | # improvement ideas 229 | 230 | * Support protobufs extensions (i.e, annotations.probo) 231 | * Generate one file from multiple services 232 | * Add more helpers around the code generation 233 | 234 | --- 235 | 236 | # conclusion 237 | 238 | * Useful to keep everything standard 239 | * The awesomeness of go-kit without the hassle of writing boilerplate code 240 | * Always up-to-date with the contracts 241 | 242 | --- 243 | 244 | # questions? 245 | 246 | ### moul.io/protoc-gen-gotemplate 247 | ### @moul 248 | -------------------------------------------------------------------------------- /examples/go-kit/services/session/gen/pb/pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. 2 | // source: services/session/session.proto 3 | // DO NOT EDIT! 4 | 5 | /* 6 | Package session is a generated protocol buffer package. 7 | 8 | It is generated from these files: 9 | services/session/session.proto 10 | 11 | It has these top-level messages: 12 | LoginRequest 13 | LoginResponse 14 | */ 15 | package session 16 | 17 | import proto "github.com/golang/protobuf/proto" 18 | import fmt "fmt" 19 | import math "math" 20 | 21 | import ( 22 | context "golang.org/x/net/context" 23 | grpc "google.golang.org/grpc" 24 | ) 25 | 26 | // Reference imports to suppress errors if they are not otherwise used. 27 | var _ = proto.Marshal 28 | var _ = fmt.Errorf 29 | var _ = math.Inf 30 | 31 | // This is a compile-time assertion to ensure that this generated file 32 | // is compatible with the proto package it is being compiled against. 33 | // A compilation error at this line likely means your copy of the 34 | // proto package needs to be updated. 35 | const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package 36 | 37 | type LoginRequest struct { 38 | Username string `protobuf:"bytes,1,opt,name=username" json:"username,omitempty"` 39 | Password string `protobuf:"bytes,2,opt,name=password" json:"password,omitempty"` 40 | } 41 | 42 | func (m *LoginRequest) Reset() { *m = LoginRequest{} } 43 | func (m *LoginRequest) String() string { return proto.CompactTextString(m) } 44 | func (*LoginRequest) ProtoMessage() {} 45 | func (*LoginRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } 46 | 47 | func (m *LoginRequest) GetUsername() string { 48 | if m != nil { 49 | return m.Username 50 | } 51 | return "" 52 | } 53 | 54 | func (m *LoginRequest) GetPassword() string { 55 | if m != nil { 56 | return m.Password 57 | } 58 | return "" 59 | } 60 | 61 | type LoginResponse struct { 62 | Token string `protobuf:"bytes,1,opt,name=token" json:"token,omitempty"` 63 | ErrMsg string `protobuf:"bytes,2,opt,name=err_msg,json=errMsg" json:"err_msg,omitempty"` 64 | } 65 | 66 | func (m *LoginResponse) Reset() { *m = LoginResponse{} } 67 | func (m *LoginResponse) String() string { return proto.CompactTextString(m) } 68 | func (*LoginResponse) ProtoMessage() {} 69 | func (*LoginResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } 70 | 71 | func (m *LoginResponse) GetToken() string { 72 | if m != nil { 73 | return m.Token 74 | } 75 | return "" 76 | } 77 | 78 | func (m *LoginResponse) GetErrMsg() string { 79 | if m != nil { 80 | return m.ErrMsg 81 | } 82 | return "" 83 | } 84 | 85 | func init() { 86 | proto.RegisterType((*LoginRequest)(nil), "session.LoginRequest") 87 | proto.RegisterType((*LoginResponse)(nil), "session.LoginResponse") 88 | } 89 | 90 | // Reference imports to suppress errors if they are not otherwise used. 91 | var _ context.Context 92 | var _ grpc.ClientConn 93 | 94 | // This is a compile-time assertion to ensure that this generated file 95 | // is compatible with the grpc package it is being compiled against. 96 | const _ = grpc.SupportPackageIsVersion4 97 | 98 | // Client API for SessionService service 99 | 100 | type SessionServiceClient interface { 101 | Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error) 102 | } 103 | 104 | type sessionServiceClient struct { 105 | cc *grpc.ClientConn 106 | } 107 | 108 | func NewSessionServiceClient(cc *grpc.ClientConn) SessionServiceClient { 109 | return &sessionServiceClient{cc} 110 | } 111 | 112 | func (c *sessionServiceClient) Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error) { 113 | out := new(LoginResponse) 114 | err := grpc.Invoke(ctx, "/session.SessionService/Login", in, out, c.cc, opts...) 115 | if err != nil { 116 | return nil, err 117 | } 118 | return out, nil 119 | } 120 | 121 | // Server API for SessionService service 122 | 123 | type SessionServiceServer interface { 124 | Login(context.Context, *LoginRequest) (*LoginResponse, error) 125 | } 126 | 127 | func RegisterSessionServiceServer(s *grpc.Server, srv SessionServiceServer) { 128 | s.RegisterService(&_SessionService_serviceDesc, srv) 129 | } 130 | 131 | func _SessionService_Login_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 132 | in := new(LoginRequest) 133 | if err := dec(in); err != nil { 134 | return nil, err 135 | } 136 | if interceptor == nil { 137 | return srv.(SessionServiceServer).Login(ctx, in) 138 | } 139 | info := &grpc.UnaryServerInfo{ 140 | Server: srv, 141 | FullMethod: "/session.SessionService/Login", 142 | } 143 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 144 | return srv.(SessionServiceServer).Login(ctx, req.(*LoginRequest)) 145 | } 146 | return interceptor(ctx, in, info, handler) 147 | } 148 | 149 | var _SessionService_serviceDesc = grpc.ServiceDesc{ 150 | ServiceName: "session.SessionService", 151 | HandlerType: (*SessionServiceServer)(nil), 152 | Methods: []grpc.MethodDesc{ 153 | { 154 | MethodName: "Login", 155 | Handler: _SessionService_Login_Handler, 156 | }, 157 | }, 158 | Streams: []grpc.StreamDesc{}, 159 | Metadata: "services/session/session.proto", 160 | } 161 | 162 | func init() { proto.RegisterFile("services/session/session.proto", fileDescriptor0) } 163 | 164 | var fileDescriptor0 = []byte{ 165 | // 188 bytes of a gzipped FileDescriptorProto 166 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0x92, 0x2b, 0x4e, 0x2d, 0x2a, 167 | 0xcb, 0x4c, 0x4e, 0x2d, 0xd6, 0x2f, 0x4e, 0x2d, 0x2e, 0xce, 0xcc, 0xcf, 0x83, 0xd1, 0x7a, 0x05, 168 | 0x45, 0xf9, 0x25, 0xf9, 0x42, 0xec, 0x50, 0xae, 0x92, 0x1b, 0x17, 0x8f, 0x4f, 0x7e, 0x7a, 0x66, 169 | 0x5e, 0x50, 0x6a, 0x61, 0x69, 0x6a, 0x71, 0x89, 0x90, 0x14, 0x17, 0x47, 0x69, 0x71, 0x6a, 0x51, 170 | 0x5e, 0x62, 0x6e, 0xaa, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x67, 0x10, 0x9c, 0x0f, 0x92, 0x2b, 0x48, 171 | 0x2c, 0x2e, 0x2e, 0xcf, 0x2f, 0x4a, 0x91, 0x60, 0x82, 0xc8, 0xc1, 0xf8, 0x4a, 0x76, 0x5c, 0xbc, 172 | 0x50, 0x73, 0x8a, 0x0b, 0xf2, 0xf3, 0x8a, 0x53, 0x85, 0x44, 0xb8, 0x58, 0x4b, 0xf2, 0xb3, 0x53, 173 | 0xf3, 0xa0, 0xa6, 0x40, 0x38, 0x42, 0xe2, 0x5c, 0xec, 0xa9, 0x45, 0x45, 0xf1, 0xb9, 0xc5, 0xe9, 174 | 0x50, 0x13, 0xd8, 0x52, 0x8b, 0x8a, 0x7c, 0x8b, 0xd3, 0x8d, 0xbc, 0xb8, 0xf8, 0x82, 0x21, 0x4e, 175 | 0x0a, 0x86, 0xb8, 0x5c, 0xc8, 0x82, 0x8b, 0x15, 0x6c, 0xa2, 0x90, 0xa8, 0x1e, 0xcc, 0xed, 0xc8, 176 | 0x2e, 0x95, 0x12, 0x43, 0x17, 0x86, 0x58, 0xac, 0xc4, 0x90, 0xc4, 0x06, 0xf6, 0xa3, 0x31, 0x20, 177 | 0x00, 0x00, 0xff, 0xff, 0x29, 0x3f, 0x91, 0xc7, 0x05, 0x01, 0x00, 0x00, 178 | } 179 | -------------------------------------------------------------------------------- /encoder.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "log" 6 | "net/url" 7 | "os" 8 | "path/filepath" 9 | "strings" 10 | "text/template" 11 | "time" 12 | 13 | "github.com/golang/protobuf/protoc-gen-go/descriptor" 14 | plugin_go "github.com/golang/protobuf/protoc-gen-go/plugin" 15 | 16 | pgghelpers "moul.io/protoc-gen-gotemplate/helpers" 17 | ) 18 | 19 | type GenericTemplateBasedEncoder struct { 20 | templateDir string 21 | service *descriptor.ServiceDescriptorProto 22 | file *descriptor.FileDescriptorProto 23 | enum []*descriptor.EnumDescriptorProto 24 | debug bool 25 | destinationDir string 26 | } 27 | 28 | type Ast struct { 29 | BuildDate time.Time `json:"build-date"` 30 | BuildHostname string `json:"build-hostname"` 31 | BuildUser string `json:"build-user"` 32 | GoPWD string `json:"go-pwd,omitempty"` 33 | PWD string `json:"pwd"` 34 | Debug bool `json:"debug"` 35 | DestinationDir string `json:"destination-dir"` 36 | File *descriptor.FileDescriptorProto `json:"file"` 37 | RawFilename string `json:"raw-filename"` 38 | Filename string `json:"filename"` 39 | TemplateDir string `json:"template-dir"` 40 | Service *descriptor.ServiceDescriptorProto `json:"service"` 41 | Enum []*descriptor.EnumDescriptorProto `json:"enum"` 42 | } 43 | 44 | func NewGenericServiceTemplateBasedEncoder(templateDir string, service *descriptor.ServiceDescriptorProto, file *descriptor.FileDescriptorProto, debug bool, destinationDir string) (e *GenericTemplateBasedEncoder) { 45 | e = &GenericTemplateBasedEncoder{ 46 | service: service, 47 | file: file, 48 | templateDir: templateDir, 49 | debug: debug, 50 | destinationDir: destinationDir, 51 | enum: file.GetEnumType(), 52 | } 53 | if debug { 54 | log.Printf("new encoder: file=%q service=%q template-dir=%q", file.GetName(), service.GetName(), templateDir) 55 | } 56 | pgghelpers.InitPathMap(file) 57 | 58 | return 59 | } 60 | 61 | func NewGenericTemplateBasedEncoder(templateDir string, file *descriptor.FileDescriptorProto, debug bool, destinationDir string) (e *GenericTemplateBasedEncoder) { 62 | e = &GenericTemplateBasedEncoder{ 63 | service: nil, 64 | file: file, 65 | templateDir: templateDir, 66 | enum: file.GetEnumType(), 67 | debug: debug, 68 | destinationDir: destinationDir, 69 | } 70 | if debug { 71 | log.Printf("new encoder: file=%q template-dir=%q", file.GetName(), templateDir) 72 | } 73 | pgghelpers.InitPathMap(file) 74 | 75 | return 76 | } 77 | 78 | func (e *GenericTemplateBasedEncoder) templates() ([]string, error) { 79 | filenames := []string{} 80 | 81 | err := filepath.Walk(e.templateDir, func(path string, info os.FileInfo, err error) error { 82 | if err != nil { 83 | return err 84 | } 85 | if info.IsDir() { 86 | return nil 87 | } 88 | if filepath.Ext(path) != ".tmpl" { 89 | return nil 90 | } 91 | rel, err := filepath.Rel(e.templateDir, path) 92 | if err != nil { 93 | return err 94 | } 95 | if e.debug { 96 | log.Printf("new template: %q", rel) 97 | } 98 | 99 | filenames = append(filenames, rel) 100 | return nil 101 | }) 102 | return filenames, err 103 | } 104 | 105 | func (e *GenericTemplateBasedEncoder) genAst(templateFilename string) (*Ast, error) { 106 | // prepare the ast passed to the template engine 107 | hostname, err := os.Hostname() 108 | if err != nil { 109 | return nil, err 110 | } 111 | pwd, err := os.Getwd() 112 | if err != nil { 113 | return nil, err 114 | } 115 | goPwd := "" 116 | if os.Getenv("GOPATH") != "" { 117 | goPwd, err = filepath.Rel(os.Getenv("GOPATH")+"/src", pwd) 118 | if err != nil { 119 | return nil, err 120 | } 121 | if strings.Contains(goPwd, "../") { 122 | goPwd = "" 123 | } 124 | } 125 | ast := Ast{ 126 | BuildDate: time.Now(), 127 | BuildHostname: hostname, 128 | BuildUser: os.Getenv("USER"), 129 | PWD: pwd, 130 | GoPWD: goPwd, 131 | File: e.file, 132 | TemplateDir: e.templateDir, 133 | DestinationDir: e.destinationDir, 134 | RawFilename: templateFilename, 135 | Filename: "", 136 | Service: e.service, 137 | Enum: e.enum, 138 | } 139 | buffer := new(bytes.Buffer) 140 | 141 | unescaped, err := url.QueryUnescape(templateFilename) 142 | if err != nil { 143 | log.Printf("failed to unescape filepath %q: %v", templateFilename, err) 144 | } else { 145 | templateFilename = unescaped 146 | } 147 | 148 | tmpl, err := template.New("").Funcs(pgghelpers.ProtoHelpersFuncMap).Parse(templateFilename) 149 | if err != nil { 150 | return nil, err 151 | } 152 | if err := tmpl.Execute(buffer, ast); err != nil { 153 | return nil, err 154 | } 155 | ast.Filename = buffer.String() 156 | return &ast, nil 157 | } 158 | 159 | func (e *GenericTemplateBasedEncoder) buildContent(templateFilename string) (string, string, error) { 160 | // initialize template engine 161 | fullPath := filepath.Join(e.templateDir, templateFilename) 162 | templateName := filepath.Base(fullPath) 163 | tmpl, err := template.New(templateName).Funcs(pgghelpers.ProtoHelpersFuncMap).ParseFiles(fullPath) 164 | if err != nil { 165 | return "", "", err 166 | } 167 | 168 | ast, err := e.genAst(templateFilename) 169 | if err != nil { 170 | return "", "", err 171 | } 172 | 173 | // generate the content 174 | buffer := new(bytes.Buffer) 175 | if err := tmpl.Execute(buffer, ast); err != nil { 176 | return "", "", err 177 | } 178 | 179 | return buffer.String(), ast.Filename, nil 180 | } 181 | 182 | func (e *GenericTemplateBasedEncoder) Files() []*plugin_go.CodeGeneratorResponse_File { 183 | templates, err := e.templates() 184 | if err != nil { 185 | log.Fatalf("cannot get templates from %q: %v", e.templateDir, err) 186 | } 187 | 188 | length := len(templates) 189 | files := make([]*plugin_go.CodeGeneratorResponse_File, 0, length) 190 | errChan := make(chan error, length) 191 | resultChan := make(chan *plugin_go.CodeGeneratorResponse_File, length) 192 | for _, templateFilename := range templates { 193 | go func(tmpl string) { 194 | var translatedFilename, content string 195 | content, translatedFilename, err = e.buildContent(tmpl) 196 | if err != nil { 197 | errChan <- err 198 | return 199 | } 200 | filename := translatedFilename[:len(translatedFilename)-len(".tmpl")] 201 | 202 | resultChan <- &plugin_go.CodeGeneratorResponse_File{ 203 | Content: &content, 204 | Name: &filename, 205 | } 206 | }(templateFilename) 207 | } 208 | for i := 0; i < length; i++ { 209 | select { 210 | case f := <-resultChan: 211 | files = append(files, f) 212 | case err = <-errChan: 213 | panic(err) 214 | } 215 | } 216 | return files 217 | } 218 | -------------------------------------------------------------------------------- /repos.bzl: -------------------------------------------------------------------------------- 1 | load("@bazel_gazelle//:deps.bzl", "go_repository") 2 | 3 | def go_repositories(): 4 | # keep 5 | go_repository( 6 | name = "io_k8s_klog", 7 | importpath = "k8s.io/klog", 8 | sum = "h1:Pt+yjF5aB1xDSVbau4VsWe+dQNzA0qv1LlXdC2dF6Q8=", 9 | version = "v1.0.0", 10 | ) 11 | go_repository( 12 | name = "com_github_aokoli_goutils", 13 | build_file_generation = "on", 14 | build_file_proto_mode = "disable", 15 | importpath = "github.com/aokoli/goutils", 16 | sum = "h1:Bn0iqJ/349f606hR0juIGyheAI6+hyg9XUOLhN9udLo=", 17 | version = "v0.0.0-20170502144750-e57d01ace047", 18 | ) 19 | go_repository( 20 | name = "com_github_davecgh_go_spew", 21 | build_file_generation = "on", 22 | build_file_proto_mode = "disable", 23 | importpath = "github.com/davecgh/go-spew", 24 | sum = "h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=", 25 | version = "v1.1.0", 26 | ) 27 | go_repository( 28 | name = "com_github_golang_glog", 29 | build_file_generation = "on", 30 | build_file_proto_mode = "disable", 31 | importpath = "github.com/golang/glog", 32 | sum = "h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=", 33 | version = "v0.0.0-20160126235308-23def4e6c14b", 34 | ) 35 | go_repository( 36 | name = "com_github_golang_protobuf", 37 | build_file_generation = "on", 38 | build_file_proto_mode = "disable", 39 | importpath = "github.com/golang/protobuf", 40 | sum = "h1:fE/yi9pibxGEc0gSJuEShcsBXE2d5FW3OudsjE9tKzQ=", 41 | version = "v0.0.0-20161117033126-8ee79997227b", 42 | ) 43 | go_repository( 44 | name = "com_github_gorilla_context", 45 | build_file_generation = "on", 46 | build_file_proto_mode = "disable", 47 | importpath = "github.com/gorilla/context", 48 | sum = "h1:9oNbS1z4rVpbnkHBdPZU4jo9bSmrLpII768arSyMFgk=", 49 | version = "v0.0.0-20160226214623-1ea25387ff6f", 50 | ) 51 | go_repository( 52 | name = "com_github_gorilla_handlers", 53 | build_file_generation = "on", 54 | build_file_proto_mode = "disable", 55 | importpath = "github.com/gorilla/handlers", 56 | sum = "h1:uANqGlSIT3JwuQVokEBcvc9WAu5+v4cVD5szF5k+iIU=", 57 | version = "v0.0.0-20161028133215-e1b2144f2167", 58 | ) 59 | go_repository( 60 | name = "com_github_gorilla_mux", 61 | build_file_generation = "on", 62 | build_file_proto_mode = "disable", 63 | importpath = "github.com/gorilla/mux", 64 | sum = "h1:mq8bRov+5x+pZNR/uAHyUEgovR9gLgYFwDQIeuYi9TM=", 65 | version = "v1.5.0", 66 | ) 67 | go_repository( 68 | name = "com_github_grpc_ecosystem_grpc_gateway", 69 | build_file_generation = "on", 70 | build_file_proto_mode = "disable", 71 | importpath = "github.com/grpc-ecosystem/grpc-gateway", 72 | sum = "h1:oR2ZMoJtQccW6NIJ9yFxRqAr2rkmcNsCaZKT66A9zt4=", 73 | version = "v1.2.2", 74 | ) 75 | go_repository( 76 | name = "com_github_huandu_xstrings", 77 | build_file_generation = "on", 78 | build_file_proto_mode = "disable", 79 | importpath = "github.com/huandu/xstrings", 80 | sum = "h1:KZOP9q7J/P4eMBibPuVwuloXgd2dTbLAHRPqxw7NXOw=", 81 | version = "v0.0.0-20151130125119-3959339b3335", 82 | ) 83 | go_repository( 84 | name = "com_github_imdario_mergo", 85 | build_file_generation = "on", 86 | build_file_proto_mode = "disable", 87 | importpath = "github.com/imdario/mergo", 88 | sum = "h1:k/Biv+LJL35wkk0Hveko1nj7as4tSHkHdZaNlzn/gcQ=", 89 | version = "v0.0.0-20171009183408-7fe0c75c13ab", 90 | ) 91 | go_repository( 92 | name = "com_github_masterminds_semver", 93 | build_file_generation = "on", 94 | build_file_proto_mode = "disable", 95 | importpath = "github.com/Masterminds/semver", 96 | sum = "h1:ptelpryog9A0pR4TGFvIAvw2c8SaNrYkFtfrxhSviss=", 97 | version = "v1.2.2", 98 | ) 99 | go_repository( 100 | name = "com_github_masterminds_sprig", 101 | build_file_generation = "on", 102 | build_file_proto_mode = "disable", 103 | importpath = "github.com/Masterminds/sprig", 104 | sum = "h1:rTHERm50Xp1Cbb8x7xBCeDp//jMMqqR44EWw7KwSXUQ=", 105 | version = "v2.14.1+incompatible", 106 | ) 107 | go_repository( 108 | name = "com_github_pmezard_go_difflib", 109 | build_file_generation = "on", 110 | build_file_proto_mode = "disable", 111 | importpath = "github.com/pmezard/go-difflib", 112 | sum = "h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=", 113 | version = "v1.0.0", 114 | ) 115 | go_repository( 116 | name = "com_github_satori_go_uuid", 117 | build_file_generation = "on", 118 | build_file_proto_mode = "disable", 119 | importpath = "github.com/satori/go.uuid", 120 | sum = "h1:B9KXyj+GzIpJbV7gmr873NsY6zpbxNy24CBtGrk7jHo=", 121 | version = "v1.1.0", 122 | ) 123 | go_repository( 124 | name = "com_github_stretchr_objx", 125 | build_file_generation = "on", 126 | build_file_proto_mode = "disable", 127 | importpath = "github.com/stretchr/objx", 128 | sum = "h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=", 129 | version = "v0.1.0", 130 | ) 131 | go_repository( 132 | name = "com_github_stretchr_testify", 133 | build_file_generation = "on", 134 | build_file_proto_mode = "disable", 135 | importpath = "github.com/stretchr/testify", 136 | sum = "h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=", 137 | version = "v1.3.0", 138 | ) 139 | go_repository( 140 | name = "in_gopkg_check_v1", 141 | build_file_generation = "on", 142 | build_file_proto_mode = "disable", 143 | importpath = "gopkg.in/check.v1", 144 | sum = "h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=", 145 | version = "v0.0.0-20161208181325-20d25e280405", 146 | ) 147 | go_repository( 148 | name = "in_gopkg_yaml_v2", 149 | build_file_generation = "on", 150 | build_file_proto_mode = "disable", 151 | importpath = "gopkg.in/yaml.v2", 152 | sum = "h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=", 153 | version = "v2.2.2", 154 | ) 155 | go_repository( 156 | name = "org_golang_google_genproto", 157 | build_file_generation = "on", 158 | build_file_proto_mode = "disable", 159 | importpath = "google.golang.org/genproto", 160 | sum = "h1:xfoW+Di7qQQUnjptcGb4/rpc701e3RvfNmaywfMxQVI=", 161 | version = "v0.0.0-20170517234824-bb3573be0c48", 162 | ) 163 | go_repository( 164 | name = "org_golang_x_crypto", 165 | build_file_generation = "on", 166 | build_file_proto_mode = "disable", 167 | importpath = "golang.org/x/crypto", 168 | sum = "h1:qjfFh1YMn6m60QTGoG+IlwUMhNlXJbDyCa6EkHM/N2w=", 169 | version = "v0.0.0-20170516161655-0fe963104e9d", 170 | ) 171 | go_repository( 172 | name = "org_golang_x_sync", 173 | build_file_generation = "on", 174 | build_file_proto_mode = "disable", 175 | importpath = "golang.org/x/sync", 176 | sum = "h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw=", 177 | version = "v0.0.0-20181221193216-37e7f081c4d4", 178 | ) 179 | -------------------------------------------------------------------------------- /examples/single-package-mode/output/bbb/bbb.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. 2 | // source: bbb/bbb.proto 3 | // DO NOT EDIT! 4 | 5 | /* 6 | Package bbb is a generated protocol buffer package. 7 | 8 | It is generated from these files: 9 | bbb/bbb.proto 10 | 11 | It has these top-level messages: 12 | BbbRequest 13 | BbbReply 14 | */ 15 | package bbb 16 | 17 | import proto "github.com/golang/protobuf/proto" 18 | import fmt "fmt" 19 | import math "math" 20 | import the_aaa_package "moul.io/protoc-gen-gotemplate/examples/single-package-mode/output/aaa" 21 | 22 | import ( 23 | context "golang.org/x/net/context" 24 | grpc "google.golang.org/grpc" 25 | ) 26 | 27 | // Reference imports to suppress errors if they are not otherwise used. 28 | var _ = proto.Marshal 29 | var _ = fmt.Errorf 30 | var _ = math.Inf 31 | 32 | // This is a compile-time assertion to ensure that this generated file 33 | // is compatible with the proto package it is being compiled against. 34 | // A compilation error at this line likely means your copy of the 35 | // proto package needs to be updated. 36 | const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package 37 | 38 | type BbbRequest struct { 39 | Enable bool `protobuf:"varint,1,opt,name=enable" json:"enable,omitempty"` 40 | } 41 | 42 | func (m *BbbRequest) Reset() { *m = BbbRequest{} } 43 | func (m *BbbRequest) String() string { return proto.CompactTextString(m) } 44 | func (*BbbRequest) ProtoMessage() {} 45 | func (*BbbRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } 46 | 47 | func (m *BbbRequest) GetEnable() bool { 48 | if m != nil { 49 | return m.Enable 50 | } 51 | return false 52 | } 53 | 54 | type BbbReply struct { 55 | Done bool `protobuf:"varint,1,opt,name=done" json:"done,omitempty"` 56 | } 57 | 58 | func (m *BbbReply) Reset() { *m = BbbReply{} } 59 | func (m *BbbReply) String() string { return proto.CompactTextString(m) } 60 | func (*BbbReply) ProtoMessage() {} 61 | func (*BbbReply) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } 62 | 63 | func (m *BbbReply) GetDone() bool { 64 | if m != nil { 65 | return m.Done 66 | } 67 | return false 68 | } 69 | 70 | func init() { 71 | proto.RegisterType((*BbbRequest)(nil), "the.bbb.package.BbbRequest") 72 | proto.RegisterType((*BbbReply)(nil), "the.bbb.package.BbbReply") 73 | } 74 | 75 | // Reference imports to suppress errors if they are not otherwise used. 76 | var _ context.Context 77 | var _ grpc.ClientConn 78 | 79 | // This is a compile-time assertion to ensure that this generated file 80 | // is compatible with the grpc package it is being compiled against. 81 | const _ = grpc.SupportPackageIsVersion4 82 | 83 | // Client API for BbbService service 84 | 85 | type BbbServiceClient interface { 86 | Aaa(ctx context.Context, in *the_aaa_package.AaaRequest, opts ...grpc.CallOption) (*the_aaa_package.AaaReply, error) 87 | Bbb(ctx context.Context, in *BbbRequest, opts ...grpc.CallOption) (*BbbReply, error) 88 | } 89 | 90 | type bbbServiceClient struct { 91 | cc *grpc.ClientConn 92 | } 93 | 94 | func NewBbbServiceClient(cc *grpc.ClientConn) BbbServiceClient { 95 | return &bbbServiceClient{cc} 96 | } 97 | 98 | func (c *bbbServiceClient) Aaa(ctx context.Context, in *the_aaa_package.AaaRequest, opts ...grpc.CallOption) (*the_aaa_package.AaaReply, error) { 99 | out := new(the_aaa_package.AaaReply) 100 | err := grpc.Invoke(ctx, "/the.bbb.package.BbbService/Aaa", in, out, c.cc, opts...) 101 | if err != nil { 102 | return nil, err 103 | } 104 | return out, nil 105 | } 106 | 107 | func (c *bbbServiceClient) Bbb(ctx context.Context, in *BbbRequest, opts ...grpc.CallOption) (*BbbReply, error) { 108 | out := new(BbbReply) 109 | err := grpc.Invoke(ctx, "/the.bbb.package.BbbService/Bbb", in, out, c.cc, opts...) 110 | if err != nil { 111 | return nil, err 112 | } 113 | return out, nil 114 | } 115 | 116 | // Server API for BbbService service 117 | 118 | type BbbServiceServer interface { 119 | Aaa(context.Context, *the_aaa_package.AaaRequest) (*the_aaa_package.AaaReply, error) 120 | Bbb(context.Context, *BbbRequest) (*BbbReply, error) 121 | } 122 | 123 | func RegisterBbbServiceServer(s *grpc.Server, srv BbbServiceServer) { 124 | s.RegisterService(&_BbbService_serviceDesc, srv) 125 | } 126 | 127 | func _BbbService_Aaa_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 128 | in := new(the_aaa_package.AaaRequest) 129 | if err := dec(in); err != nil { 130 | return nil, err 131 | } 132 | if interceptor == nil { 133 | return srv.(BbbServiceServer).Aaa(ctx, in) 134 | } 135 | info := &grpc.UnaryServerInfo{ 136 | Server: srv, 137 | FullMethod: "/the.bbb.package.BbbService/Aaa", 138 | } 139 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 140 | return srv.(BbbServiceServer).Aaa(ctx, req.(*the_aaa_package.AaaRequest)) 141 | } 142 | return interceptor(ctx, in, info, handler) 143 | } 144 | 145 | func _BbbService_Bbb_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 146 | in := new(BbbRequest) 147 | if err := dec(in); err != nil { 148 | return nil, err 149 | } 150 | if interceptor == nil { 151 | return srv.(BbbServiceServer).Bbb(ctx, in) 152 | } 153 | info := &grpc.UnaryServerInfo{ 154 | Server: srv, 155 | FullMethod: "/the.bbb.package.BbbService/Bbb", 156 | } 157 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 158 | return srv.(BbbServiceServer).Bbb(ctx, req.(*BbbRequest)) 159 | } 160 | return interceptor(ctx, in, info, handler) 161 | } 162 | 163 | var _BbbService_serviceDesc = grpc.ServiceDesc{ 164 | ServiceName: "the.bbb.package.BbbService", 165 | HandlerType: (*BbbServiceServer)(nil), 166 | Methods: []grpc.MethodDesc{ 167 | { 168 | MethodName: "Aaa", 169 | Handler: _BbbService_Aaa_Handler, 170 | }, 171 | { 172 | MethodName: "Bbb", 173 | Handler: _BbbService_Bbb_Handler, 174 | }, 175 | }, 176 | Streams: []grpc.StreamDesc{}, 177 | Metadata: "bbb/bbb.proto", 178 | } 179 | 180 | func init() { proto.RegisterFile("bbb/bbb.proto", fileDescriptor0) } 181 | 182 | var fileDescriptor0 = []byte{ 183 | // 242 bytes of a gzipped FileDescriptorProto 184 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x90, 0x41, 0x4b, 0x03, 0x31, 185 | 0x10, 0x85, 0x59, 0x2a, 0xa5, 0x04, 0x8a, 0x90, 0x83, 0x68, 0x05, 0x91, 0xe2, 0xc1, 0xcb, 0x26, 186 | 0xa0, 0xe7, 0x1e, 0xba, 0x77, 0x11, 0xea, 0xcd, 0xdb, 0xcc, 0x76, 0x48, 0x17, 0x93, 0x9d, 0xd8, 187 | 0x9d, 0x88, 0xfd, 0x0b, 0xfe, 0x6a, 0xd9, 0x34, 0xa2, 0x60, 0x6f, 0x19, 0xde, 0xbc, 0xf7, 0xbd, 188 | 0x8c, 0x9a, 0x23, 0xa2, 0x45, 0x44, 0x13, 0xf7, 0x2c, 0xac, 0xcf, 0x65, 0x47, 0x26, 0x8f, 0xd0, 189 | 0xbe, 0x81, 0xa3, 0xc5, 0x1c, 0x00, 0x2c, 0x00, 0x1c, 0xf5, 0xe5, 0x9d, 0x52, 0x0d, 0xe2, 0x86, 190 | 0xde, 0x13, 0x0d, 0xa2, 0x2f, 0xd4, 0x94, 0x7a, 0x40, 0x4f, 0x97, 0xd5, 0x6d, 0x75, 0x3f, 0xdb, 191 | 0x94, 0x69, 0x79, 0xa3, 0x66, 0x79, 0x2b, 0xfa, 0x83, 0xd6, 0xea, 0x6c, 0xcb, 0xfd, 0xcf, 0x46, 192 | 0x7e, 0x3f, 0x7c, 0x55, 0x39, 0xe6, 0x85, 0xf6, 0x1f, 0x5d, 0x4b, 0x7a, 0xa5, 0x26, 0x6b, 0x00, 193 | 0x7d, 0x6d, 0x46, 0x78, 0x66, 0x1d, 0xe1, 0x66, 0x0d, 0x50, 0x50, 0x8b, 0xab, 0xd3, 0xe2, 0x48, 194 | 0x58, 0xa9, 0x49, 0x83, 0x58, 0xec, 0x7f, 0xba, 0x9b, 0xdf, 0xa6, 0xc5, 0xfe, 0x4f, 0x8c, 0xfe, 195 | 0xd0, 0x3c, 0xbf, 0x3e, 0xb9, 0x4e, 0x76, 0x09, 0x4d, 0xcb, 0xc1, 0x06, 0x4e, 0xde, 0xe6, 0xbf, 196 | 0xb6, 0xb5, 0xa3, 0xbe, 0x76, 0x2c, 0x14, 0xa2, 0x07, 0x21, 0x4b, 0x9f, 0x10, 0xa2, 0xa7, 0xc1, 197 | 0x0e, 0x5d, 0xef, 0x3c, 0xd5, 0x25, 0xa9, 0x0e, 0xbc, 0x25, 0xcb, 0x49, 0x62, 0x92, 0xf1, 0x92, 198 | 0x38, 0xcd, 0xf6, 0xc7, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0xe0, 0xe1, 0x26, 0xcb, 0x5b, 0x01, 199 | 0x00, 0x00, 200 | } 201 | -------------------------------------------------------------------------------- /examples/go-kit/services/user/gen/pb/pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. 2 | // source: services/user/user.proto 3 | // DO NOT EDIT! 4 | 5 | /* 6 | Package user is a generated protocol buffer package. 7 | 8 | It is generated from these files: 9 | services/user/user.proto 10 | 11 | It has these top-level messages: 12 | CreateUserRequest 13 | CreateUserResponse 14 | GetUserRequest 15 | GetUserResponse 16 | User 17 | */ 18 | package user 19 | 20 | import proto "github.com/golang/protobuf/proto" 21 | import fmt "fmt" 22 | import math "math" 23 | 24 | import ( 25 | context "golang.org/x/net/context" 26 | grpc "google.golang.org/grpc" 27 | ) 28 | 29 | // Reference imports to suppress errors if they are not otherwise used. 30 | var _ = proto.Marshal 31 | var _ = fmt.Errorf 32 | var _ = math.Inf 33 | 34 | // This is a compile-time assertion to ensure that this generated file 35 | // is compatible with the proto package it is being compiled against. 36 | // A compilation error at this line likely means your copy of the 37 | // proto package needs to be updated. 38 | const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package 39 | 40 | type CreateUserRequest struct { 41 | Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` 42 | } 43 | 44 | func (m *CreateUserRequest) Reset() { *m = CreateUserRequest{} } 45 | func (m *CreateUserRequest) String() string { return proto.CompactTextString(m) } 46 | func (*CreateUserRequest) ProtoMessage() {} 47 | func (*CreateUserRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } 48 | 49 | func (m *CreateUserRequest) GetName() string { 50 | if m != nil { 51 | return m.Name 52 | } 53 | return "" 54 | } 55 | 56 | type CreateUserResponse struct { 57 | User *User `protobuf:"bytes,1,opt,name=user" json:"user,omitempty"` 58 | ErrMsg string `protobuf:"bytes,2,opt,name=err_msg,json=errMsg" json:"err_msg,omitempty"` 59 | } 60 | 61 | func (m *CreateUserResponse) Reset() { *m = CreateUserResponse{} } 62 | func (m *CreateUserResponse) String() string { return proto.CompactTextString(m) } 63 | func (*CreateUserResponse) ProtoMessage() {} 64 | func (*CreateUserResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } 65 | 66 | func (m *CreateUserResponse) GetUser() *User { 67 | if m != nil { 68 | return m.User 69 | } 70 | return nil 71 | } 72 | 73 | func (m *CreateUserResponse) GetErrMsg() string { 74 | if m != nil { 75 | return m.ErrMsg 76 | } 77 | return "" 78 | } 79 | 80 | type GetUserRequest struct { 81 | Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` 82 | } 83 | 84 | func (m *GetUserRequest) Reset() { *m = GetUserRequest{} } 85 | func (m *GetUserRequest) String() string { return proto.CompactTextString(m) } 86 | func (*GetUserRequest) ProtoMessage() {} 87 | func (*GetUserRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } 88 | 89 | func (m *GetUserRequest) GetId() string { 90 | if m != nil { 91 | return m.Id 92 | } 93 | return "" 94 | } 95 | 96 | type GetUserResponse struct { 97 | User *User `protobuf:"bytes,1,opt,name=user" json:"user,omitempty"` 98 | ErrMsg string `protobuf:"bytes,2,opt,name=err_msg,json=errMsg" json:"err_msg,omitempty"` 99 | } 100 | 101 | func (m *GetUserResponse) Reset() { *m = GetUserResponse{} } 102 | func (m *GetUserResponse) String() string { return proto.CompactTextString(m) } 103 | func (*GetUserResponse) ProtoMessage() {} 104 | func (*GetUserResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } 105 | 106 | func (m *GetUserResponse) GetUser() *User { 107 | if m != nil { 108 | return m.User 109 | } 110 | return nil 111 | } 112 | 113 | func (m *GetUserResponse) GetErrMsg() string { 114 | if m != nil { 115 | return m.ErrMsg 116 | } 117 | return "" 118 | } 119 | 120 | type User struct { 121 | Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` 122 | Name string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` 123 | } 124 | 125 | func (m *User) Reset() { *m = User{} } 126 | func (m *User) String() string { return proto.CompactTextString(m) } 127 | func (*User) ProtoMessage() {} 128 | func (*User) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } 129 | 130 | func (m *User) GetId() string { 131 | if m != nil { 132 | return m.Id 133 | } 134 | return "" 135 | } 136 | 137 | func (m *User) GetName() string { 138 | if m != nil { 139 | return m.Name 140 | } 141 | return "" 142 | } 143 | 144 | func init() { 145 | proto.RegisterType((*CreateUserRequest)(nil), "user.CreateUserRequest") 146 | proto.RegisterType((*CreateUserResponse)(nil), "user.CreateUserResponse") 147 | proto.RegisterType((*GetUserRequest)(nil), "user.GetUserRequest") 148 | proto.RegisterType((*GetUserResponse)(nil), "user.GetUserResponse") 149 | proto.RegisterType((*User)(nil), "user.User") 150 | } 151 | 152 | // Reference imports to suppress errors if they are not otherwise used. 153 | var _ context.Context 154 | var _ grpc.ClientConn 155 | 156 | // This is a compile-time assertion to ensure that this generated file 157 | // is compatible with the grpc package it is being compiled against. 158 | const _ = grpc.SupportPackageIsVersion4 159 | 160 | // Client API for UserService service 161 | 162 | type UserServiceClient interface { 163 | CreateUser(ctx context.Context, in *CreateUserRequest, opts ...grpc.CallOption) (*CreateUserResponse, error) 164 | GetUser(ctx context.Context, in *GetUserRequest, opts ...grpc.CallOption) (*GetUserResponse, error) 165 | } 166 | 167 | type userServiceClient struct { 168 | cc *grpc.ClientConn 169 | } 170 | 171 | func NewUserServiceClient(cc *grpc.ClientConn) UserServiceClient { 172 | return &userServiceClient{cc} 173 | } 174 | 175 | func (c *userServiceClient) CreateUser(ctx context.Context, in *CreateUserRequest, opts ...grpc.CallOption) (*CreateUserResponse, error) { 176 | out := new(CreateUserResponse) 177 | err := grpc.Invoke(ctx, "/user.UserService/CreateUser", in, out, c.cc, opts...) 178 | if err != nil { 179 | return nil, err 180 | } 181 | return out, nil 182 | } 183 | 184 | func (c *userServiceClient) GetUser(ctx context.Context, in *GetUserRequest, opts ...grpc.CallOption) (*GetUserResponse, error) { 185 | out := new(GetUserResponse) 186 | err := grpc.Invoke(ctx, "/user.UserService/GetUser", in, out, c.cc, opts...) 187 | if err != nil { 188 | return nil, err 189 | } 190 | return out, nil 191 | } 192 | 193 | // Server API for UserService service 194 | 195 | type UserServiceServer interface { 196 | CreateUser(context.Context, *CreateUserRequest) (*CreateUserResponse, error) 197 | GetUser(context.Context, *GetUserRequest) (*GetUserResponse, error) 198 | } 199 | 200 | func RegisterUserServiceServer(s *grpc.Server, srv UserServiceServer) { 201 | s.RegisterService(&_UserService_serviceDesc, srv) 202 | } 203 | 204 | func _UserService_CreateUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 205 | in := new(CreateUserRequest) 206 | if err := dec(in); err != nil { 207 | return nil, err 208 | } 209 | if interceptor == nil { 210 | return srv.(UserServiceServer).CreateUser(ctx, in) 211 | } 212 | info := &grpc.UnaryServerInfo{ 213 | Server: srv, 214 | FullMethod: "/user.UserService/CreateUser", 215 | } 216 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 217 | return srv.(UserServiceServer).CreateUser(ctx, req.(*CreateUserRequest)) 218 | } 219 | return interceptor(ctx, in, info, handler) 220 | } 221 | 222 | func _UserService_GetUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 223 | in := new(GetUserRequest) 224 | if err := dec(in); err != nil { 225 | return nil, err 226 | } 227 | if interceptor == nil { 228 | return srv.(UserServiceServer).GetUser(ctx, in) 229 | } 230 | info := &grpc.UnaryServerInfo{ 231 | Server: srv, 232 | FullMethod: "/user.UserService/GetUser", 233 | } 234 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 235 | return srv.(UserServiceServer).GetUser(ctx, req.(*GetUserRequest)) 236 | } 237 | return interceptor(ctx, in, info, handler) 238 | } 239 | 240 | var _UserService_serviceDesc = grpc.ServiceDesc{ 241 | ServiceName: "user.UserService", 242 | HandlerType: (*UserServiceServer)(nil), 243 | Methods: []grpc.MethodDesc{ 244 | { 245 | MethodName: "CreateUser", 246 | Handler: _UserService_CreateUser_Handler, 247 | }, 248 | { 249 | MethodName: "GetUser", 250 | Handler: _UserService_GetUser_Handler, 251 | }, 252 | }, 253 | Streams: []grpc.StreamDesc{}, 254 | Metadata: "services/user/user.proto", 255 | } 256 | 257 | func init() { proto.RegisterFile("services/user/user.proto", fileDescriptor0) } 258 | 259 | var fileDescriptor0 = []byte{ 260 | // 236 bytes of a gzipped FileDescriptorProto 261 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0x92, 0x28, 0x4e, 0x2d, 0x2a, 262 | 0xcb, 0x4c, 0x4e, 0x2d, 0xd6, 0x2f, 0x2d, 0x4e, 0x2d, 0x02, 0x13, 0x7a, 0x05, 0x45, 0xf9, 0x25, 263 | 0xf9, 0x42, 0x2c, 0x20, 0xb6, 0x92, 0x3a, 0x97, 0xa0, 0x73, 0x51, 0x6a, 0x62, 0x49, 0x6a, 0x68, 264 | 0x71, 0x6a, 0x51, 0x50, 0x6a, 0x61, 0x69, 0x6a, 0x71, 0x89, 0x90, 0x10, 0x17, 0x4b, 0x5e, 0x62, 265 | 0x6e, 0xaa, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x67, 0x10, 0x98, 0xad, 0xe4, 0xcb, 0x25, 0x84, 0xac, 266 | 0xb0, 0xb8, 0x20, 0x3f, 0xaf, 0x38, 0x55, 0x48, 0x8e, 0x0b, 0x6c, 0x0c, 0x58, 0x25, 0xb7, 0x11, 267 | 0x97, 0x1e, 0xd8, 0x7c, 0xb0, 0x0a, 0xb0, 0xb8, 0x90, 0x38, 0x17, 0x7b, 0x6a, 0x51, 0x51, 0x7c, 268 | 0x6e, 0x71, 0xba, 0x04, 0x13, 0xd8, 0x30, 0xb6, 0xd4, 0xa2, 0x22, 0xdf, 0xe2, 0x74, 0x25, 0x05, 269 | 0x2e, 0x3e, 0xf7, 0xd4, 0x12, 0x64, 0x4b, 0xf9, 0xb8, 0x98, 0x32, 0x53, 0xa0, 0x56, 0x32, 0x65, 270 | 0xa6, 0x28, 0x79, 0x71, 0xf1, 0xc3, 0x55, 0x50, 0x6a, 0x9b, 0x16, 0x17, 0x0b, 0x48, 0x19, 0xba, 271 | 0x1d, 0x70, 0x8f, 0x32, 0x21, 0x3c, 0x6a, 0xd4, 0xc5, 0xc8, 0xc5, 0x0d, 0x52, 0x1c, 0x0c, 0x09, 272 | 0x38, 0x21, 0x47, 0x2e, 0x2e, 0x84, 0xc7, 0x85, 0xc4, 0x21, 0x96, 0x62, 0x84, 0x99, 0x94, 0x04, 273 | 0xa6, 0x04, 0xc4, 0xd5, 0x4a, 0x0c, 0x42, 0x16, 0x5c, 0xec, 0x50, 0xaf, 0x08, 0x89, 0x40, 0x94, 274 | 0xa1, 0xfa, 0x5d, 0x4a, 0x14, 0x4d, 0x14, 0xa6, 0x33, 0x89, 0x0d, 0x1c, 0x57, 0xc6, 0x80, 0x00, 275 | 0x00, 0x00, 0xff, 0xff, 0xce, 0xde, 0xa3, 0x2e, 0xc7, 0x01, 0x00, 0x00, 276 | } 277 | -------------------------------------------------------------------------------- /examples/flow/output/test/test_grpc_js.js: -------------------------------------------------------------------------------- 1 | // @flow 2 | // GENERATED CODE -- DO NOT EDIT! 3 | 4 | import base64 from 'base64-js' 5 | import test_pb from './test_pb' 6 | 7 | 8 | export type TestEnum = {| 9 | ELEMENT_A?: 0; 10 | ELEMENT_B?: 1; 11 | |}; 12 | 13 | 14 | export type TestMessage$TestNestedEnum = {| 15 | ELEMENT_C?: 0; 16 | ELEMENT_D?: 1; 17 | |}; 18 | 19 | 20 | export type TestMessage$TestNestedMessage = { 21 | getS?: () => string; 22 | setS?: (s: string) => void; 23 | getT?: () => number; 24 | setT?: (t: number) => void; 25 | }; 26 | 27 | export type TestMessage = { 28 | getA?: () => string; 29 | setA?: (a: string) => void; 30 | getB?: () => number; 31 | setB?: (b: number) => void; 32 | getC?: () => number; 33 | setC?: (c: number) => void; 34 | getD?: () => number; 35 | setD?: (d: number) => void; 36 | getE?: () => number; 37 | setE?: (e: number) => void; 38 | getNList?: () => Array; 39 | setNList?: (n: Array) => void; 40 | addN?: (n: string) => void; 41 | clearNList?: () => void; 42 | getOList?: () => Array; 43 | setOList?: (o: Array) => void; 44 | addO?: (o: number) => void; 45 | clearOList?: () => void; 46 | getPList?: () => Array; 47 | setPList?: (p: Array) => void; 48 | addP?: (p: number) => void; 49 | clearPList?: () => void; 50 | getQList?: () => Array; 51 | setQList?: (q: Array) => void; 52 | addQ?: (q: number) => void; 53 | clearQList?: () => void; 54 | getRList?: () => Array; 55 | setRList?: (r: Array) => void; 56 | addR?: (r: number) => void; 57 | clearRList?: () => void; 58 | getU?: () => test$TestEnum; 59 | setU?: (u: test$TestEnum) => void; 60 | getV?: () => test$TestMessage$TestNestedEnum; 61 | setV?: (v: test$TestMessage$TestNestedEnum) => void; 62 | getWList?: () => Array; 63 | setWList?: (w: Array) => void; 64 | addW?: (w: test$TestMessage$TestNestedMessage) => void; 65 | clearWList?: () => void; 66 | }; 67 | 68 | 69 | 70 | 71 | 72 | export type TestNoStreamRequest = { 73 | getMessage?: () => test$TestMessage; 74 | setMessage?: (message: test$TestMessage) => void; 75 | clearMessage?: () => void; 76 | hasMessage?: () => boolean; 77 | }; 78 | 79 | 80 | 81 | 82 | 83 | export type TestNoStreamReply = { 84 | getMessage?: () => test$TestMessage; 85 | setMessage?: (message: test$TestMessage) => void; 86 | clearMessage?: () => void; 87 | hasMessage?: () => boolean; 88 | getErrMsg?: () => string; 89 | setErrMsg?: (err_msg: string) => void; 90 | }; 91 | 92 | 93 | 94 | 95 | 96 | export type TestStreamRequestRequest = { 97 | getMessage?: () => test$TestMessage; 98 | setMessage?: (message: test$TestMessage) => void; 99 | clearMessage?: () => void; 100 | hasMessage?: () => boolean; 101 | }; 102 | 103 | 104 | 105 | 106 | 107 | export type TestStreamRequestReply = { 108 | getMessage?: () => test$TestMessage; 109 | setMessage?: (message: test$TestMessage) => void; 110 | clearMessage?: () => void; 111 | hasMessage?: () => boolean; 112 | getErrMsg?: () => string; 113 | setErrMsg?: (err_msg: string) => void; 114 | }; 115 | 116 | 117 | 118 | 119 | 120 | export type TestStreamReplyRequest = { 121 | getMessage?: () => test$TestMessage; 122 | setMessage?: (message: test$TestMessage) => void; 123 | clearMessage?: () => void; 124 | hasMessage?: () => boolean; 125 | }; 126 | 127 | 128 | 129 | 130 | 131 | export type TestStreamReplyReply = { 132 | getMessage?: () => test$TestMessage; 133 | setMessage?: (message: test$TestMessage) => void; 134 | clearMessage?: () => void; 135 | hasMessage?: () => boolean; 136 | getErrMsg?: () => string; 137 | setErrMsg?: (err_msg: string) => void; 138 | }; 139 | 140 | 141 | 142 | 143 | 144 | export type TestStreamBothRequest = { 145 | getMessage?: () => test$TestMessage; 146 | setMessage?: (message: test$TestMessage) => void; 147 | clearMessage?: () => void; 148 | hasMessage?: () => boolean; 149 | }; 150 | 151 | 152 | 153 | 154 | 155 | export type TestStreamBothReply = { 156 | getMessage?: () => test$TestMessage; 157 | setMessage?: (message: test$TestMessage) => void; 158 | clearMessage?: () => void; 159 | hasMessage?: () => boolean; 160 | getErrMsg?: () => string; 161 | setErrMsg?: (err_msg: string) => void; 162 | }; 163 | 164 | const serializeToBase64 = (byteArray: Uint8Array): string => base64.fromByteArray(byteArray) 165 | const deserializeFromBase64 = (base64Encoded: string): Uint8Array => new Uint8Array(base64.toByteArray(base64Encoded)) 166 | 167 | 168 | function serialize_test_TestNoStreamRequest(arg : TestNoStreamRequest): string { 169 | if (!(arg instanceof test_pb.TestNoStreamRequest)) { 170 | throw new Error('Expected argument of type TestNoStreamRequest') 171 | } 172 | return serializeToBase64(arg.serializeBinary()) 173 | } 174 | 175 | function deserialize_test_TestNoStreamRequest(base64Encoded: string): TestNoStreamRequest { 176 | return test_pb.TestNoStreamRequest.deserializeBinary(deserializeFromBase64(base64Encoded)) 177 | } 178 | 179 | function serialize_test_TestNoStreamReply(arg : TestNoStreamReply): string { 180 | if (!(arg instanceof test_pb.TestNoStreamReply)) { 181 | throw new Error('Expected argument of type TestNoStreamReply') 182 | } 183 | return serializeToBase64(arg.serializeBinary()) 184 | } 185 | 186 | function deserialize_test_TestNoStreamReply(base64Encoded: string): TestNoStreamReply { 187 | return test_pb.TestNoStreamReply.deserializeBinary(deserializeFromBase64(base64Encoded)) 188 | } 189 | 190 | 191 | function serialize_test_TestStreamRequestRequest(arg : TestStreamRequestRequest): string { 192 | if (!(arg instanceof test_pb.TestStreamRequestRequest)) { 193 | throw new Error('Expected argument of type TestStreamRequestRequest') 194 | } 195 | return serializeToBase64(arg.serializeBinary()) 196 | } 197 | 198 | function deserialize_test_TestStreamRequestRequest(base64Encoded: string): TestStreamRequestRequest { 199 | return test_pb.TestStreamRequestRequest.deserializeBinary(deserializeFromBase64(base64Encoded)) 200 | } 201 | 202 | function serialize_test_TestStreamRequestReply(arg : TestStreamRequestReply): string { 203 | if (!(arg instanceof test_pb.TestStreamRequestReply)) { 204 | throw new Error('Expected argument of type TestStreamRequestReply') 205 | } 206 | return serializeToBase64(arg.serializeBinary()) 207 | } 208 | 209 | function deserialize_test_TestStreamRequestReply(base64Encoded: string): TestStreamRequestReply { 210 | return test_pb.TestStreamRequestReply.deserializeBinary(deserializeFromBase64(base64Encoded)) 211 | } 212 | 213 | 214 | function serialize_test_TestStreamReplyRequest(arg : TestStreamReplyRequest): string { 215 | if (!(arg instanceof test_pb.TestStreamReplyRequest)) { 216 | throw new Error('Expected argument of type TestStreamReplyRequest') 217 | } 218 | return serializeToBase64(arg.serializeBinary()) 219 | } 220 | 221 | function deserialize_test_TestStreamReplyRequest(base64Encoded: string): TestStreamReplyRequest { 222 | return test_pb.TestStreamReplyRequest.deserializeBinary(deserializeFromBase64(base64Encoded)) 223 | } 224 | 225 | function serialize_test_TestStreamReplyReply(arg : TestStreamReplyReply): string { 226 | if (!(arg instanceof test_pb.TestStreamReplyReply)) { 227 | throw new Error('Expected argument of type TestStreamReplyReply') 228 | } 229 | return serializeToBase64(arg.serializeBinary()) 230 | } 231 | 232 | function deserialize_test_TestStreamReplyReply(base64Encoded: string): TestStreamReplyReply { 233 | return test_pb.TestStreamReplyReply.deserializeBinary(deserializeFromBase64(base64Encoded)) 234 | } 235 | 236 | 237 | function serialize_test_TestStreamBothRequest(arg : TestStreamBothRequest): string { 238 | if (!(arg instanceof test_pb.TestStreamBothRequest)) { 239 | throw new Error('Expected argument of type TestStreamBothRequest') 240 | } 241 | return serializeToBase64(arg.serializeBinary()) 242 | } 243 | 244 | function deserialize_test_TestStreamBothRequest(base64Encoded: string): TestStreamBothRequest { 245 | return test_pb.TestStreamBothRequest.deserializeBinary(deserializeFromBase64(base64Encoded)) 246 | } 247 | 248 | function serialize_test_TestStreamBothReply(arg : TestStreamBothReply): string { 249 | if (!(arg instanceof test_pb.TestStreamBothReply)) { 250 | throw new Error('Expected argument of type TestStreamBothReply') 251 | } 252 | return serializeToBase64(arg.serializeBinary()) 253 | } 254 | 255 | function deserialize_test_TestStreamBothReply(base64Encoded: string): TestStreamBothReply { 256 | return test_pb.TestStreamBothReply.deserializeBinary(deserializeFromBase64(base64Encoded)) 257 | } 258 | 259 | 260 | export default { 261 | 262 | TestService: { 263 | 264 | testNoStream: { 265 | path: '/test.TestService/TestNoStream', 266 | requestStream: false, 267 | responseStream: false, 268 | requestType: test_pb.TestNoStreamRequest, 269 | responseType: test_pb.TestNoStreamReply, 270 | requestSerialize: serialize_test_TestNoStreamRequest, 271 | requestDeserialize: deserialize_test_TestNoStreamRequest, 272 | responseSerialize: serialize_test_TestNoStreamReply, 273 | responseDeserialize: deserialize_test_TestNoStreamReply, 274 | }, 275 | testStreamRequest: { 276 | path: '/test.TestService/TestStreamRequest', 277 | requestStream: true, 278 | responseStream: false, 279 | requestType: test_pb.TestStreamRequestRequest, 280 | responseType: test_pb.TestStreamRequestReply, 281 | requestSerialize: serialize_test_TestStreamRequestRequest, 282 | requestDeserialize: deserialize_test_TestStreamRequestRequest, 283 | responseSerialize: serialize_test_TestStreamRequestReply, 284 | responseDeserialize: deserialize_test_TestStreamRequestReply, 285 | }, 286 | testStreamReply: { 287 | path: '/test.TestService/TestStreamReply', 288 | requestStream: false, 289 | responseStream: true, 290 | requestType: test_pb.TestStreamReplyRequest, 291 | responseType: test_pb.TestStreamReplyReply, 292 | requestSerialize: serialize_test_TestStreamReplyRequest, 293 | requestDeserialize: deserialize_test_TestStreamReplyRequest, 294 | responseSerialize: serialize_test_TestStreamReplyReply, 295 | responseDeserialize: deserialize_test_TestStreamReplyReply, 296 | }, 297 | testStreamBoth: { 298 | path: '/test.TestService/TestStreamBoth', 299 | requestStream: true, 300 | responseStream: true, 301 | requestType: test_pb.TestStreamBothRequest, 302 | responseType: test_pb.TestStreamBothReply, 303 | requestSerialize: serialize_test_TestStreamBothRequest, 304 | requestDeserialize: deserialize_test_TestStreamBothRequest, 305 | responseSerialize: serialize_test_TestStreamBothReply, 306 | responseDeserialize: deserialize_test_TestStreamBothReply, 307 | }, 308 | 309 | } 310 | 311 | } 312 | -------------------------------------------------------------------------------- /cmd/web-editor/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | protoc-gen-gotemplate web editor 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | `protoc-gen-gotemplate`: input 102 | 103 | 104 | ./example.proto 105 | 107 | 108 | 109 | 110 | ./example.txt.tmpl 111 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | Output 123 | ./example.txt 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | Command: protoc --gotemplate_out=template_dir=.:. example.proto 132 | Powered by protoc-gen-gotemplate 133 | 134 | 135 | 136 | 137 | 138 | 139 | --------------------------------------------------------------------------------
protoc --gotemplate_out=template_dir=.:. example.proto