@@ -32,40 +32,63 @@ type Configuration struct {
3232 Livingio_RES_Server string `json:"livingio_res_server"`
3333 PostFS string `json:"postFS"`
3434 LogFileName string `json:"logFileName"`
35+ EnableDatabaseAndAPI bool `json:"enableDatabaseAndAPI"`
36+ SqliteLocation string `json:"sqliteLocation"`
3537}
3638
3739var (
38- conf Configuration
40+ conf Configuration
41+ useDatabaseAndAPI bool = false
3942)
4043
4144func main () {
45+ log .Println ("Starting application..." )
4246 //load config
4347 confFile := flag .String ("c" , "emoProxy.conf" , "config file to use" )
48+ Port := flag .Int ("port" , 8080 , "http port" )
4449 flag .Parse ()
4550
4651 err := loadConfig (* confFile )
4752 if err != nil {
4853 log .Println ("can't read conf file" , * confFile , "- using default config" )
4954 }
50-
55+ log . Println ( "config loaded" )
5156 writePid ()
5257
5358 // disable ssl checks
5459 http .DefaultTransport .(* http.Transport ).TLSClientConfig = & tls.Config {InsecureSkipVerify : true }
5560
61+ // parse flags
62+ log .Println ("Starting app on port: " , * Port )
63+
5664 // redirect log
5765 logFile , err := os .OpenFile (conf .LogFileName , os .O_APPEND | os .O_RDWR | os .O_CREATE , 0644 )
5866 if err != nil {
5967 log .Panic (err )
6068 }
69+
6170 defer logFile .Close ()
6271 log .SetOutput (logFile )
6372 log .SetFlags (log .Lshortfile | log .LstdFlags )
6473
65- // parse flags
66- Port := flag .Int ("port" , 8081 , "http port" )
67- flag .Parse ()
68- log .Println ("Port: " , * Port )
74+ useDatabaseAndAPI = conf .EnableDatabaseAndAPI
75+
76+ if useDatabaseAndAPI {
77+ log .Println ("Database and API enabled" )
78+
79+ dbPath := conf .SqliteLocation
80+ flagDbPath := flag .String ("db" , "" , "path to the sqlite database file" )
81+ if * flagDbPath != "" {
82+ dbPath = * flagDbPath
83+ }
84+ flag .Parse ()
85+ dbCreateErr := InitDB (dbPath )
86+ if dbCreateErr != nil {
87+ log .Panic (dbCreateErr )
88+ }
89+ } else {
90+ log .Println ("Note: Database and API disabled" )
91+ }
6992
7093 // handle time requests
7194 http .HandleFunc ("/time" , func (w http.ResponseWriter , r * http.Request ) {
@@ -152,7 +175,40 @@ func main() {
152175 fmt .Fprint (w , body )
153176 })
154177
155- log .Fatal (http .ListenAndServe (":" + strconv .Itoa (* Port ), nil ))
178+ if useDatabaseAndAPI {
179+ // proxy-api endpoints
180+ http .HandleFunc ("/proxy-api/requests" , func (w http.ResponseWriter , r * http.Request ) {
181+ logRequest (r )
182+ w .Header ().Set ("Content-Type" , "application/json; charset=utf-8" )
183+ w .WriteHeader (http .StatusOK )
184+
185+ requests , err := getAllRequests ()
186+ if err != nil {
187+ http .Error (w , fmt .Sprintf (`{"error":"%v"}` , err ), http .StatusInternalServerError )
188+ return
189+ }
190+ json .NewEncoder (w ).Encode (requests )
191+ })
192+ }
193+
194+ log .Fatal (http .ListenAndServe (":" + strconv .Itoa (* Port ), corsMiddleware (http .DefaultServeMux )))
195+ }
196+
197+ func corsMiddleware (next http.Handler ) http.Handler {
198+ return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
199+ // Replace "*" with "http://localhost:3000" for better security
200+ w .Header ().Set ("Access-Control-Allow-Origin" , "http://localhost:3000" )
201+ w .Header ().Set ("Access-Control-Allow-Methods" , "POST, GET, OPTIONS, PUT, DELETE" )
202+ w .Header ().Set ("Access-Control-Allow-Headers" , "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization" )
203+
204+ // Handle the preflight OPTIONS request
205+ if r .Method == "OPTIONS" {
206+ w .WriteHeader (http .StatusOK )
207+ return
208+ }
209+
210+ next .ServeHTTP (w , r )
211+ })
156212}
157213
158214func loadConfig (filename string ) error {
@@ -164,6 +220,8 @@ func loadConfig(filename string) error {
164220 Livingio_RES_Server : "res.living.ai" ,
165221 PostFS : "/tmp/" ,
166222 LogFileName : "/var/log/emoProxy.log" ,
223+ EnableDatabaseAndAPI : false ,
224+ SqliteLocation : "/var/data/emo_logs.db" ,
167225 }
168226
169227 bytes , err := os .ReadFile (filename )
@@ -228,16 +286,17 @@ func logBody(contentType string, body []byte, prefix string) {
228286
229287func makeApiRequest (r * http.Request ) string {
230288 var request * http.Request
289+ var requestBody []byte
231290 switch r .Method {
232291 case "GET" :
233292 request , _ = http .NewRequest ("GET" , "https://" + conf .Livingio_API_Server + r .URL .RequestURI (), nil )
234293 case "POST" :
235- body , _ := io .ReadAll (r .Body )
294+ requestBody , _ := io .ReadAll (r .Body )
236295
237296 // write post request body to fs
238- logBody (r .Header .Get ("Content-Type" ), body , "apiReq_" )
297+ logBody (r .Header .Get ("Content-Type" ), requestBody , "apiReq_" )
239298
240- request , _ = http .NewRequest ("POST" , "https://" + conf .Livingio_API_Server + r .URL .RequestURI (), bytes .NewBuffer (body ))
299+ request , _ = http .NewRequest ("POST" , "https://" + conf .Livingio_API_Server + r .URL .RequestURI (), bytes .NewBuffer (requestBody ))
241300
242301 request .Header .Add ("Content-Type" , r .Header .Get ("Content-Type" ))
243302 request .Header .Add ("Content-Length" , r .Header .Get ("Content-Length" ))
@@ -269,6 +328,10 @@ func makeApiRequest(r *http.Request) string {
269328 log .Println ("Server response: " , string (body ))
270329
271330 logResponse (response )
331+
332+ if useDatabaseAndAPI {
333+ saveRequest (r .URL .RequestURI (), string (requestBody ), string (body ))
334+ }
272335 return string (body )
273336}
274337
@@ -301,6 +364,10 @@ func makeTtsRequest(r *http.Request) string {
301364 // write post request body to fs
302365 logBody (response .Header .Get ("Content-Type" ), body , "tts_" )
303366 logResponse (response )
367+
368+ if useDatabaseAndAPI {
369+ saveRequest (r .URL .RequestURI (), "" , "" )
370+ }
304371 return string (body )
305372}
306373
@@ -333,6 +400,10 @@ func makeApiTtsRequest(r *http.Request) string {
333400 // write post request body to fs
334401 logBody (response .Header .Get ("Content-Type" ), body , "apitts_" )
335402 logResponse (response )
403+
404+ if useDatabaseAndAPI {
405+ saveRequest (r .URL .RequestURI (), "" , string (body ))
406+ }
336407 return string (body )
337408}
338409
@@ -369,5 +440,9 @@ func makeResRequest(r *http.Request, w http.ResponseWriter) string {
369440 }
370441
371442 logResponse (response )
443+
444+ if useDatabaseAndAPI {
445+ saveRequest (r .URL .RequestURI (), "" , string (body ))
446+ }
372447 return string (body )
373448}
0 commit comments