modify.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package config
  2. import (
  3. "net/http"
  4. "path/filepath"
  5. "time"
  6. "github.com/0xJacky/Nginx-UI/internal/config"
  7. "github.com/0xJacky/Nginx-UI/internal/helper"
  8. "github.com/0xJacky/Nginx-UI/internal/nginx"
  9. "github.com/0xJacky/Nginx-UI/model"
  10. "github.com/0xJacky/Nginx-UI/query"
  11. "github.com/gin-gonic/gin"
  12. "github.com/uozi-tech/cosy"
  13. "gorm.io/gen/field"
  14. )
  15. type EditConfigJson struct {
  16. Content string `json:"content" binding:"required"`
  17. }
  18. func EditConfig(c *gin.Context) {
  19. var json struct {
  20. Content string `json:"content"`
  21. Path string `json:"path"`
  22. SyncOverwrite bool `json:"sync_overwrite"`
  23. SyncNodeIds []uint64 `json:"sync_node_ids"`
  24. }
  25. if !cosy.BindAndValid(c, &json) {
  26. return
  27. }
  28. var absPath string
  29. if filepath.IsAbs(json.Path) {
  30. absPath = json.Path
  31. } else {
  32. absPath = nginx.GetConfPath(json.Path)
  33. }
  34. if !helper.FileExists(absPath) {
  35. c.JSON(http.StatusNotFound, gin.H{
  36. "message": "file not found",
  37. })
  38. return
  39. }
  40. q := query.Config
  41. cfg, err := q.Assign(field.Attrs(&model.Config{
  42. Filepath: absPath,
  43. Name: filepath.Base(absPath),
  44. })).Where(q.Filepath.Eq(absPath)).FirstOrCreate()
  45. if err != nil {
  46. return
  47. }
  48. // Update database record
  49. _, err = q.Where(q.Filepath.Eq(absPath)).
  50. Select(q.SyncNodeIds, q.SyncOverwrite).
  51. Updates(&model.Config{
  52. SyncNodeIds: json.SyncNodeIds,
  53. SyncOverwrite: json.SyncOverwrite,
  54. })
  55. if err != nil {
  56. return
  57. }
  58. cfg.SyncNodeIds = json.SyncNodeIds
  59. cfg.SyncOverwrite = json.SyncOverwrite
  60. content := json.Content
  61. err = config.Save(absPath, content, cfg)
  62. if err != nil {
  63. cosy.ErrHandler(c, err)
  64. return
  65. }
  66. c.JSON(http.StatusOK, config.Config{
  67. Name: filepath.Base(absPath),
  68. Content: content,
  69. FilePath: absPath,
  70. ModifiedAt: time.Now(),
  71. Dir: filepath.Dir(absPath),
  72. SyncNodeIds: cfg.SyncNodeIds,
  73. SyncOverwrite: cfg.SyncOverwrite,
  74. })
  75. }