servicestate.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package parser
  2. import (
  3. "fmt"
  4. "strings"
  5. "zero/tools/goctl/api/spec"
  6. )
  7. type serviceState struct {
  8. *baseState
  9. annos []spec.Annotation
  10. }
  11. func newServiceState(state *baseState, annos []spec.Annotation) state {
  12. return &serviceState{
  13. baseState: state,
  14. annos: annos,
  15. }
  16. }
  17. func (s *serviceState) process(api *spec.ApiSpec) (state, error) {
  18. var name string
  19. var routes []spec.Route
  20. parser := &serviceEntityParser{
  21. acceptName: func(n string) {
  22. name = n
  23. },
  24. acceptRoute: func(route spec.Route) {
  25. routes = append(routes, route)
  26. },
  27. }
  28. ent := newEntity(s.baseState, api, parser)
  29. if err := ent.process(); err != nil {
  30. return nil, err
  31. }
  32. api.Service = spec.Service{
  33. Name: name,
  34. Annotations: append(api.Service.Annotations, s.annos...),
  35. Routes: append(api.Service.Routes, routes...),
  36. Groups: append(api.Service.Groups, spec.Group{
  37. Annotations: s.annos,
  38. Routes: routes,
  39. }),
  40. }
  41. return newRootState(s.r, s.lineNumber), nil
  42. }
  43. type serviceEntityParser struct {
  44. acceptName func(name string)
  45. acceptRoute func(route spec.Route)
  46. }
  47. func (p *serviceEntityParser) parseLine(line string, api *spec.ApiSpec, annos []spec.Annotation) error {
  48. fields := strings.Fields(line)
  49. if len(fields) < 2 {
  50. return fmt.Errorf("wrong line %q", line)
  51. }
  52. method := fields[0]
  53. pathAndRequest := fields[1]
  54. pos := strings.Index(pathAndRequest, "(")
  55. if pos < 0 {
  56. return fmt.Errorf("wrong line %q", line)
  57. }
  58. path := strings.TrimSpace(pathAndRequest[:pos])
  59. pathAndRequest = pathAndRequest[pos+1:]
  60. pos = strings.Index(pathAndRequest, ")")
  61. if pos < 0 {
  62. return fmt.Errorf("wrong line %q", line)
  63. }
  64. req := pathAndRequest[:pos]
  65. var returns string
  66. if len(fields) > 2 {
  67. returns = fields[2]
  68. }
  69. returns = strings.ReplaceAll(returns, "returns", "")
  70. returns = strings.ReplaceAll(returns, "(", "")
  71. returns = strings.ReplaceAll(returns, ")", "")
  72. returns = strings.TrimSpace(returns)
  73. p.acceptRoute(spec.Route{
  74. Annotations: annos,
  75. Method: method,
  76. Path: path,
  77. RequestType: GetType(api, req),
  78. ResponseType: GetType(api, returns),
  79. })
  80. return nil
  81. }
  82. func (p *serviceEntityParser) setEntityName(name string) {
  83. p.acceptName(name)
  84. }