From 16a8797efe18c27b78cd2df32a84f97502814632 Mon Sep 17 00:00:00 2001
From: Andrea Zagli <azagli@libero.it>
Date: Mon, 10 Oct 2022 17:12:55 +0200
Subject: [PATCH] When build error, show stderr instead of response.

---
 main.go | 43 ++++++++++++++++++++++++++++++++++---------
 1 file changed, 34 insertions(+), 9 deletions(-)

diff --git a/main.go b/main.go
index 158991d..78d528d 100644
--- a/main.go
+++ b/main.go
@@ -1,9 +1,10 @@
 package main
 
 import (
-	"errors"
+	_ "errors"
 	"fmt"
 	"log"
+	"io"
 	"net"
 	"net/http"
 	"net/http/httputil"
@@ -13,6 +14,7 @@ import (
 	"time"
 	"strings"
 	"flag"
+	"bytes"
 
 	"github.com/spf13/viper"
 )
@@ -61,8 +63,8 @@ func NewProxy(targetHost string) (*httputil.ReverseProxy, error) {
 		modifyRequest(req)
 	}
 
-	/*proxy.ModifyResponse = modifyResponse()
-	proxy.ErrorHandler = errorHandler()*/
+	proxy.ModifyResponse = modifyResponse()
+	/*proxy.ErrorHandler = errorHandler()*/
 	return proxy, nil
 }
 
@@ -75,6 +77,7 @@ func modifyRequest(req *http.Request) {
 	fmt.Println(req.URL)
 
 	/* controllo se i file *.go sono cambiati */
+	/* TODO aggiungere i tipi di file da monitorare e anche le sotto-directory */
 	rebuild := false
 	dir, _ := os.Open(config.Service.Path)
 	dirEntries, _ := dir.ReadDir(0)
@@ -111,7 +114,16 @@ func errorHandler() func(http.ResponseWriter, *http.Request, error) {
 
 func modifyResponse() func(*http.Response) error {
 	return func(resp *http.Response) error {
-		return errors.New("response body is invalid")
+		if resp_build.err != nil {
+			//b, _ := io.ReadAll(resp.Body)
+			buf := bytes.NewBufferString(fmt.Sprintf("<pre>STDERR\n%s</pre>", string(resp_build.bStderr.Bytes())))
+			//buf.Write(b)
+			resp.Body = io.NopCloser(buf)
+			resp.Header["Content-Length"] = []string{fmt.Sprint(buf.Len())}
+		}
+
+		//return errors.New("response body is invalid")
+		return nil
 	}
 }
 
@@ -122,6 +134,14 @@ func ProxyRequestHandler(proxy *httputil.ReverseProxy) func(http.ResponseWriter,
 	}
 }
 
+type respBuild struct {
+	err error
+	bStdout *bytes.Buffer
+	bStderr *bytes.Buffer
+}
+
+var resp_build respBuild
+
 func startApp() {
 	if pid != 0 {
 		/* kill app */
@@ -139,17 +159,22 @@ func startApp() {
 		return
 	}
 
+	resp_build.bStdout = new(bytes.Buffer)
+	resp_build.bStderr = new(bytes.Buffer)
+
 	cmd := &exec.Cmd {
 		Dir: config.Service.Path,
 		Path: goExecPath,
 		Args: []string{goExecPath, "build", "-o", config.Service.Executable, "."},
-		Stdout: os.Stdout,
-		Stderr: os.Stdout,
+		Stdout: resp_build.bStdout,
+		Stderr: resp_build.bStderr,
 	}
 
-	err = cmd.Run()
-	if err != nil {
-		fmt.Println(err)
+	resp_build.err = cmd.Run()
+	if resp_build.err != nil {
+		fmt.Println("ERR BUILD", resp_build.err)
+		fmt.Println("STDOUT", string(resp_build.bStdout.Bytes()))
+		fmt.Println("STDERR", string(resp_build.bStderr.Bytes()))
 	}
 
 	fmt.Println("ESEGUO RUN")
-- 
2.49.0