@@ -2,6 +2,7 @@ package api
22
33import (
44 "encoding/json"
5+ "github.com/0xJacky/Nginx-UI/server/pkg/nginx"
56 "github.com/0xJacky/Nginx-UI/server/settings"
67 "github.com/gin-gonic/gin"
78 "github.com/gorilla/websocket"
@@ -10,11 +11,15 @@ import (
1011 "io"
1112 "log"
1213 "net/http"
14+ "path/filepath"
1315)
1416
1517type controlStruct struct {
16- Fetch string `json:"fetch"`
17- Type string `json:"type"`
18+ Fetch string `json:"fetch"`
19+ Type string `json:"type"`
20+ ConfName string `json:"conf_name"`
21+ ServerIdx int `json:"server_idx"`
22+ DirectiveIdx int `json:"directive_idx"`
1823}
1924
2025func tailNginxLog (ws * websocket.Conn , controlChan chan controlStruct , errChan chan error ) {
@@ -33,11 +38,40 @@ func tailNginxLog(ws *websocket.Conn, controlChan chan controlStruct, errChan ch
3338 seek .Offset = 0
3439 seek .Whence = io .SeekEnd
3540 }
41+ var logPath string
42+ switch control .Type {
43+ case "site" :
44+ path := filepath .Join (nginx .GetNginxConfPath ("sites-available" ), control .ConfName )
45+ config , err := nginx .ParseNgxConfig (path )
46+ if err != nil {
47+ errChan <- errors .Wrap (err , "error parsing ngx config" )
48+ return
49+ }
50+
51+ if control .ServerIdx >= len (config .Servers ) {
52+ errChan <- errors .New ("serverIdx out of range" )
53+ return
54+ }
55+ if control .DirectiveIdx >= len (config .Servers [control .ServerIdx ].Directives ) {
56+ errChan <- errors .New ("DirectiveIdx out of range" )
57+ return
58+ }
59+ directive := config .Servers [control .ServerIdx ].Directives [control .DirectiveIdx ]
60+
61+ switch directive .Directive {
62+ case "access_log" , "error_log" :
63+ // ok
64+ default :
65+ errChan <- errors .New ("directive.Params neither access_log nor error_log" )
66+ return
67+ }
3668
37- logPath := settings . NginxLogSettings . AccessLogPath
69+ logPath = directive . Params
3870
39- if control . Type == "error" {
71+ case "error" :
4072 logPath = settings .NginxLogSettings .ErrorLogPath
73+ default :
74+ logPath = settings .NginxLogSettings .AccessLogPath
4175 }
4276
4377 // Create a tail
@@ -61,7 +95,6 @@ func tailNginxLog(ws *websocket.Conn, controlChan chan controlStruct, errChan ch
6195 return
6296 }
6397 case control = <- controlChan :
64- log .Println ("control change" )
6598 next = true
6699 break
67100 }
@@ -125,6 +158,7 @@ func NginxLog(c *gin.Context) {
125158
126159 if err = <- errChan ; err != nil {
127160 log .Println (err )
161+ _ = ws .WriteMessage (websocket .TextMessage , []byte (err .Error ()))
128162 return
129163 }
130164}
0 commit comments