mirror of
https://github.com/sipeed/picoclaw.git
synced 2026-06-12 18:08:54 +00:00
c513ad22d7
- move chat controller, state, protocol, history, and websocket logic into a dedicated chat feature module - improve chat reconnection, session hydration, and send gating based on actual websocket state - preserve gateway status during transient SSE disconnects and update stop state immediately - generate wss websocket URLs behind HTTPS proxies and add backend tests for forwarded proto handling
85 lines
1.7 KiB
Go
85 lines
1.7 KiB
Go
package api
|
|
|
|
import (
|
|
"net"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/sipeed/picoclaw/pkg/config"
|
|
)
|
|
|
|
func (h *Handler) effectiveLauncherPublic() bool {
|
|
if h.serverPublicExplicit {
|
|
return h.serverPublic
|
|
}
|
|
|
|
cfg, err := h.loadLauncherConfig()
|
|
if err == nil {
|
|
return cfg.Public
|
|
}
|
|
|
|
return h.serverPublic
|
|
}
|
|
|
|
func (h *Handler) gatewayHostOverride() string {
|
|
if h.effectiveLauncherPublic() {
|
|
return "0.0.0.0"
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func (h *Handler) effectiveGatewayBindHost(cfg *config.Config) string {
|
|
if override := h.gatewayHostOverride(); override != "" {
|
|
return override
|
|
}
|
|
if cfg == nil {
|
|
return ""
|
|
}
|
|
return strings.TrimSpace(cfg.Gateway.Host)
|
|
}
|
|
|
|
func gatewayProbeHost(bindHost string) string {
|
|
if bindHost == "" || bindHost == "0.0.0.0" {
|
|
return "127.0.0.1"
|
|
}
|
|
return bindHost
|
|
}
|
|
|
|
func requestHostName(r *http.Request) string {
|
|
reqHost, _, err := net.SplitHostPort(r.Host)
|
|
if err == nil {
|
|
return reqHost
|
|
}
|
|
if strings.TrimSpace(r.Host) != "" {
|
|
return r.Host
|
|
}
|
|
return "127.0.0.1"
|
|
}
|
|
|
|
func requestWSScheme(r *http.Request) string {
|
|
if forwarded := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")); forwarded != "" {
|
|
proto := strings.ToLower(strings.TrimSpace(strings.Split(forwarded, ",")[0]))
|
|
if proto == "https" || proto == "wss" {
|
|
return "wss"
|
|
}
|
|
if proto == "http" || proto == "ws" {
|
|
return "ws"
|
|
}
|
|
}
|
|
|
|
if r.TLS != nil {
|
|
return "wss"
|
|
}
|
|
|
|
return "ws"
|
|
}
|
|
|
|
func (h *Handler) buildWsURL(r *http.Request, cfg *config.Config) string {
|
|
host := h.effectiveGatewayBindHost(cfg)
|
|
if host == "" || host == "0.0.0.0" {
|
|
host = requestHostName(r)
|
|
}
|
|
return requestWSScheme(r) + "://" + net.JoinHostPort(host, strconv.Itoa(cfg.Gateway.Port)) + "/pico/ws"
|
|
}
|