feat: Enhance proxy initialization and error handling

* Add a timeout to the dialer for Unix socket connections
* Improve error response by including the error message in the "Bad Gateway" response
This commit is contained in:
HynoR 2025-12-04 13:19:51 +08:00
parent 5d2084fda4
commit 3a00bcb5b3
2 changed files with 5 additions and 8 deletions

View file

@ -15,8 +15,11 @@ var (
)
func Init() {
dialer := &net.Dialer{
Timeout: 5 * time.Second,
}
dialUnix := func(ctx context.Context, network, addr string) (net.Conn, error) {
return net.Dial("unix", sockPath)
return dialer.DialContext(ctx, "unix", sockPath)
}
transport := &http.Transport{
DialContext: dialUnix,
@ -33,7 +36,7 @@ func Init() {
Transport: transport,
ErrorHandler: func(rw http.ResponseWriter, req *http.Request, err error) {
rw.WriteHeader(http.StatusBadGateway)
rw.Write([]byte("Bad Gateway"))
_, _ = rw.Write([]byte("Bad Gateway: " + err.Error()))
},
}
}

View file

@ -3,7 +3,6 @@ package router
import (
"net/http"
"net/url"
"os"
"strconv"
"strings"
@ -52,11 +51,6 @@ func Proxy() gin.HandlerFunc {
}
if !strings.HasPrefix(c.Request.URL.Path, "/api/v2/core") && (currentNode == "local" || len(currentNode) == 0) {
sockPath := "/etc/1panel/agent.sock"
if _, err := os.Stat(sockPath); err != nil {
helper.ErrorWithDetail(c, http.StatusBadRequest, "ErrProxy", err)
return
}
defer func() {
if err := recover(); err != nil && err != http.ErrAbortHandler {
global.LOG.Debug(err)