gorm_execute.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package generator_handler
  2. import (
  3. "bytes"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "runtime"
  8. "strings"
  9. "github.com/xinliangnote/go-gin-api/configs"
  10. "github.com/xinliangnote/go-gin-api/internal/pkg/core"
  11. )
  12. type gormExecuteRequest struct {
  13. Tables string `form:"tables"`
  14. }
  15. func (h *handler) GormExecute() core.HandlerFunc {
  16. dir, _ := os.Getwd()
  17. projectPath := strings.Replace(dir, "\\", "/", -1)
  18. gormgenSh := projectPath + "/scripts/gormgen.sh"
  19. gormgenBat := projectPath + "/scripts/gormgen.bat"
  20. return func(c core.Context) {
  21. req := new(gormExecuteRequest)
  22. if err := c.ShouldBindPostForm(req); err != nil {
  23. c.Payload("参数传递有误")
  24. return
  25. }
  26. mysqlConf := configs.Get().MySQL.Read
  27. shellPath := fmt.Sprintf("%s %s %s %s %s %s", gormgenSh, mysqlConf.Addr, mysqlConf.User, mysqlConf.Pass, mysqlConf.Name, req.Tables)
  28. batPath := fmt.Sprintf("%s %s %s %s %s %s", gormgenBat, mysqlConf.Addr, mysqlConf.User, mysqlConf.Pass, mysqlConf.Name, req.Tables)
  29. command := new(exec.Cmd)
  30. if runtime.GOOS == "windows" {
  31. command = exec.Command("cmd", "/C", batPath)
  32. } else {
  33. // runtime.GOOS = linux or darwin
  34. command = exec.Command("/bin/bash", "-c", shellPath)
  35. }
  36. var stderr bytes.Buffer
  37. command.Stderr = &stderr
  38. output, err := command.Output()
  39. if err != nil {
  40. c.Payload(stderr.String())
  41. return
  42. }
  43. c.Payload(string(output))
  44. }
  45. }