Proxy: Fix nil pointer panic in BuildStreamURL and resource leak in ParseBody

1. BuildStreamURL: net.ParseIP() returns nil for non-IP hostnames
   (e.g., "example.com"), then calling nil.To4() panics. Add nil
   check before calling To4().

2. ParseBody: defer r.Close() is placed after the ReadAll error
   check. If ReadAll fails, the function returns early without
   closing r, causing a resource leak. Move defer to the top of
   the function.
This commit is contained in:
shiweikang 2026-04-11 12:43:05 +08:00 committed by Jacob Su
parent 913b773282
commit e124f9f881

View File

@ -69,11 +69,12 @@ func ApiCORS(ctx context.Context, w http.ResponseWriter, r *http.Request) bool {
// ParseBody read the body from r, and unmarshal JSON to v.
func ParseBody(r io.ReadCloser, v interface{}) error {
defer r.Close()
b, err := io.ReadAll(r)
if err != nil {
return errors.Wrapf(err, "read body")
}
defer r.Close()
if len(b) == 0 {
return nil
@ -97,7 +98,7 @@ func BuildStreamURL(r string) (string, error) {
defaultVhost := !strings.Contains(u.Hostname(), ".")
// If hostname is actually an IP address, it's __defaultVhost__.
if ip := net.ParseIP(u.Hostname()); ip.To4() != nil {
if ip := net.ParseIP(u.Hostname()); ip != nil && ip.To4() != nil {
defaultVhost = true
}