1
0

write_file.go 1.8 KB

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