config.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package api
  2. import (
  3. "github.com/0xJacky/Nginx-UI/model"
  4. "github.com/0xJacky/Nginx-UI/tool"
  5. "github.com/gin-gonic/gin"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. "path/filepath"
  10. "strconv"
  11. )
  12. func GetConfigs(c *gin.Context) {
  13. configFiles, err := ioutil.ReadDir(filepath.Join("/usr/local/etc/nginx"))
  14. if err != nil {
  15. log.Println(err)
  16. }
  17. var configs []gin.H
  18. for i := range configFiles {
  19. file := configFiles[i]
  20. if !file.IsDir() && "." != file.Name()[0:1] {
  21. configs = append(configs, gin.H{
  22. "name": file.Name(),
  23. "size": file.Size(),
  24. "modify": file.ModTime(),
  25. })
  26. }
  27. }
  28. c.JSON(http.StatusOK, gin.H{
  29. "configs": configs,
  30. })
  31. }
  32. func GetConfig(c *gin.Context) {
  33. name := c.Param("name")
  34. path := filepath.Join("/usr/local/etc/nginx", name)
  35. content, err := ioutil.ReadFile(path)
  36. if err != nil {
  37. log.Println(err)
  38. }
  39. c.JSON(http.StatusOK, gin.H{
  40. "config": string(content),
  41. })
  42. }
  43. func AddConfig(c *gin.Context) {
  44. name := c.PostForm("name")
  45. content := c.PostForm("content")
  46. path := filepath.Join(tool.GetNginxConfPath("/"), name)
  47. s, err := strconv.Unquote(`"` + content + `"`)
  48. if err != nil {
  49. log.Println(err)
  50. }
  51. if s != "" {
  52. err := ioutil.WriteFile(path, []byte(s), 0644)
  53. if err != nil {
  54. log.Println(err)
  55. }
  56. }
  57. tool.ReloadNginx()
  58. c.JSON(http.StatusOK, gin.H{
  59. "message": "ok",
  60. })
  61. }
  62. func EditConfig(c *gin.Context) {
  63. name := c.Param("name")
  64. content := c.PostForm("content")
  65. path := filepath.Join(tool.GetNginxConfPath("/"), name)
  66. s, err := strconv.Unquote(`"` + content + `"`)
  67. if err != nil {
  68. log.Println(err)
  69. }
  70. origContent, err := ioutil.ReadFile(path)
  71. if err != nil {
  72. log.Println(err)
  73. }
  74. if s != "" && s != string(origContent) {
  75. model.CreateBackup(path)
  76. err := ioutil.WriteFile(path, []byte(s), 0644)
  77. if err != nil {
  78. log.Println(err)
  79. }
  80. }
  81. tool.ReloadNginx()
  82. GetConfig(c)
  83. }