modify.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. relativePath := helper.UnescapeURL(c.Param("path"))
  20. var json struct {
  21. Content string `json:"content"`
  22. SyncOverwrite bool `json:"sync_overwrite"`
  23. SyncNodeIds []uint64 `json:"sync_node_ids"`
  24. }
  25. if !cosy.BindAndValid(c, &json) {
  26. return
  27. }
  28. absPath := nginx.GetConfPath(relativePath)
  29. if !helper.FileExists(absPath) {
  30. c.JSON(http.StatusNotFound, gin.H{
  31. "message": "file not found",
  32. })
  33. return
  34. }
  35. q := query.Config
  36. cfg, err := q.Assign(field.Attrs(&model.Config{
  37. Filepath: absPath,
  38. })).Where(q.Filepath.Eq(absPath)).FirstOrCreate()
  39. if err != nil {
  40. return
  41. }
  42. // Update database record
  43. _, err = q.Where(q.Filepath.Eq(absPath)).
  44. Select(q.SyncNodeIds, q.SyncOverwrite).
  45. Updates(&model.Config{
  46. SyncNodeIds: json.SyncNodeIds,
  47. SyncOverwrite: json.SyncOverwrite,
  48. })
  49. if err != nil {
  50. return
  51. }
  52. cfg.SyncNodeIds = json.SyncNodeIds
  53. cfg.SyncOverwrite = json.SyncOverwrite
  54. content := json.Content
  55. err = config.Save(absPath, content, cfg)
  56. if err != nil {
  57. cosy.ErrHandler(c, err)
  58. return
  59. }
  60. c.JSON(http.StatusOK, config.Config{
  61. Name: filepath.Base(absPath),
  62. Content: content,
  63. FilePath: absPath,
  64. ModifiedAt: time.Now(),
  65. Dir: filepath.Dir(relativePath),
  66. SyncNodeIds: cfg.SyncNodeIds,
  67. SyncOverwrite: cfg.SyncOverwrite,
  68. })
  69. }