build_config.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package nginx
  2. import (
  3. "bufio"
  4. "fmt"
  5. "strings"
  6. )
  7. func buildComments(orig string, indent int) (content string) {
  8. scanner := bufio.NewScanner(strings.NewReader(orig))
  9. for scanner.Scan() {
  10. content += strings.Repeat("\t", indent) + "# " + scanner.Text() + "\n"
  11. }
  12. content = strings.TrimLeft(content, "\n")
  13. return
  14. }
  15. func (c *NgxConfig) BuildConfig() (content string) {
  16. // Custom
  17. if c.Custom != "" {
  18. content += fmtCode(c.Custom)
  19. content += "\n\n"
  20. }
  21. // Upstreams
  22. for _, u := range c.Upstreams {
  23. upstream := ""
  24. var comments string
  25. for _, directive := range u.Directives {
  26. if directive.Comments != "" {
  27. comments = buildComments(directive.Comments, 1)
  28. }
  29. upstream += fmt.Sprintf("%s\t%s;\n", comments, directive.Orig())
  30. }
  31. comments = buildComments(u.Comments, 1)
  32. content += fmt.Sprintf("upstream %s {\n%s%s}\n\n", u.Name, comments, upstream)
  33. }
  34. // Servers
  35. for _, s := range c.Servers {
  36. server := ""
  37. // directives
  38. for _, directive := range s.Directives {
  39. var comments string
  40. if directive.Comments != "" {
  41. comments = buildComments(directive.Comments, 1)
  42. }
  43. if directive.Directive == If {
  44. server += fmt.Sprintf("%s%s\n", comments, fmtCodeWithIndent(directive.Params, 1))
  45. } else 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. return
  74. }