refactor: nginx conf parser #45
parent
b7d5590714
commit
5cc9068f5f
@ -1 +1 @@
|
||||
{"version":"1.7.0","build_id":63,"total_build":133}
|
||||
{"version":"1.7.0","build_id":0,"total_build":0}
|
||||
@ -1,173 +1,184 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"github.com/0xJacky/Nginx-UI/server/pkg/config_list"
|
||||
"github.com/0xJacky/Nginx-UI/server/pkg/nginx"
|
||||
"github.com/gin-gonic/gin"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"github.com/0xJacky/Nginx-UI/server/pkg/config_list"
|
||||
"github.com/0xJacky/Nginx-UI/server/pkg/nginx"
|
||||
"github.com/gin-gonic/gin"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func GetConfigs(c *gin.Context) {
|
||||
orderBy := c.Query("order_by")
|
||||
sort := c.DefaultQuery("sort", "desc")
|
||||
dir := c.DefaultQuery("dir", "/")
|
||||
|
||||
mySort := map[string]string{
|
||||
"name": "string",
|
||||
"modify": "time",
|
||||
"is_dir": "bool",
|
||||
}
|
||||
|
||||
configFiles, err := os.ReadDir(nginx.GetNginxConfPath(dir))
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
var configs []gin.H
|
||||
|
||||
for i := range configFiles {
|
||||
file := configFiles[i]
|
||||
fileInfo, _ := file.Info()
|
||||
|
||||
switch mode := fileInfo.Mode(); {
|
||||
case mode.IsRegular(): // regular file, not a hidden file
|
||||
if "." == file.Name()[0:1] {
|
||||
continue
|
||||
}
|
||||
case mode&os.ModeSymlink != 0: // is a symbol
|
||||
var targetPath string
|
||||
targetPath, err = os.Readlink(nginx.GetNginxConfPath(file.Name()))
|
||||
if err != nil {
|
||||
log.Println("GetConfigs Read Symlink Error", targetPath, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
configs = append(configs, gin.H{
|
||||
"name": file.Name(),
|
||||
"size": fileInfo.Size(),
|
||||
"modify": fileInfo.ModTime(),
|
||||
"is_dir": file.IsDir(),
|
||||
})
|
||||
}
|
||||
|
||||
configs = config_list.Sort(orderBy, sort, mySort[orderBy], configs)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": configs,
|
||||
})
|
||||
orderBy := c.Query("order_by")
|
||||
sort := c.DefaultQuery("sort", "desc")
|
||||
dir := c.DefaultQuery("dir", "/")
|
||||
|
||||
mySort := map[string]string{
|
||||
"name": "string",
|
||||
"modify": "time",
|
||||
"is_dir": "bool",
|
||||
}
|
||||
|
||||
configFiles, err := os.ReadDir(nginx.GetNginxConfPath(dir))
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
var configs []gin.H
|
||||
|
||||
for i := range configFiles {
|
||||
file := configFiles[i]
|
||||
fileInfo, _ := file.Info()
|
||||
|
||||
switch mode := fileInfo.Mode(); {
|
||||
case mode.IsRegular(): // regular file, not a hidden file
|
||||
if "." == file.Name()[0:1] {
|
||||
continue
|
||||
}
|
||||
case mode&os.ModeSymlink != 0: // is a symbol
|
||||
var targetPath string
|
||||
targetPath, err = os.Readlink(nginx.GetNginxConfPath(file.Name()))
|
||||
if err != nil {
|
||||
log.Println("GetConfigs Read Symlink Error", targetPath, err)
|
||||
continue
|
||||
}
|
||||
|
||||
var targetInfo os.FileInfo
|
||||
targetInfo, err = os.Stat(targetPath)
|
||||
if err != nil {
|
||||
log.Println("GetConfigs Stat Error", targetPath, err)
|
||||
continue
|
||||
}
|
||||
// but target file is not a dir
|
||||
if targetInfo.IsDir() {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
configs = append(configs, gin.H{
|
||||
"name": file.Name(),
|
||||
"size": fileInfo.Size(),
|
||||
"modify": fileInfo.ModTime(),
|
||||
"is_dir": file.IsDir(),
|
||||
})
|
||||
}
|
||||
|
||||
configs = config_list.Sort(orderBy, sort, mySort[orderBy], configs)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": configs,
|
||||
})
|
||||
}
|
||||
|
||||
func GetConfig(c *gin.Context) {
|
||||
name := c.Param("name")
|
||||
path := filepath.Join(nginx.GetNginxConfPath("/"), name)
|
||||
name := c.Param("name")
|
||||
path := filepath.Join(nginx.GetNginxConfPath("/"), name)
|
||||
|
||||
content, err := os.ReadFile(path)
|
||||
content, err := os.ReadFile(path)
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"config": string(content),
|
||||
})
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"config": string(content),
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
type AddConfigJson struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Content string `json:"content" binding:"required"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Content string `json:"content" binding:"required"`
|
||||
}
|
||||
|
||||
func AddConfig(c *gin.Context) {
|
||||
var request AddConfigJson
|
||||
err := c.BindJSON(&request)
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
name := request.Name
|
||||
content := request.Content
|
||||
|
||||
path := filepath.Join(nginx.GetNginxConfPath("/"), name)
|
||||
|
||||
if _, err = os.Stat(path); err == nil {
|
||||
c.JSON(http.StatusNotAcceptable, gin.H{
|
||||
"message": "config exist",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if content != "" {
|
||||
err = os.WriteFile(path, []byte(content), 0644)
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
output := nginx.ReloadNginx()
|
||||
|
||||
if output != "" && strings.Contains(output, "error") {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": output,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"name": name,
|
||||
"content": content,
|
||||
})
|
||||
var request AddConfigJson
|
||||
err := c.BindJSON(&request)
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
name := request.Name
|
||||
content := request.Content
|
||||
|
||||
path := filepath.Join(nginx.GetNginxConfPath("/"), name)
|
||||
|
||||
if _, err = os.Stat(path); err == nil {
|
||||
c.JSON(http.StatusNotAcceptable, gin.H{
|
||||
"message": "config exist",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if content != "" {
|
||||
err = os.WriteFile(path, []byte(content), 0644)
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
output := nginx.ReloadNginx()
|
||||
|
||||
if output != "" && strings.Contains(output, "error") {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": output,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"name": name,
|
||||
"content": content,
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
type EditConfigJson struct {
|
||||
Content string `json:"content" binding:"required"`
|
||||
Content string `json:"content" binding:"required"`
|
||||
}
|
||||
|
||||
func EditConfig(c *gin.Context) {
|
||||
name := c.Param("name")
|
||||
var request EditConfigJson
|
||||
err := c.BindJSON(&request)
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
path := filepath.Join(nginx.GetNginxConfPath("/"), name)
|
||||
content := request.Content
|
||||
|
||||
origContent, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
if content != "" && content != string(origContent) {
|
||||
// model.CreateBackup(path)
|
||||
err = os.WriteFile(path, []byte(content), 0644)
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
output := nginx.ReloadNginx()
|
||||
|
||||
if output != "" && strings.Contains(output, "error") {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": output,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
GetConfig(c)
|
||||
name := c.Param("name")
|
||||
var request EditConfigJson
|
||||
err := c.BindJSON(&request)
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
path := filepath.Join(nginx.GetNginxConfPath("/"), name)
|
||||
content := request.Content
|
||||
|
||||
origContent, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
if content != "" && content != string(origContent) {
|
||||
// model.CreateBackup(path)
|
||||
err = os.WriteFile(path, []byte(content), 0644)
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
output := nginx.ReloadNginx()
|
||||
|
||||
if output != "" && strings.Contains(output, "error") {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": output,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
GetConfig(c)
|
||||
}
|
||||
|
||||
@ -1,381 +1,381 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"github.com/0xJacky/Nginx-UI/server/model"
|
||||
"github.com/0xJacky/Nginx-UI/server/pkg/cert"
|
||||
"github.com/0xJacky/Nginx-UI/server/pkg/config_list"
|
||||
"github.com/0xJacky/Nginx-UI/server/pkg/nginx"
|
||||
"github.com/gin-gonic/gin"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
"github.com/0xJacky/Nginx-UI/server/model"
|
||||
"github.com/0xJacky/Nginx-UI/server/pkg/cert"
|
||||
"github.com/0xJacky/Nginx-UI/server/pkg/config_list"
|
||||
"github.com/0xJacky/Nginx-UI/server/pkg/nginx"
|
||||
"github.com/gin-gonic/gin"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func GetDomains(c *gin.Context) {
|
||||
name := c.Query("name")
|
||||
orderBy := c.Query("order_by")
|
||||
sort := c.DefaultQuery("sort", "desc")
|
||||
|
||||
mySort := map[string]string{
|
||||
"enabled": "bool",
|
||||
"name": "string",
|
||||
"modify": "time",
|
||||
}
|
||||
|
||||
configFiles, err := os.ReadDir(nginx.GetNginxConfPath("sites-available"))
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
enabledConfig, err := os.ReadDir(filepath.Join(nginx.GetNginxConfPath("sites-enabled")))
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
enabledConfigMap := make(map[string]bool)
|
||||
for i := range enabledConfig {
|
||||
enabledConfigMap[enabledConfig[i].Name()] = true
|
||||
}
|
||||
|
||||
var configs []gin.H
|
||||
|
||||
for i := range configFiles {
|
||||
file := configFiles[i]
|
||||
fileInfo, _ := file.Info()
|
||||
if !file.IsDir() {
|
||||
if name != "" && !strings.Contains(file.Name(), name) {
|
||||
continue
|
||||
}
|
||||
configs = append(configs, gin.H{
|
||||
"name": file.Name(),
|
||||
"size": fileInfo.Size(),
|
||||
"modify": fileInfo.ModTime(),
|
||||
"enabled": enabledConfigMap[file.Name()],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
configs = config_list.Sort(orderBy, sort, mySort[orderBy], configs)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": configs,
|
||||
})
|
||||
name := c.Query("name")
|
||||
orderBy := c.Query("order_by")
|
||||
sort := c.DefaultQuery("sort", "desc")
|
||||
|
||||
mySort := map[string]string{
|
||||
"enabled": "bool",
|
||||
"name": "string",
|
||||
"modify": "time",
|
||||
}
|
||||
|
||||
configFiles, err := os.ReadDir(nginx.GetNginxConfPath("sites-available"))
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
enabledConfig, err := os.ReadDir(filepath.Join(nginx.GetNginxConfPath("sites-enabled")))
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
enabledConfigMap := make(map[string]bool)
|
||||
for i := range enabledConfig {
|
||||
enabledConfigMap[enabledConfig[i].Name()] = true
|
||||
}
|
||||
|
||||
var configs []gin.H
|
||||
|
||||
for i := range configFiles {
|
||||
file := configFiles[i]
|
||||
fileInfo, _ := file.Info()
|
||||
if !file.IsDir() {
|
||||
if name != "" && !strings.Contains(file.Name(), name) {
|
||||
continue
|
||||
}
|
||||
configs = append(configs, gin.H{
|
||||
"name": file.Name(),
|
||||
"size": fileInfo.Size(),
|
||||
"modify": fileInfo.ModTime(),
|
||||
"enabled": enabledConfigMap[file.Name()],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
configs = config_list.Sort(orderBy, sort, mySort[orderBy], configs)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": configs,
|
||||
})
|
||||
}
|
||||
|
||||
type CertificateInfo struct {
|
||||
SubjectName string `json:"subject_name"`
|
||||
IssuerName string `json:"issuer_name"`
|
||||
NotAfter time.Time `json:"not_after"`
|
||||
NotBefore time.Time `json:"not_before"`
|
||||
SubjectName string `json:"subject_name"`
|
||||
IssuerName string `json:"issuer_name"`
|
||||
NotAfter time.Time `json:"not_after"`
|
||||
NotBefore time.Time `json:"not_before"`
|
||||
}
|
||||
|
||||
func GetDomain(c *gin.Context) {
|
||||
rewriteName, ok := c.Get("rewriteConfigFileName")
|
||||
rewriteName, ok := c.Get("rewriteConfigFileName")
|
||||
|
||||
name := c.Param("name")
|
||||
name := c.Param("name")
|
||||
|
||||
// for modify filename
|
||||
if ok {
|
||||
name = rewriteName.(string)
|
||||
}
|
||||
// for modify filename
|
||||
if ok {
|
||||
name = rewriteName.(string)
|
||||
}
|
||||
|
||||
path := filepath.Join(nginx.GetNginxConfPath("sites-available"), name)
|
||||
path := filepath.Join(nginx.GetNginxConfPath("sites-available"), name)
|
||||
|
||||
enabled := true
|
||||
if _, err := os.Stat(filepath.Join(nginx.GetNginxConfPath("sites-enabled"), name)); os.IsNotExist(err) {
|
||||
enabled = false
|
||||
}
|
||||
enabled := true
|
||||
if _, err := os.Stat(filepath.Join(nginx.GetNginxConfPath("sites-enabled"), name)); os.IsNotExist(err) {
|
||||
enabled = false
|
||||
}
|
||||
|
||||
config, err := nginx.ParseNgxConfig(path)
|
||||
config, err := nginx.ParseNgxConfig(path)
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
certInfoMap := make(map[int]CertificateInfo)
|
||||
var serverName string
|
||||
for serverIdx, server := range config.Servers {
|
||||
for _, directive := range server.Directives {
|
||||
certInfoMap := make(map[int]CertificateInfo)
|
||||
var serverName string
|
||||
for serverIdx, server := range config.Servers {
|
||||
for _, directive := range server.Directives {
|
||||
|
||||
if directive.Directive == "server_name" {
|
||||
serverName = strings.ReplaceAll(directive.Params, " ", "_")
|
||||
continue
|
||||
}
|
||||
if directive.Directive == "server_name" {
|
||||
serverName = strings.ReplaceAll(directive.Params, " ", "_")
|
||||
continue
|
||||
}
|
||||
|
||||
if directive.Directive == "ssl_certificate" {
|
||||
if directive.Directive == "ssl_certificate" {
|
||||
|
||||
pubKey, err := cert.GetCertInfo(directive.Params)
|
||||
pubKey, err := cert.GetCertInfo(directive.Params)
|
||||
|
||||
if err != nil {
|
||||
log.Println("Failed to get certificate information", err)
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
log.Println("Failed to get certificate information", err)
|
||||
break
|
||||
}
|
||||
|
||||
certInfoMap[serverIdx] = CertificateInfo{
|
||||
SubjectName: pubKey.Subject.CommonName,
|
||||
IssuerName: pubKey.Issuer.CommonName,
|
||||
NotAfter: pubKey.NotAfter,
|
||||
NotBefore: pubKey.NotBefore,
|
||||
}
|
||||
certInfoMap[serverIdx] = CertificateInfo{
|
||||
SubjectName: pubKey.Subject.CommonName,
|
||||
IssuerName: pubKey.Issuer.CommonName,
|
||||
NotAfter: pubKey.NotAfter,
|
||||
NotBefore: pubKey.NotBefore,
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
certModel, _ := model.FirstCert(serverName)
|
||||
certModel, _ := model.FirstCert(serverName)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"enabled": enabled,
|
||||
"name": name,
|
||||
"config": config.BuildConfig(),
|
||||
"tokenized": config,
|
||||
"auto_cert": certModel.AutoCert == model.AutoCertEnabled,
|
||||
"cert_info": certInfoMap,
|
||||
})
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"enabled": enabled,
|
||||
"name": name,
|
||||
"config": config.FmtCode(),
|
||||
"tokenized": config,
|
||||
"auto_cert": certModel.AutoCert == model.AutoCertEnabled,
|
||||
"cert_info": certInfoMap,
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func EditDomain(c *gin.Context) {
|
||||
name := c.Param("name")
|
||||
|
||||
if name == "" {
|
||||
c.JSON(http.StatusNotAcceptable, gin.H{
|
||||
"message": "param name is empty",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var json struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
if !BindAndValid(c, &json) {
|
||||
return
|
||||
}
|
||||
|
||||
path := filepath.Join(nginx.GetNginxConfPath("sites-available"), name)
|
||||
|
||||
err := os.WriteFile(path, []byte(json.Content), 0644)
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
enabledConfigFilePath := filepath.Join(nginx.GetNginxConfPath("sites-enabled"), name)
|
||||
// rename the config file if needed
|
||||
if name != json.Name {
|
||||
newPath := filepath.Join(nginx.GetNginxConfPath("sites-available"), json.Name)
|
||||
// recreate soft link
|
||||
log.Println(enabledConfigFilePath)
|
||||
if _, err = os.Stat(enabledConfigFilePath); err == nil {
|
||||
log.Println(enabledConfigFilePath)
|
||||
_ = os.Remove(enabledConfigFilePath)
|
||||
enabledConfigFilePath = filepath.Join(nginx.GetNginxConfPath("sites-enabled"), json.Name)
|
||||
err = os.Symlink(newPath, enabledConfigFilePath)
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
err = os.Rename(path, newPath)
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
name = json.Name
|
||||
c.Set("rewriteConfigFileName", name)
|
||||
|
||||
}
|
||||
|
||||
enabledConfigFilePath = filepath.Join(nginx.GetNginxConfPath("sites-enabled"), name)
|
||||
if _, err = os.Stat(enabledConfigFilePath); err == nil {
|
||||
// Test nginx configuration
|
||||
err = nginx.TestNginxConf()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
output := nginx.ReloadNginx()
|
||||
|
||||
if output != "" && strings.Contains(output, "error") {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": output,
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
GetDomain(c)
|
||||
name := c.Param("name")
|
||||
|
||||
if name == "" {
|
||||
c.JSON(http.StatusNotAcceptable, gin.H{
|
||||
"message": "param name is empty",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var json struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
if !BindAndValid(c, &json) {
|
||||
return
|
||||
}
|
||||
|
||||
path := filepath.Join(nginx.GetNginxConfPath("sites-available"), name)
|
||||
|
||||
err := os.WriteFile(path, []byte(json.Content), 0644)
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
enabledConfigFilePath := filepath.Join(nginx.GetNginxConfPath("sites-enabled"), name)
|
||||
// rename the config file if needed
|
||||
if name != json.Name {
|
||||
newPath := filepath.Join(nginx.GetNginxConfPath("sites-available"), json.Name)
|
||||
// recreate soft link
|
||||
log.Println(enabledConfigFilePath)
|
||||
if _, err = os.Stat(enabledConfigFilePath); err == nil {
|
||||
log.Println(enabledConfigFilePath)
|
||||
_ = os.Remove(enabledConfigFilePath)
|
||||
enabledConfigFilePath = filepath.Join(nginx.GetNginxConfPath("sites-enabled"), json.Name)
|
||||
err = os.Symlink(newPath, enabledConfigFilePath)
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
err = os.Rename(path, newPath)
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
name = json.Name
|
||||
c.Set("rewriteConfigFileName", name)
|
||||
|
||||
}
|
||||
|
||||
enabledConfigFilePath = filepath.Join(nginx.GetNginxConfPath("sites-enabled"), name)
|
||||
if _, err = os.Stat(enabledConfigFilePath); err == nil {
|
||||
// Test nginx configuration
|
||||
err = nginx.TestNginxConf()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
output := nginx.ReloadNginx()
|
||||
|
||||
if output != "" && strings.Contains(output, "error") {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": output,
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
GetDomain(c)
|
||||
}
|
||||
|
||||
func EnableDomain(c *gin.Context) {
|
||||
configFilePath := filepath.Join(nginx.GetNginxConfPath("sites-available"), c.Param("name"))
|
||||
enabledConfigFilePath := filepath.Join(nginx.GetNginxConfPath("sites-enabled"), c.Param("name"))
|
||||
|
||||
_, err := os.Stat(configFilePath)
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err = os.Stat(enabledConfigFilePath); os.IsNotExist(err) {
|
||||
err = os.Symlink(configFilePath, enabledConfigFilePath)
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Test nginx config, if not pass then rollback.
|
||||
err = nginx.TestNginxConf()
|
||||
if err != nil {
|
||||
_ = os.Remove(enabledConfigFilePath)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
output := nginx.ReloadNginx()
|
||||
|
||||
if output != "" && strings.Contains(output, "error") {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": output,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "ok",
|
||||
})
|
||||
configFilePath := filepath.Join(nginx.GetNginxConfPath("sites-available"), c.Param("name"))
|
||||
enabledConfigFilePath := filepath.Join(nginx.GetNginxConfPath("sites-enabled"), c.Param("name"))
|
||||
|
||||
_, err := os.Stat(configFilePath)
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err = os.Stat(enabledConfigFilePath); os.IsNotExist(err) {
|
||||
err = os.Symlink(configFilePath, enabledConfigFilePath)
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Test nginx config, if not pass then rollback.
|
||||
err = nginx.TestNginxConf()
|
||||
if err != nil {
|
||||
_ = os.Remove(enabledConfigFilePath)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
output := nginx.ReloadNginx()
|
||||
|
||||
if output != "" && strings.Contains(output, "error") {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": output,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "ok",
|
||||
})
|
||||
}
|
||||
|
||||
func DisableDomain(c *gin.Context) {
|
||||
enabledConfigFilePath := filepath.Join(nginx.GetNginxConfPath("sites-enabled"), c.Param("name"))
|
||||
|
||||
_, err := os.Stat(enabledConfigFilePath)
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
err = os.Remove(enabledConfigFilePath)
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
// delete auto cert record
|
||||
certModel := model.Cert{Domain: c.Param("name")}
|
||||
err = certModel.Remove()
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
output := nginx.ReloadNginx()
|
||||
|
||||
if output != "" {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": output,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "ok",
|
||||
})
|
||||
enabledConfigFilePath := filepath.Join(nginx.GetNginxConfPath("sites-enabled"), c.Param("name"))
|
||||
|
||||
_, err := os.Stat(enabledConfigFilePath)
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
err = os.Remove(enabledConfigFilePath)
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
// delete auto cert record
|
||||
certModel := model.Cert{Domain: c.Param("name")}
|
||||
err = certModel.Remove()
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
output := nginx.ReloadNginx()
|
||||
|
||||
if output != "" {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": output,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "ok",
|
||||
})
|
||||
}
|
||||
|
||||
func DeleteDomain(c *gin.Context) {
|
||||
var err error
|
||||
name := c.Param("name")
|
||||
availablePath := filepath.Join(nginx.GetNginxConfPath("sites-available"), name)
|
||||
enabledPath := filepath.Join(nginx.GetNginxConfPath("sites-enabled"), name)
|
||||
|
||||
if _, err = os.Stat(availablePath); os.IsNotExist(err) {
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
"message": "site not found",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if _, err = os.Stat(enabledPath); err == nil {
|
||||
c.JSON(http.StatusNotAcceptable, gin.H{
|
||||
"message": "site is enabled",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
certModel := model.Cert{Domain: name}
|
||||
_ = certModel.Remove()
|
||||
|
||||
err = os.Remove(availablePath)
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "ok",
|
||||
})
|
||||
var err error
|
||||
name := c.Param("name")
|
||||
availablePath := filepath.Join(nginx.GetNginxConfPath("sites-available"), name)
|
||||
enabledPath := filepath.Join(nginx.GetNginxConfPath("sites-enabled"), name)
|
||||
|
||||
if _, err = os.Stat(availablePath); os.IsNotExist(err) {
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
"message": "site not found",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if _, err = os.Stat(enabledPath); err == nil {
|
||||
c.JSON(http.StatusNotAcceptable, gin.H{
|
||||
"message": "site is enabled",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
certModel := model.Cert{Domain: name}
|
||||
_ = certModel.Remove()
|
||||
|
||||
err = os.Remove(availablePath)
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "ok",
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func AddDomainToAutoCert(c *gin.Context) {
|
||||
domain := c.Param("domain")
|
||||
domain = strings.ReplaceAll(domain, " ", "_")
|
||||
certModel, err := model.FirstOrCreateCert(domain)
|
||||
domain := c.Param("domain")
|
||||
domain = strings.ReplaceAll(domain, " ", "_")
|
||||
certModel, err := model.FirstOrCreateCert(domain)
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
err = certModel.Updates(&model.Cert{
|
||||
AutoCert: model.AutoCertEnabled,
|
||||
})
|
||||
err = certModel.Updates(&model.Cert{
|
||||
AutoCert: model.AutoCertEnabled,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, certModel)
|
||||
c.JSON(http.StatusOK, certModel)
|
||||
}
|
||||
|
||||
func RemoveDomainFromAutoCert(c *gin.Context) {
|
||||
domain := c.Param("domain")
|
||||
domain = strings.ReplaceAll(domain, " ", "_")
|
||||
certModel := model.Cert{
|
||||
Domain: domain,
|
||||
}
|
||||
|
||||
err := certModel.Updates(&model.Cert{
|
||||
AutoCert: model.AutoCertDisabled,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, nil)
|
||||
domain := c.Param("domain")
|
||||
domain = strings.ReplaceAll(domain, " ", "_")
|
||||
certModel := model.Cert{
|
||||
Domain: domain,
|
||||
}
|
||||
|
||||
err := certModel.Updates(&model.Cert{
|
||||
AutoCert: model.AutoCertDisabled,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, nil)
|
||||
}
|
||||
|
||||
@ -1,88 +1,90 @@
|
||||
package nginx
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"strings"
|
||||
"bufio"
|
||||
"fmt"
|
||||
"github.com/tufanbarisyildirim/gonginx"
|
||||
"github.com/tufanbarisyildirim/gonginx/parser"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func buildComments(orig string, indent int) (content string) {
|
||||
scanner := bufio.NewScanner(strings.NewReader(orig))
|
||||
for scanner.Scan() {
|
||||
content += strings.Repeat("\t", indent) + "# " + scanner.Text() + "\n"
|
||||
}
|
||||
content = strings.TrimLeft(content, "\n")
|
||||
return
|
||||
scanner := bufio.NewScanner(strings.NewReader(orig))
|
||||
for scanner.Scan() {
|
||||
content += strings.Repeat("\t", indent) + "# " + scanner.Text() + "\n"
|
||||
}
|
||||
content = strings.TrimLeft(content, "\n")
|
||||
return
|
||||
}
|
||||
|
||||
func (c *NgxConfig) BuildConfig() (content string) {
|
||||
|
||||
// Custom
|
||||
if c.Custom != "" {
|
||||
content += fmtCode(c.Custom)
|
||||
content += "\n\n"
|
||||
}
|
||||
// Custom
|
||||
if c.Custom != "" {
|
||||
content += c.Custom
|
||||
content += "\n\n"
|
||||
}
|
||||
|
||||
// Upstreams
|
||||
for _, u := range c.Upstreams {
|
||||
// Upstreams
|
||||
for _, u := range c.Upstreams {
|
||||
|
||||
upstream := ""
|
||||
var comments string
|
||||
for _, directive := range u.Directives {
|
||||
if directive.Comments != "" {
|
||||
comments = buildComments(directive.Comments, 1)
|
||||
}
|
||||
upstream += fmt.Sprintf("%s\t%s;\n", comments, directive.Orig())
|
||||
}
|
||||
comments = buildComments(u.Comments, 1)
|
||||
content += fmt.Sprintf("upstream %s {\n%s%s}\n\n", u.Name, comments, upstream)
|
||||
}
|
||||
upstream := ""
|
||||
var comments string
|
||||
for _, directive := range u.Directives {
|
||||
if directive.Comments != "" {
|
||||
comments = buildComments(directive.Comments, 1)
|
||||
}
|
||||
upstream += fmt.Sprintf("%s\t%s;\n", comments, directive.Orig())
|
||||
}
|
||||
comments = buildComments(u.Comments, 1)
|
||||
content += fmt.Sprintf("upstream %s {\n%s%s}\n\n", u.Name, comments, upstream)
|
||||
}
|
||||
|
||||
// Servers
|
||||
for _, s := range c.Servers {
|
||||
server := ""
|
||||
// Servers
|
||||
for _, s := range c.Servers {
|
||||
server := ""
|
||||
|
||||
// directives
|
||||
for _, directive := range s.Directives {
|
||||
var comments string
|
||||
if directive.Comments != "" {
|
||||
comments = buildComments(directive.Comments, 1)
|
||||
}
|
||||
if directive.Directive == If {
|
||||
server += fmt.Sprintf("%s%s\n", comments, fmtCodeWithIndent(directive.Params, 1))
|
||||
} else if directive.Params != "" {
|
||||
server += fmt.Sprintf("%s\t%s;\n", comments, directive.Orig())
|
||||
}
|
||||
}
|
||||
// directives
|
||||
for _, directive := range s.Directives {
|
||||
var comments string
|
||||
if directive.Comments != "" {
|
||||
comments = buildComments(directive.Comments, 1)
|
||||
}
|
||||
if directive.Params != "" {
|
||||
server += fmt.Sprintf("%s\t%s;\n", comments, directive.Orig())
|
||||
}
|
||||
}
|
||||
|
||||
if len(s.Directives) > 0 {
|
||||
server += "\n"
|
||||
}
|
||||
if len(s.Directives) > 0 {
|
||||
server += "\n"
|
||||
}
|
||||
|
||||
// locations
|
||||
locations := ""
|
||||
for _, location := range s.Locations {
|
||||
locationContent := ""
|
||||
scanner := bufio.NewScanner(strings.NewReader(location.Content))
|
||||
for scanner.Scan() {
|
||||
locationContent += "\t\t" + scanner.Text() + "\n"
|
||||
}
|
||||
var comments string
|
||||
if location.Comments != "" {
|
||||
comments = buildComments(location.Comments, 1)
|
||||
}
|
||||
locations += fmt.Sprintf("%s\tlocation %s {\n%s\t}\n\n", comments, location.Path, locationContent)
|
||||
}
|
||||
// locations
|
||||
locations := ""
|
||||
for _, location := range s.Locations {
|
||||
locationContent := ""
|
||||
scanner := bufio.NewScanner(strings.NewReader(location.Content))
|
||||
for scanner.Scan() {
|
||||
locationContent += "\t\t" + scanner.Text() + "\n"
|
||||
}
|
||||
var comments string
|
||||
if location.Comments != "" {
|
||||
comments = buildComments(location.Comments, 1)
|
||||
}
|
||||
locations += fmt.Sprintf("%s\tlocation %s {\n%s\t}\n\n", comments, location.Path, locationContent)
|
||||
}
|
||||
|
||||
server += locations
|
||||
server += locations
|
||||
|
||||
var comments string
|
||||
if s.Comments != "" {
|
||||
comments = buildComments(s.Comments, 0) + "\n"
|
||||
}
|
||||
var comments string
|
||||
if s.Comments != "" {
|
||||
comments = buildComments(s.Comments, 0) + "\n"
|
||||
}
|
||||
|
||||
content += fmt.Sprintf("%sserver {\n%s}\n\n", comments, server)
|
||||
}
|
||||
|
||||
return
|
||||
content += fmt.Sprintf("%sserver {\n%s}\n\n", comments, server)
|
||||
}
|
||||
p := parser.NewStringParser(content)
|
||||
config := p.Parse()
|
||||
content = gonginx.DumpConfig(config, gonginx.IndentedStyle)
|
||||
return
|
||||
}
|
||||
|
||||
@ -0,0 +1,36 @@
|
||||
map $http_upgrade $connection_upgrade {
|
||||
default upgrade;
|
||||
'' close;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name blog.jackyu.cn test.jackyu.cn;
|
||||
|
||||
location /.well-known/acme-challenge {
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real_IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $remote_addr:$remote_port;
|
||||
proxy_pass http://127.0.0.1:9180;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
listen [::]:443 ssl http2;
|
||||
server_name blog.jackyu.cn test.jackyu.cn;
|
||||
ssl_certificate /etc/nginx/ssl/blog.jackyu.cn_test.jackyu.cn/fullchain.cer;
|
||||
ssl_certificate_key /etc/nginx/ssl/blog.jackyu.cn_test.jackyu.cn/private.key;
|
||||
include enable-php-8.conf;
|
||||
|
||||
location /.well-known/acme-challenge {
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real_IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $remote_addr:$remote_port;
|
||||
proxy_pass http://127.0.0.1:9180;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,49 +1,10 @@
|
||||
package nginx
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"github.com/emirpasic/gods/stacks/linkedliststack"
|
||||
"strings"
|
||||
"github.com/tufanbarisyildirim/gonginx"
|
||||
)
|
||||
|
||||
func fmtCode(content string) (fmtContent string) {
|
||||
fmtContent = fmtCodeWithIndent(content, 0)
|
||||
return
|
||||
}
|
||||
|
||||
func fmtCodeWithIndent(content string, indent int) (fmtContent string) {
|
||||
/*
|
||||
Format content
|
||||
1. TrimSpace for each line
|
||||
2. use stack to count how many \t should add
|
||||
*/
|
||||
stack := linkedliststack.New()
|
||||
|
||||
scanner := bufio.NewScanner(strings.NewReader(content))
|
||||
|
||||
for scanner.Scan() {
|
||||
text := scanner.Text()
|
||||
text = strings.TrimSpace(text)
|
||||
|
||||
before := stack.Size()
|
||||
|
||||
for _, char := range text {
|
||||
matchParentheses(stack, char)
|
||||
}
|
||||
|
||||
after := stack.Size()
|
||||
|
||||
fmtContent += strings.Repeat("\t", indent)
|
||||
|
||||
if before == after {
|
||||
fmtContent += strings.Repeat("\t", stack.Size()) + text + "\n"
|
||||
} else {
|
||||
fmtContent += text + "\n"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fmtContent = strings.Trim(fmtContent, "\n")
|
||||
|
||||
return
|
||||
func (c *NgxConfig) FmtCode() (fmtContent string) {
|
||||
fmtContent = gonginx.DumpConfig(c.c, gonginx.IndentedStyle)
|
||||
return
|
||||
}
|
||||
|
||||
@ -0,0 +1,49 @@
|
||||
package nginx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/tufanbarisyildirim/gonginx"
|
||||
"github.com/tufanbarisyildirim/gonginx/parser"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNgxConfParse(t *testing.T) {
|
||||
p, err := parser.NewParser("conf/nextcloud_ngx.conf")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
n := p.Parse()
|
||||
|
||||
fn(n.Block, 0)
|
||||
|
||||
c, err := ParseNgxConfig("conf/nextcloud_ngx.conf")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
fmt.Println(c)
|
||||
c, err = ParseNgxConfig("conf/test.conf")
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return
|
||||
}
|
||||
fmt.Println(c)
|
||||
}
|
||||
|
||||
func fn(block gonginx.IBlock, deep int) {
|
||||
if block == nil {
|
||||
return
|
||||
}
|
||||
for _, v := range block.GetDirectives() {
|
||||
if len(v.GetComment()) > 0 {
|
||||
for _, c := range v.GetComment() {
|
||||
fmt.Println(strings.Repeat("\t", deep), c)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println(fmt.Sprintf("%s%s %s", strings.Repeat("\t", deep), v.GetName(), strings.Join(v.GetParameters(), " ")))
|
||||
fn(v.GetBlock(), deep+1)
|
||||
}
|
||||
}
|
||||
@ -1,150 +1,158 @@
|
||||
package nginx
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"github.com/emirpasic/gods/stacks/linkedliststack"
|
||||
"github.com/pkg/errors"
|
||||
"os"
|
||||
"github.com/tufanbarisyildirim/gonginx"
|
||||
"github.com/tufanbarisyildirim/gonginx/parser"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
const (
|
||||
Server = "server"
|
||||
Location = "location"
|
||||
Upstream = "upstream"
|
||||
CommentStart = "#"
|
||||
Empty = ""
|
||||
If = "if"
|
||||
Server = "server"
|
||||
Location = "location"
|
||||
Upstream = "upstream"
|
||||
)
|
||||
|
||||
func matchParentheses(stack *linkedliststack.Stack, v int32) {
|
||||
if v == '{' {
|
||||
stack.Push(v)
|
||||
} else if v == '}' {
|
||||
// stack is not empty and the top is == '{'
|
||||
if top, ok := stack.Peek(); ok && top == '{' {
|
||||
stack.Pop()
|
||||
} else {
|
||||
// fail
|
||||
stack.Push(v)
|
||||
func (s *NgxServer) parseServer(directive gonginx.IDirective) {
|
||||
if directive.GetBlock() == nil {
|
||||
return
|
||||
}
|
||||
for _, d := range directive.GetBlock().GetDirectives() {
|
||||
switch d.GetName() {
|
||||
case Location:
|
||||
location := &NgxLocation{
|
||||
Path: strings.Join(d.GetParameters(), " "),
|
||||
Comments: buildComment(d.GetComment()),
|
||||
}
|
||||
location.parseLocation(d, 0)
|
||||
s.Locations = append(s.Locations, location)
|
||||
default:
|
||||
dir := &NgxDirective{
|
||||
Directive: d.GetName(),
|
||||
Comments: buildComment(d.GetComment()),
|
||||
}
|
||||
dir.parseDirective(d, 0)
|
||||
s.Directives = append(s.Directives, dir)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func parseDirective(scanner *bufio.Scanner) (d NgxDirective) {
|
||||
text := strings.TrimSpace(scanner.Text())
|
||||
// escape empty line or comment line
|
||||
if len(text) < 1 {
|
||||
return
|
||||
}
|
||||
|
||||
if text[0] == '#' {
|
||||
d.Directive = "#"
|
||||
d.Params = strings.TrimLeft(text, "#")
|
||||
func (l *NgxLocation) parseLocation(directive gonginx.IDirective, deep int) {
|
||||
if directive.GetBlock() == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if len(text) > 1 {
|
||||
sep := len(text) - 1
|
||||
for k, v := range text {
|
||||
if unicode.IsSpace(v) {
|
||||
sep = k
|
||||
break
|
||||
for _, location := range directive.GetBlock().GetDirectives() {
|
||||
if len(location.GetComment()) > 0 {
|
||||
for _, c := range location.GetComment() {
|
||||
l.Content += strings.Repeat("\t", deep) + c + "\n"
|
||||
}
|
||||
}
|
||||
|
||||
d.Directive = text[0:sep]
|
||||
d.Params = text[sep:]
|
||||
} else {
|
||||
d.Directive = text
|
||||
return
|
||||
l.Content += strings.Repeat("\t", deep) + location.GetName() + " " + strings.Join(location.GetParameters(), " ") + ";\n"
|
||||
l.parseLocation(location, deep+1)
|
||||
}
|
||||
}
|
||||
|
||||
stack := linkedliststack.New()
|
||||
|
||||
if d.Directive == Server || d.Directive == Upstream || d.Directive == Location || d.Directive == If {
|
||||
// { } in one line
|
||||
// location = /.well-known/carddav { return 301 /remote.php/dav/; }
|
||||
if strings.Contains(d.Params, "{") {
|
||||
for _, v := range d.Params {
|
||||
matchParentheses(stack, v)
|
||||
}
|
||||
|
||||
if stack.Empty() {
|
||||
return
|
||||
func (d *NgxDirective) parseDirective(directive gonginx.IDirective, deep int) {
|
||||
if directive.GetBlock() != nil {
|
||||
d.Params += directive.GetName() + " "
|
||||
d.Directive = ""
|
||||
}
|
||||
d.Params += strings.Join(directive.GetParameters(), " ")
|
||||
if directive.GetBlock() != nil {
|
||||
d.Params += " {\n"
|
||||
for _, location := range directive.GetBlock().GetDirectives() {
|
||||
if len(location.GetComment()) > 0 {
|
||||
for _, c := range location.GetComment() {
|
||||
d.Params += strings.Repeat("\t", deep) + c + "\n"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// location ^~ /.well-known {
|
||||
// location ^~ /.well-known
|
||||
// {
|
||||
// location ^~ /.well-known
|
||||
//
|
||||
// {
|
||||
// { } not in one line
|
||||
for scanner.Scan() {
|
||||
text = strings.TrimSpace(scanner.Text())
|
||||
// escape empty line
|
||||
if text == "" {
|
||||
d.Params += strings.Repeat("\t", deep+1) + location.GetName() + " " +
|
||||
strings.Join(location.GetParameters(), " ") + ";\n"
|
||||
// d.parseDirective(location, deep+1)
|
||||
if location.GetBlock() == nil {
|
||||
continue
|
||||
}
|
||||
d.Params += "\n" + scanner.Text()
|
||||
for _, v := range text {
|
||||
matchParentheses(stack, v)
|
||||
if stack.Empty() {
|
||||
break
|
||||
}
|
||||
}
|
||||
if stack.Empty() {
|
||||
break
|
||||
for _, v := range location.GetBlock().GetDirectives() {
|
||||
d.parseDirective(v, deep+1)
|
||||
}
|
||||
}
|
||||
d.Params += "}\n"
|
||||
return
|
||||
}
|
||||
d.Params = strings.TrimSpace(d.Params)
|
||||
return
|
||||
}
|
||||
|
||||
func ParseNgxConfigByScanner(filename string, scanner *bufio.Scanner) (c *NgxConfig, err error) {
|
||||
c = NewNgxConfig(filename)
|
||||
|
||||
for scanner.Scan() {
|
||||
d := parseDirective(scanner)
|
||||
paramsScanner := bufio.NewScanner(strings.NewReader(d.Params))
|
||||
switch d.Directive {
|
||||
case Server:
|
||||
c.parseServer(paramsScanner)
|
||||
case Upstream:
|
||||
c.parseUpstream(paramsScanner)
|
||||
case CommentStart:
|
||||
c.commentQueue.Enqueue(d.Params)
|
||||
case Empty:
|
||||
continue
|
||||
default:
|
||||
c.Custom += d.Orig() + "\n"
|
||||
func (u *NgxUpstream) parseUpstream(directive gonginx.IDirective) {
|
||||
if directive.GetBlock() == nil {
|
||||
return
|
||||
}
|
||||
for _, us := range directive.GetBlock().GetDirectives() {
|
||||
d := &NgxDirective{
|
||||
Directive: us.GetName(),
|
||||
Params: strings.Join(us.GetParameters(), " "),
|
||||
Comments: buildComment(us.GetComment()),
|
||||
}
|
||||
u.Directives = append(u.Directives, d)
|
||||
}
|
||||
}
|
||||
|
||||
if err = scanner.Err(); err != nil {
|
||||
return nil, errors.Wrap(err, "error scanner in ParseNgxConfig")
|
||||
func (c *NgxConfig) parseCustom(directive gonginx.IDirective) {
|
||||
if directive.GetBlock() == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Attach the rest of the comments to the last server
|
||||
if len(c.Servers) > 0 {
|
||||
c.Servers[len(c.Servers)-1].Comments += c.commentQueue.DequeueAllComments()
|
||||
c.Custom += "{\n"
|
||||
for _, v := range directive.GetBlock().GetDirectives() {
|
||||
c.Custom += strings.Join(v.GetComment(), "\n") + "\n" +
|
||||
v.GetName() + " " + strings.Join(v.GetParameters(), " ") + ";\n"
|
||||
}
|
||||
c.Custom += "}\n"
|
||||
}
|
||||
|
||||
return c, nil
|
||||
func buildComment(c []string) string {
|
||||
return strings.ReplaceAll(strings.Join(c, "\n"), "#", "")
|
||||
}
|
||||
|
||||
func ParseNgxConfig(filename string) (c *NgxConfig, err error) {
|
||||
file, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "error open file in ParseNgxConfig")
|
||||
func parse(block gonginx.IBlock, ngxConfig *NgxConfig) {
|
||||
if block == nil {
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
for _, v := range block.GetDirectives() {
|
||||
comments := buildComment(v.GetComment())
|
||||
switch v.GetName() {
|
||||
case Server:
|
||||
server := NewNgxServer()
|
||||
server.Comments = comments
|
||||
server.parseServer(v)
|
||||
ngxConfig.Servers = append(ngxConfig.Servers, server)
|
||||
case Upstream:
|
||||
upstream := &NgxUpstream{}
|
||||
upstream.Comments = comments
|
||||
upstream.parseUpstream(v)
|
||||
ngxConfig.Upstreams = append(ngxConfig.Upstreams, upstream)
|
||||
default:
|
||||
ngxConfig.Custom += strings.Join(v.GetComment(), "\n") + "\n" +
|
||||
v.GetName() + " " + strings.Join(v.GetParameters(), " ") + "\n"
|
||||
ngxConfig.parseCustom(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
func ParseNgxConfigByContent(content string) (ngxConfig *NgxConfig) {
|
||||
p := parser.NewStringParser(content)
|
||||
c := p.Parse()
|
||||
ngxConfig = NewNgxConfig("")
|
||||
ngxConfig.c = c
|
||||
parse(c.Block, ngxConfig)
|
||||
return
|
||||
}
|
||||
|
||||
return ParseNgxConfigByScanner(filename, scanner)
|
||||
func ParseNgxConfig(filename string) (ngxConfig *NgxConfig, err error) {
|
||||
p, err := parser.NewParser(filename)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "error ParseNgxConfig")
|
||||
}
|
||||
c := p.Parse()
|
||||
ngxConfig = NewNgxConfig(filename)
|
||||
ngxConfig.c = c
|
||||
parse(c.Block, ngxConfig)
|
||||
return
|
||||
}
|
||||
|
||||
@ -1,125 +0,0 @@
|
||||
package nginx
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
func (c *NgxConfig) parseServer(scanner *bufio.Scanner) {
|
||||
server := NewNgxServer()
|
||||
for scanner.Scan() {
|
||||
d := parseDirective(scanner)
|
||||
switch d.Directive {
|
||||
case Location:
|
||||
server.parseLocation(d.Params)
|
||||
case CommentStart:
|
||||
server.commentQueue.Enqueue(d.Params)
|
||||
default:
|
||||
server.parseDirective(d)
|
||||
}
|
||||
}
|
||||
// Attach the rest of the comments to the last location
|
||||
if len(server.Locations) > 0 {
|
||||
server.Locations[len(server.Locations)-1].Comments += server.commentQueue.DequeueAllComments()
|
||||
}
|
||||
|
||||
// Attach comments which are over the current server
|
||||
server.Comments = c.commentQueue.DequeueAllComments()
|
||||
|
||||
c.Servers = append(c.Servers, server)
|
||||
}
|
||||
|
||||
func (c *NgxConfig) parseUpstream(scanner *bufio.Scanner) {
|
||||
upstream := &NgxUpstream{}
|
||||
for scanner.Scan() {
|
||||
d := NgxDirective{}
|
||||
text := strings.TrimSpace(scanner.Text())
|
||||
// escape empty line or comment line
|
||||
if len(text) < 1 || text[0] == '#' {
|
||||
return
|
||||
}
|
||||
|
||||
sep := len(text) - 1
|
||||
for k, v := range text {
|
||||
if unicode.IsSpace(v) {
|
||||
sep = k
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
d.Directive = text[0:sep]
|
||||
d.Params = strings.Trim(text[sep:], ";")
|
||||
|
||||
if d.Directive == Server {
|
||||
upstream.Directives = append(upstream.Directives, &d)
|
||||
} else if upstream.Name == "" {
|
||||
upstream.Name = d.Directive
|
||||
}
|
||||
}
|
||||
// attach comments which are over the current upstream
|
||||
upstream.Comments = c.commentQueue.DequeueAllComments()
|
||||
|
||||
c.Upstreams = append(c.Upstreams, upstream)
|
||||
}
|
||||
|
||||
func (s *NgxServer) parseDirective(d NgxDirective) {
|
||||
orig := d.Orig()
|
||||
// handle inline comments
|
||||
str, comments, _ := strings.Cut(orig, "#")
|
||||
|
||||
if d.Directive == If {
|
||||
d.Params = "if " + d.Params
|
||||
d.Params = fmtCode(d.Params)
|
||||
s.Directives = append(s.Directives, &d)
|
||||
return
|
||||
}
|
||||
|
||||
regExp := regexp.MustCompile("(\\S+?)\\s+?{?(.+)[;|}]")
|
||||
matchSlice := regExp.FindAllStringSubmatch(str, -1)
|
||||
|
||||
for k, v := range matchSlice {
|
||||
// [[gzip_min_length 256; gzip_min_length 256] [gzip_proxied expired no-cache no-store private no_last_modified no_etag auth; gzip_proxied expired no-cache no-store private no_last_modified no_etag auth] [gzip on; gzip on] [gzip_vary on; gzip_vary on] [location /x/ {} location /x/ {] [gzip_comp_level 4; gzip_comp_level 4]]
|
||||
if len(v) > 0 {
|
||||
scanner := bufio.NewScanner(strings.NewReader(v[0]))
|
||||
if scanner.Scan() {
|
||||
d = parseDirective(scanner)
|
||||
// inline location
|
||||
if d.Directive == Location {
|
||||
s.parseLocation(d.Orig())
|
||||
} else {
|
||||
|
||||
if k == 0 {
|
||||
d.Comments = s.commentQueue.DequeueAllComments()
|
||||
} else if k == len(matchSlice)-1 {
|
||||
d.Comments = comments
|
||||
}
|
||||
|
||||
// trim right ';'
|
||||
d.TrimParams()
|
||||
// map[directive]=>[]Params
|
||||
s.Directives = append(s.Directives, &d)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *NgxServer) parseLocation(str string) {
|
||||
path, content, _ := strings.Cut(str, "{")
|
||||
path = strings.TrimSpace(path)
|
||||
|
||||
content = strings.TrimSpace(content)
|
||||
content = strings.Trim(content, "}")
|
||||
|
||||
content = fmtCode(content)
|
||||
|
||||
location := &NgxLocation{
|
||||
Path: path,
|
||||
Content: content,
|
||||
}
|
||||
location.Comments = s.commentQueue.DequeueAllComments()
|
||||
s.Locations = append(s.Locations, location)
|
||||
}
|
||||
@ -1,42 +0,0 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/0xJacky/Nginx-UI/server/pkg/nginx"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNgxConfParse(t *testing.T) {
|
||||
c, err := nginx.ParseNgxConfig("nextcloud_ngx.conf")
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
fmt.Println(c.FileName)
|
||||
// directive in root
|
||||
fmt.Println("Upstream")
|
||||
for _, u := range c.Upstreams {
|
||||
fmt.Println("upstream name", u.Name)
|
||||
fmt.Printf("comments\n%v", u.Comments)
|
||||
for _, d := range u.Directives {
|
||||
fmt.Println("u.Directives.d", d)
|
||||
}
|
||||
}
|
||||
fmt.Println("==========================")
|
||||
fmt.Println("Servers")
|
||||
for _, s := range c.Servers {
|
||||
fmt.Printf("comments\n%v", s.Comments)
|
||||
for _, d := range s.Directives {
|
||||
fmt.Println(d)
|
||||
}
|
||||
// locations
|
||||
for _, location := range s.Locations {
|
||||
fmt.Printf("comments\n%v", location.Comments)
|
||||
fmt.Println("path", location.Path)
|
||||
fmt.Println("content", location.Content)
|
||||
fmt.Println("==========================")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Reference in New Issue