mysql.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package controller
  2. import (
  3. "fmt"
  4. "git.wanbits.cc/sin/flytalk/config"
  5. "git.wanbits.cc/sin/flytalk/database"
  6. "git.wanbits.cc/sin/flytalk/tools"
  7. "github.com/gin-gonic/gin"
  8. "os"
  9. )
  10. func MysqlGetConf(c *gin.Context) {
  11. mysqlInfo := config.GetMysql()
  12. c.JSON(200, gin.H{
  13. "code": 200,
  14. "msg": "验证成功",
  15. "result": mysqlInfo,
  16. })
  17. }
  18. func MysqlSetConf(c *gin.Context) {
  19. mysqlServer := c.PostForm("server")
  20. mysqlPort := c.PostForm("port")
  21. mysqlDb := c.PostForm("database")
  22. mysqlUsername := c.PostForm("username")
  23. mysqlPassword := c.PostForm("password")
  24. dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", mysqlUsername, mysqlPassword, mysqlServer, mysqlPort, mysqlDb)
  25. mysql := database.NewMysql()
  26. mysql.Dsn = dsn
  27. err := mysql.Ping()
  28. if err != nil {
  29. c.JSON(200, gin.H{
  30. "code": 403,
  31. "msg": "数据库连接失败:" + err.Error(),
  32. })
  33. return
  34. }
  35. isExist, _ := tools.IsFileExist(config.Dir)
  36. if !isExist {
  37. os.Mkdir(config.Dir, os.ModePerm)
  38. }
  39. fileConfig := config.MysqlConf
  40. file, _ := os.OpenFile(fileConfig, os.O_RDWR|os.O_CREATE, os.ModePerm)
  41. format := `{
  42. "Server":"%s",
  43. "Port":"%s",
  44. "Database":"%s",
  45. "Username":"%s",
  46. "Password":"%s"
  47. }
  48. `
  49. data := fmt.Sprintf(format, mysqlServer, mysqlPort, mysqlDb, mysqlUsername, mysqlPassword)
  50. file.WriteString(data)
  51. c.JSON(200, gin.H{
  52. "code": 200,
  53. "msg": "操作成功",
  54. })
  55. }