build_config.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package nginx
  2. import (
  3. "bufio"
  4. "fmt"
  5. "github.com/tufanbarisyildirim/gonginx"
  6. "github.com/tufanbarisyildirim/gonginx/parser"
  7. "strings"
  8. )
  9. func buildComments(orig string, indent int) (content string) {
  10. scanner := bufio.NewScanner(strings.NewReader(orig))
  11. for scanner.Scan() {
  12. content += strings.Repeat("\t", indent) + "# " + strings.TrimSpace(scanner.Text()) + "\n"
  13. }
  14. content = strings.TrimLeft(content, "\n")
  15. return
  16. }
  17. func (c *NgxConfig) BuildConfig() (content string, err error) {
  18. // Custom
  19. if c.Custom != "" {
  20. content += c.Custom
  21. content += "\n\n"
  22. }
  23. // Upstreams
  24. for _, u := range c.Upstreams {
  25. upstream := ""
  26. var comments string
  27. for _, directive := range u.Directives {
  28. if directive.Comments != "" {
  29. comments = buildComments(directive.Comments, 1)
  30. }
  31. upstream += fmt.Sprintf("%s\t%s;\n", comments, directive.Orig())
  32. }
  33. comments = buildComments(u.Comments, 1)
  34. content += fmt.Sprintf("upstream %s {\n%s%s}\n\n", u.Name, comments, upstream)
  35. }
  36. // Servers
  37. for _, s := range c.Servers {
  38. server := ""
  39. // directives
  40. for _, directive := range s.Directives {
  41. var comments string
  42. if directive.Comments != "" {
  43. comments = buildComments(directive.Comments, 1)
  44. }
  45. if directive.Params != "" {
  46. server += fmt.Sprintf("%s\t%s;\n", comments, directive.Orig())
  47. }
  48. }
  49. if len(s.Directives) > 0 {
  50. server += "\n"
  51. }
  52. // locations
  53. locations := ""
  54. for _, location := range s.Locations {
  55. locationContent := ""
  56. scanner := bufio.NewScanner(strings.NewReader(location.Content))
  57. for scanner.Scan() {
  58. locationContent += "\t\t" + scanner.Text() + "\n"
  59. }
  60. var comments string
  61. if location.Comments != "" {
  62. comments = buildComments(location.Comments, 1)
  63. }
  64. locations += fmt.Sprintf("%s\tlocation %s {\n%s\t}\n\n", comments, location.Path, locationContent)
  65. }
  66. server += locations
  67. var comments string
  68. if s.Comments != "" {
  69. comments = buildComments(s.Comments, 0) + "\n"
  70. }
  71. content += fmt.Sprintf("%sserver {\n%s}\n\n", comments, server)
  72. }
  73. p := parser.NewStringParser(content, parser.WithSkipValidDirectivesErr())
  74. config, err := p.Parse()
  75. if err != nil {
  76. return
  77. }
  78. content = gonginx.DumpConfig(config, gonginx.IndentedStyle)
  79. return
  80. }