validator.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package parser
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "github.com/tal-tech/go-zero/core/stringx"
  7. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  8. "github.com/tal-tech/go-zero/tools/goctl/api/util"
  9. )
  10. func (p *Parser) validate(api *spec.ApiSpec) (err error) {
  11. var builder strings.Builder
  12. for _, tp := range api.Types {
  13. if ok, name := p.validateDuplicateProperty(tp); !ok {
  14. fmt.Fprintf(&builder, `duplicate property "%s" of type "%s"`+"\n", name, tp.Name)
  15. }
  16. }
  17. if ok, info := p.validateDuplicateRouteHandler(api); !ok {
  18. fmt.Fprintf(&builder, info)
  19. }
  20. if len(builder.String()) > 0 {
  21. return errors.New(builder.String())
  22. }
  23. return nil
  24. }
  25. func (p *Parser) validateDuplicateProperty(tp spec.Type) (bool, string) {
  26. var names []string
  27. for _, member := range tp.Members {
  28. if stringx.Contains(names, member.Name) {
  29. return false, member.Name
  30. } else {
  31. names = append(names, member.Name)
  32. }
  33. }
  34. return true, ""
  35. }
  36. func (p *Parser) validateDuplicateRouteHandler(api *spec.ApiSpec) (bool, string) {
  37. var names []string
  38. for _, r := range api.Service.Routes() {
  39. handler, ok := util.GetAnnotationValue(r.Annotations, "server", "handler")
  40. if !ok {
  41. return false, fmt.Sprintf("missing handler annotation for %s", r.Path)
  42. }
  43. if stringx.Contains(names, handler) {
  44. return false, fmt.Sprintf(`duplicated handler for name "%s"`, handler)
  45. } else {
  46. names = append(names, handler)
  47. }
  48. }
  49. return true, ""
  50. }