Skip to content

Commit

Permalink
feat: add logging
Browse files Browse the repository at this point in the history
Signed-off-by: Smuu <18609909+Smuu@users.noreply.github.com>
  • Loading branch information
smuu committed Oct 24, 2023
1 parent b067ff6 commit b90b42a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
# autoscale-proxy
# autoscale-proxy

## ToDo

- use internal services instead of domain names
22 changes: 22 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand All @@ -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 {
Expand All @@ -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)
}

0 comments on commit b90b42a

Please sign in to comment.