product.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package main
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "sparrow/pkg/models"
  9. "sparrow/pkg/productconfig"
  10. "strconv"
  11. "strings"
  12. "sparrow/pkg/server"
  13. )
  14. func addProduct() error {
  15. args := models.Product{}
  16. reader := bufio.NewReader(os.Stdin)
  17. fmt.Printf("vendor ID: ")
  18. id, err := reader.ReadString('\n')
  19. if err != nil {
  20. return err
  21. }
  22. vendor := strings.Replace(id, "\n", "", -1)
  23. vendorid, err := strconv.Atoi(vendor)
  24. if err != nil {
  25. return err
  26. }
  27. args.VendorID = int32(vendorid)
  28. fmt.Printf("product name: ")
  29. name, err := reader.ReadString('\n')
  30. if err != nil {
  31. return err
  32. }
  33. args.ProductName = strings.Replace(name, "\n", "", -1)
  34. fmt.Printf("product description: ")
  35. desc, err := reader.ReadString('\n')
  36. if err != nil {
  37. return err
  38. }
  39. args.ProductDescription = strings.Replace(desc, "\n", "", -1)
  40. fmt.Printf("product config json file: ")
  41. file, err := reader.ReadString('\n')
  42. if err != nil {
  43. return err
  44. }
  45. jsonfile := strings.Replace(file, "\n", "", -1)
  46. fi, err := os.Open(jsonfile)
  47. if err != nil {
  48. return err
  49. }
  50. content, err := ioutil.ReadAll(fi)
  51. config := string(content)
  52. fi.Close()
  53. _, err = productconfig.New(config)
  54. if err != nil {
  55. return err
  56. }
  57. args.ProductConfig = config
  58. reply := &models.Product{}
  59. err = server.RPCCallByName(nil, "registry", "Registry.SaveProduct", &args, reply)
  60. if err != nil {
  61. return err
  62. }
  63. fmt.Println("=======> product created successfully:")
  64. printStruct(reply)
  65. fmt.Println("=======")
  66. return nil
  67. }
  68. func DoProductCommand(args []string) error {
  69. if len(args) < 1 {
  70. return errors.New("command arguments not enough!")
  71. }
  72. op := strings.Replace(args[0], "\n", "", -1)
  73. switch op {
  74. case "add":
  75. if len(args) > 1 {
  76. return errors.New("unnecessary command arguments. just type 'product add'")
  77. }
  78. err := addProduct()
  79. if err != nil {
  80. return err
  81. }
  82. default:
  83. return errors.New("operation not suported:" + op)
  84. }
  85. return nil
  86. }