generator.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package codegenerator
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "github.com/golang/protobuf/proto"
  7. plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
  8. )
  9. // ParseRequest parses a code generator request from a proto Message.
  10. func ParseRequest(r io.Reader) (*plugin.CodeGeneratorRequest, error) {
  11. input, err := ioutil.ReadAll(r)
  12. if err != nil {
  13. return nil, fmt.Errorf("failed to read code generator request: %v", err)
  14. }
  15. req := new(plugin.CodeGeneratorRequest)
  16. if err = proto.Unmarshal(input, req); err != nil {
  17. return nil, fmt.Errorf("failed to unmarshal code generator request: %v", err)
  18. }
  19. return req, nil
  20. }
  21. // WriteResponse write a code generator response
  22. func WriteResponse(w io.Writer, files []*plugin.CodeGeneratorResponse_File, inErr error) error {
  23. var perrMsg *string
  24. if inErr != nil {
  25. errMsg := inErr.Error()
  26. perrMsg = &errMsg
  27. }
  28. resp := &plugin.CodeGeneratorResponse{Error: perrMsg, File: files}
  29. buf, err := proto.Marshal(resp)
  30. if err != nil {
  31. return err
  32. }
  33. _, err = w.Write(buf)
  34. return err
  35. }