2024-07-23 10:11:43 +08:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2024-07-25 14:43:41 +08:00
|
|
|
"context"
|
2024-07-29 14:13:47 +08:00
|
|
|
"fmt"
|
2024-07-25 14:43:41 +08:00
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"net/http/httputil"
|
2024-07-29 14:13:47 +08:00
|
|
|
"net/url"
|
2024-07-25 14:43:41 +08:00
|
|
|
"os"
|
2024-07-23 10:11:43 +08:00
|
|
|
"strings"
|
|
|
|
|
2024-07-25 18:13:57 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/core/app/api/v1/helper"
|
|
|
|
"github.com/1Panel-dev/1Panel/core/constant"
|
2024-07-23 10:11:43 +08:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
)
|
|
|
|
|
|
|
|
func Proxy() gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
2024-07-25 14:43:41 +08:00
|
|
|
if strings.HasPrefix(c.Request.URL.Path, "/api/v2/core") {
|
2024-07-23 10:11:43 +08:00
|
|
|
c.Next()
|
|
|
|
return
|
|
|
|
}
|
2024-07-29 14:13:47 +08:00
|
|
|
currentNode := c.Request.Header.Get("CurrentNode")
|
|
|
|
if currentNode == "127.0.0.1" {
|
|
|
|
sockPath := "/tmp/agent.sock"
|
|
|
|
if _, err := os.Stat(sockPath); err != nil {
|
|
|
|
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrProxy, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
dialUnix := func() (conn net.Conn, err error) {
|
|
|
|
return net.Dial("unix", sockPath)
|
|
|
|
}
|
|
|
|
transport := &http.Transport{
|
|
|
|
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
|
|
return dialUnix()
|
|
|
|
},
|
|
|
|
}
|
|
|
|
proxy := &httputil.ReverseProxy{
|
|
|
|
Director: func(req *http.Request) {
|
|
|
|
req.URL.Scheme = "http"
|
|
|
|
req.URL.Host = "unix"
|
|
|
|
},
|
|
|
|
Transport: transport,
|
|
|
|
}
|
|
|
|
proxy.ServeHTTP(c.Writer, c.Request)
|
|
|
|
c.Abort()
|
2024-07-25 18:13:57 +08:00
|
|
|
return
|
|
|
|
}
|
2024-07-29 14:13:47 +08:00
|
|
|
target, err := url.Parse(fmt.Sprintf("http://%s:9999", currentNode))
|
|
|
|
if err != nil {
|
|
|
|
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrProxy, err)
|
|
|
|
return
|
2024-07-25 18:13:57 +08:00
|
|
|
}
|
2024-07-29 14:13:47 +08:00
|
|
|
proxy := httputil.NewSingleHostReverseProxy(target)
|
|
|
|
c.Request.Host = target.Host
|
|
|
|
c.Request.URL.Scheme = target.Scheme
|
|
|
|
c.Request.URL.Host = target.Host
|
2024-07-25 18:13:57 +08:00
|
|
|
proxy.ServeHTTP(c.Writer, c.Request)
|
|
|
|
c.Abort()
|
2024-07-23 10:11:43 +08:00
|
|
|
}
|
|
|
|
}
|