From b90b42ac7106aa7e4d1d3203ba7cdc52fbf1fc80 Mon Sep 17 00:00:00 2001 From: Smuu <18609909+Smuu@users.noreply.github.com> Date: Tue, 24 Oct 2023 14:21:49 +0200 Subject: [PATCH] feat: add logging Signed-off-by: Smuu <18609909+Smuu@users.noreply.github.com> --- README.md | 6 +++++- main.go | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 82a341c..70cd774 100644 --- a/README.md +++ b/README.md @@ -1 +1,5 @@ -# autoscale-proxy \ No newline at end of file +# autoscale-proxy + +## ToDo + +- use internal services instead of domain names diff --git a/main.go b/main.go index 75650b6..632183b 100644 --- a/main.go +++ b/main.go @@ -3,10 +3,24 @@ package main import ( "bytes" "io" + "log" "net/http" + "os" "strings" ) +var ( + debugLog *log.Logger + infoLog *log.Logger + errorLog *log.Logger +) + +func init() { + debugLog = log.New(os.Stdout, "DEBUG: ", log.Ldate|log.Ltime|log.Lshortfile) + infoLog = log.New(os.Stdout, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile) + errorLog = log.New(os.Stderr, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile) +} + func replaceDomainInResponse(originalSubdomain, replaceSubdomain, originalDomain string, buffer *bytes.Buffer) { body := buffer.String() fullReplace := replaceSubdomain + "." + "lunaroasis.net" // We know that statescale and snapscale are under this domain @@ -43,8 +57,10 @@ func proxyRequest(fullSubdomain, path string, buffer *bytes.Buffer, r *http.Requ } func handleRequest(w http.ResponseWriter, r *http.Request) { + infoLog.Printf("Received request from %s", r.Host) hostParts := strings.Split(r.Host, ".") if len(hostParts) < 3 { + errorLog.Printf("Invalid domain: %s", r.Host) http.Error(w, "Invalid domain", http.StatusBadRequest) return } @@ -55,9 +71,14 @@ func handleRequest(w http.ResponseWriter, r *http.Request) { buffer := new(bytes.Buffer) backupBuffer := new(bytes.Buffer) + debugLog.Printf("Proxying request to %s", subdomain+".statescale") statusCode, headers, err := proxyRequest(subdomain+".statescale", r.RequestURI, buffer, r) + debugLog.Printf("Received status code %d", statusCode) if err != nil || statusCode >= 400 { + debugLog.Printf("Proxying request to %s", subdomain+".snapscale") backupStatusCode, backupHeaders, _ := proxyRequest(subdomain+".snapscale", r.RequestURI, backupBuffer, r) + debugLog.Printf("Received status code %d", backupStatusCode) + replaceDomainInResponse(subdomain, subdomain+".snapscale", originalDomain, backupBuffer) for key, value := range backupHeaders { @@ -77,6 +98,7 @@ func handleRequest(w http.ResponseWriter, r *http.Request) { } func main() { + infoLog.Println("Starting server on :8080") http.HandleFunc("/", handleRequest) http.ListenAndServe(":8080", nil) }