chore: stop using go:linkname for http.registerOnHitEOF, http.requestBodyRemains (#1275)

relate to https://github.com/MetaCubeX/mihomo/pull/952#issuecomment-2118639385
This commit is contained in:
hunshcn 2024-05-18 20:16:53 +08:00 committed by GitHub
parent 56edd8f671
commit 00e361c5ac
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -8,7 +8,6 @@ import (
"net/http" "net/http"
"strings" "strings"
"sync" "sync"
_ "unsafe"
"github.com/metacubex/mihomo/adapter/inbound" "github.com/metacubex/mihomo/adapter/inbound"
"github.com/metacubex/mihomo/common/lru" "github.com/metacubex/mihomo/common/lru"
@ -18,11 +17,19 @@ import (
"github.com/metacubex/mihomo/log" "github.com/metacubex/mihomo/log"
) )
//go:linkname registerOnHitEOF net/http.registerOnHitEOF type bodyWrapper struct {
func registerOnHitEOF(rc io.ReadCloser, fn func()) io.ReadCloser
once sync.Once
onHitEOF func()
}
//go:linkname requestBodyRemains net/http.requestBodyRemains func (b *bodyWrapper) Read(p []byte) (n int, err error) {
func requestBodyRemains(rc io.ReadCloser) bool n, err = b.ReadCloser.Read(p)
if err == io.EOF && b.onHitEOF != nil {
b.once.Do(b.onHitEOF)
}
return n, err
}
func HandleConn(c net.Conn, tunnel C.Tunnel, cache *lru.LruCache[string, bool], additions ...inbound.Addition) { func HandleConn(c net.Conn, tunnel C.Tunnel, cache *lru.LruCache[string, bool], additions ...inbound.Addition) {
client := newClient(c, tunnel, additions...) client := newClient(c, tunnel, additions...)
@ -100,10 +107,10 @@ func HandleConn(c net.Conn, tunnel C.Tunnel, cache *lru.LruCache[string, bool],
} }
}() }()
} }
if requestBodyRemains(request.Body) { if request.Body == nil || request.Body == http.NoBody {
registerOnHitEOF(request.Body, startBackgroundRead)
} else {
startBackgroundRead() startBackgroundRead()
} else {
request.Body = &bodyWrapper{ReadCloser: request.Body, onHitEOF: startBackgroundRead}
} }
resp, err = client.Do(request) resp, err = client.Do(request)
if err != nil { if err != nil {