podterminal/web/reverseProxy.go

106 lines
2.3 KiB
Go
Raw Normal View History

2024-01-30 16:45:03 +01:00
package web
import (
"fmt"
"log"
"net/http/httputil"
"net/url"
"time"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"git.jmbit.de/jmb/podterminal/pods"
)
func createReverseProxy(backendService string) (*httputil.ReverseProxy, error) {
var err error
log.Println("Creating reverse Proxy for ", backendService)
backendURL, err := url.Parse(backendService)
if err != nil {
log.Printf("Could not parse backend URL: %v", err)
}
proxy := &httputil.ReverseProxy{
Rewrite: func(request *httputil.ProxyRequest) {
request.SetURL(backendURL)
request.Out.Host = request.In.Host
},
}
return proxy, err
}
func containerProxy(c *gin.Context) {
session := sessions.Default(c)
session.Save()
sessionID := sessions.Session.ID(session)
2024-01-30 16:45:03 +01:00
if session.Get("ct") == nil {
log.Println("Creating Container for Session ", sessionID)
ct, err := pods.CreateContainer()
session.Set("ct", ct)
session.Save()
2024-01-30 16:45:03 +01:00
if err != nil {
c.HTML(500, "Error", fmt.Sprintf("[%s] Could not create Container: %v", sessionID, err))
session.Delete("ct")
session.Save()
2024-01-30 16:45:03 +01:00
c.Abort()
}
err = pods.StartContainer(ct)
if err != nil {
c.HTML(500, "Error", fmt.Sprintf("[%s] Could not start Container: %v", sessionID, err))
session.Delete("ct")
session.Save()
2024-01-30 16:45:03 +01:00
c.Abort()
}
2024-01-30 16:45:03 +01:00
ctip, err := pods.GetContainerIP(ct)
if err != nil {
c.HTML(500, "Error", fmt.Sprintf("[%s] Could not get Container ip: %v", sessionID, err))
session.Delete("ct")
session.Save()
2024-01-30 16:45:03 +01:00
c.Abort()
}
2024-01-31 13:12:43 +01:00
// Soft fail Skel
2024-02-01 17:32:46 +01:00
// _ = pods.CopySkelToContainer(ct)
2024-01-30 16:45:03 +01:00
proxies[ct], err = createReverseProxy(fmt.Sprintf("http://%s:3000", ctip))
if err != nil {
c.HTML(
500,
"Error",
fmt.Sprintf("[%s] Could not create Container Proxy: %v", sessionID, err),
)
session.Delete("ct")
session.Save()
2024-01-30 16:45:03 +01:00
c.Abort()
}
session.Set("ready", true)
2024-01-30 16:45:03 +01:00
session.Save()
c.Redirect(301, "/")
} else {
sessionCT := session.Get("ct")
switch sessionCT.(type) {
case string:
default:
c.HTML(500, "Error", "Session Container ID is not a string")
session.Delete("ct")
session.Save()
2024-01-30 16:45:03 +01:00
c.Abort()
}
if session.Get("ready") == nil {
time.Sleep(100 * time.Millisecond)
c.Redirect(301, "/")
}
2024-01-30 16:45:03 +01:00
id := session.Get("ct").(string)
proxy := proxies[id]
proxy.ServeHTTP(c.Writer, c.Request)
}
}