helper.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "go-common/app/tool/bmproto/protoc-gen-bm/extensions/gogoproto"
  7. "github.com/golang/protobuf/proto"
  8. "github.com/golang/protobuf/protoc-gen-go/descriptor"
  9. "google.golang.org/genproto/googleapis/api/annotations"
  10. )
  11. func getMoreTags(field *descriptor.FieldDescriptorProto) *string {
  12. if field == nil {
  13. return nil
  14. }
  15. if field.Options != nil {
  16. v, err := proto.GetExtension(field.Options, gogoproto.E_Moretags)
  17. if err == nil && v.(*string) != nil {
  18. return v.(*string)
  19. }
  20. }
  21. return nil
  22. }
  23. func getJsonTag(field *descriptor.FieldDescriptorProto) string {
  24. if field == nil {
  25. return ""
  26. }
  27. if field.Options != nil {
  28. v, err := proto.GetExtension(field.Options, gogoproto.E_Jsontag)
  29. if err == nil && v.(*string) != nil {
  30. ret := *(v.(*string))
  31. i := strings.Index(ret, ",")
  32. if i != -1 {
  33. ret = ret[:i]
  34. }
  35. return ret
  36. }
  37. }
  38. return field.GetName()
  39. }
  40. type googleMethodOptionInfo struct {
  41. Method string
  42. PathPattern string
  43. HTTPRule *annotations.HttpRule
  44. }
  45. // ParseBMMethod parse BMMethodDescriptor form method descriptor proto
  46. func ParseBMMethod(method *descriptor.MethodDescriptorProto) (*googleMethodOptionInfo, error) {
  47. ext, err := proto.GetExtension(method.GetOptions(), annotations.E_Http)
  48. if err != nil {
  49. return nil, fmt.Errorf("get extension error: %s", err)
  50. }
  51. rule := ext.(*annotations.HttpRule)
  52. var httpMethod string
  53. var pathPattern string
  54. switch pattern := rule.Pattern.(type) {
  55. case *annotations.HttpRule_Get:
  56. pathPattern = pattern.Get
  57. httpMethod = http.MethodGet
  58. case *annotations.HttpRule_Put:
  59. pathPattern = pattern.Put
  60. httpMethod = http.MethodPut
  61. case *annotations.HttpRule_Post:
  62. pathPattern = pattern.Post
  63. httpMethod = http.MethodPost
  64. case *annotations.HttpRule_Patch:
  65. pathPattern = pattern.Patch
  66. httpMethod = http.MethodPatch
  67. case *annotations.HttpRule_Delete:
  68. pathPattern = pattern.Delete
  69. httpMethod = http.MethodDelete
  70. default:
  71. return nil, fmt.Errorf("unsupport http pattern %s", rule.Pattern)
  72. }
  73. bmMethod := &googleMethodOptionInfo{
  74. Method: httpMethod,
  75. PathPattern: pathPattern,
  76. HTTPRule: rule,
  77. }
  78. return bmMethod, nil
  79. }