add.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package config
  2. import (
  3. "github.com/0xJacky/Nginx-UI/api"
  4. "github.com/0xJacky/Nginx-UI/internal/config"
  5. "github.com/0xJacky/Nginx-UI/internal/helper"
  6. "github.com/0xJacky/Nginx-UI/internal/nginx"
  7. "github.com/gin-gonic/gin"
  8. "github.com/sashabaranov/go-openai"
  9. "net/http"
  10. "os"
  11. "time"
  12. )
  13. func AddConfig(c *gin.Context) {
  14. var json struct {
  15. Name string `json:"name" binding:"required"`
  16. NewFilepath string `json:"new_filepath" binding:"required"`
  17. Content string `json:"content"`
  18. Overwrite bool `json:"overwrite"`
  19. }
  20. if !api.BindAndValid(c, &json) {
  21. return
  22. }
  23. name := json.Name
  24. content := json.Content
  25. path := json.NewFilepath
  26. if !helper.IsUnderDirectory(path, nginx.GetConfPath()) {
  27. c.JSON(http.StatusForbidden, gin.H{
  28. "message": "new filepath is not under the nginx conf path",
  29. })
  30. return
  31. }
  32. if !json.Overwrite && helper.FileExists(path) {
  33. c.JSON(http.StatusNotAcceptable, gin.H{
  34. "message": "File exists",
  35. })
  36. return
  37. }
  38. err := os.WriteFile(path, []byte(content), 0644)
  39. if err != nil {
  40. api.ErrHandler(c, err)
  41. return
  42. }
  43. output := nginx.Reload()
  44. if nginx.GetLogLevel(output) >= nginx.Warn {
  45. c.JSON(http.StatusInternalServerError, gin.H{
  46. "message": output,
  47. })
  48. return
  49. }
  50. c.JSON(http.StatusOK, config.Config{
  51. Name: name,
  52. Content: content,
  53. ChatGPTMessages: make([]openai.ChatCompletionMessage, 0),
  54. FilePath: path,
  55. ModifiedAt: time.Now(),
  56. })
  57. }