write_file.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package cert
  2. import (
  3. "github.com/0xJacky/Nginx-UI/internal/helper"
  4. "github.com/0xJacky/Nginx-UI/internal/nginx"
  5. "os"
  6. "path/filepath"
  7. )
  8. type Content struct {
  9. SSLCertificatePath string `json:"ssl_certificate_path" binding:"required"`
  10. SSLCertificateKeyPath string `json:"ssl_certificate_key_path" binding:"required"`
  11. SSLCertificate string `json:"ssl_certificate"`
  12. SSLCertificateKey string `json:"ssl_certificate_key"`
  13. }
  14. func (c *Content) WriteFile() (err error) {
  15. if c.SSLCertificatePath == "" || c.SSLCertificateKeyPath == "" {
  16. return
  17. }
  18. nginxConfPath := nginx.GetConfPath()
  19. if !helper.IsUnderDirectory(c.SSLCertificatePath, nginxConfPath) {
  20. return e.NewWithParams(50006, ErrPathIsNotUnderTheNginxConfDir.Error(), c.SSLCertificatePath, nginxConfPath)
  21. }
  22. if !helper.IsUnderDirectory(c.SSLCertificateKeyPath, nginxConfPath) {
  23. return e.NewWithParams(50006, ErrPathIsNotUnderTheNginxConfDir.Error(), c.SSLCertificateKeyPath, nginxConfPath)
  24. }
  25. // MkdirAll creates a directory named path, along with any necessary parents,
  26. // and returns nil, or else returns an error.
  27. // The permission bits perm (before umask) are used for all directories that MkdirAll creates.
  28. // If path is already a directory, MkdirAll does nothing and returns nil.
  29. err = os.MkdirAll(filepath.Dir(c.SSLCertificatePath), 0644)
  30. if err != nil {
  31. return
  32. }
  33. err = os.MkdirAll(filepath.Dir(c.SSLCertificateKeyPath), 0644)
  34. if err != nil {
  35. return
  36. }
  37. if c.SSLCertificate != "" {
  38. err = os.WriteFile(c.SSLCertificatePath, []byte(c.SSLCertificate), 0644)
  39. if err != nil {
  40. return
  41. }
  42. }
  43. if c.SSLCertificateKey != "" {
  44. err = os.WriteFile(c.SSLCertificateKeyPath, []byte(c.SSLCertificateKey), 0644)
  45. if err != nil {
  46. return
  47. }
  48. }
  49. return
  50. }