1
0

Feature: add meanDelay on URLTest

This commit is contained in:
Dreamacro 2023-02-27 19:13:26 +08:00
parent 8173d6681b
commit f78a7cb2cb
3 changed files with 19 additions and 8 deletions

View File

@ -101,12 +101,13 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
// URLTest get the delay for the specified URL // URLTest get the delay for the specified URL
// implements C.Proxy // implements C.Proxy
func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) { func (p *Proxy) URLTest(ctx context.Context, url string) (delay, meanDelay uint16, err error) {
defer func() { defer func() {
p.alive.Store(err == nil) p.alive.Store(err == nil)
record := C.DelayHistory{Time: time.Now()} record := C.DelayHistory{Time: time.Now()}
if err == nil { if err == nil {
record.Delay = t record.Delay = delay
record.MeanDelay = meanDelay
} }
p.history.Put(record) p.history.Put(record)
if p.history.Len() > 10 { if p.history.Len() > 10 {
@ -156,7 +157,15 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
return return
} }
resp.Body.Close() resp.Body.Close()
t = uint16(time.Since(start) / time.Millisecond) delay = uint16(time.Since(start) / time.Millisecond)
resp, err = client.Do(req)
if err != nil {
return
}
resp.Body.Close()
meanDelay = uint16(time.Since(start) / time.Millisecond / 2)
return return
} }

View File

@ -101,8 +101,9 @@ type ProxyAdapter interface {
} }
type DelayHistory struct { type DelayHistory struct {
Time time.Time `json:"time"` Time time.Time `json:"time"`
Delay uint16 `json:"delay"` Delay uint16 `json:"delay"`
MeanDelay uint16 `json:"meanDelay"`
} }
type Proxy interface { type Proxy interface {
@ -110,7 +111,7 @@ type Proxy interface {
Alive() bool Alive() bool
DelayHistory() []DelayHistory DelayHistory() []DelayHistory
LastDelay() uint16 LastDelay() uint16
URLTest(ctx context.Context, url string) (uint16, error) URLTest(ctx context.Context, url string) (uint16, uint16, error)
// Deprecated: use DialContext instead. // Deprecated: use DialContext instead.
Dial(metadata *Metadata) (Conn, error) Dial(metadata *Metadata) (Conn, error)

View File

@ -109,7 +109,7 @@ func getProxyDelay(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout)) ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout))
defer cancel() defer cancel()
delay, err := proxy.URLTest(ctx, url) delay, meanDelay, err := proxy.URLTest(ctx, url)
if ctx.Err() != nil { if ctx.Err() != nil {
render.Status(r, http.StatusGatewayTimeout) render.Status(r, http.StatusGatewayTimeout)
render.JSON(w, r, ErrRequestTimeout) render.JSON(w, r, ErrRequestTimeout)
@ -123,6 +123,7 @@ func getProxyDelay(w http.ResponseWriter, r *http.Request) {
} }
render.JSON(w, r, render.M{ render.JSON(w, r, render.M{
"delay": delay, "delay": delay,
"meanDelay": meanDelay,
}) })
} }