genmongomodelbynetwork.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package gen
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "text/template"
  8. "zero/tools/goctl/model/mongomodel/utils"
  9. )
  10. func GenMongoModelByNetwork(input string, needCache bool) (string, error) {
  11. if strings.TrimSpace(input) == "" {
  12. return "", errors.New("struct不能为空")
  13. }
  14. if strings.Index(strings.TrimSpace(input), "type") != 0 {
  15. input = "type " + input
  16. }
  17. if strings.Index(strings.TrimSpace(input), "package") != 0 {
  18. input = "package model\r\n" + input
  19. }
  20. structs, imports, err := utils.ParseGoFileByNetwork(input)
  21. if err != nil {
  22. return "", err
  23. }
  24. if len(structs) != 1 {
  25. return "", fmt.Errorf("only 1 struct should be provided")
  26. }
  27. structStr, err := genStructs(structs)
  28. if err != nil {
  29. return "", err
  30. }
  31. var myTemplate string
  32. if needCache {
  33. myTemplate = cacheTemplate
  34. } else {
  35. myTemplate = noCacheTemplate
  36. }
  37. structName := getStructName(structs)
  38. functionList := getFunctionList(structs)
  39. for _, fun := range functionList {
  40. funTmp := genMethodTemplate(fun, needCache)
  41. if funTmp == "" {
  42. continue
  43. }
  44. myTemplate += "\n"
  45. myTemplate += funTmp
  46. myTemplate += "\n"
  47. }
  48. t := template.Must(template.New("mongoTemplate").Parse(myTemplate))
  49. var result bytes.Buffer
  50. err = t.Execute(&result, map[string]string{
  51. "modelName": structName,
  52. "importArray": getImports(imports, needCache),
  53. "modelFields": structStr,
  54. })
  55. if err != nil {
  56. return "", err
  57. }
  58. return result.String(), nil
  59. }