speedtest

package
v1.7.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 9, 2024 License: MIT Imports: 24 Imported by: 59

Documentation

Index

Constants

View Source
const (
	UnitTypeDecimalBits  = UnitType(iota) // auto scaled
	UnitTypeDecimalBytes                  // auto scaled
	UnitTypeBinaryBits                    // auto scaled
	UnitTypeBinaryBytes                   // auto scaled
	UnitTypeDefaultMbps                   // fixed
)

IEC and SI

View Source
const (
	B  = 1.0
	KB = 1000 * B
	MB = 1000 * KB
	GB = 1000 * MB

	IB  = 1
	KiB = 1024 * IB
	MiB = 1024 * KiB
	GiB = 1024 * MiB
)
View Source
const PingTimeout = -1

Variables

View Source
var (
	DecimalBitsUnits  = []string{"bps", "Kbps", "Mbps", "Gbps"}
	DecimalBytesUnits = []string{"B/s", "KB/s", "MB/s", "GB/s"}
	BinaryBitsUnits   = []string{"Kibps", "KiMbps", "KiGbps"}
	BinaryBytesUnits  = []string{"KiB/s", "MiB/s", "GiB/s"}
)
View Source
var (
	DefaultUserAgent = fmt.Sprintf("showwin/speedtest-go %s", version)
)
View Source
var (
	ErrConnectTimeout = errors.New("server connect timeout")
)
View Source
var (
	ErrServerNotFound = errors.New("no server available or found")
)
View Source
var (
	ErrorUninitializedManager = errors.New("uninitialized manager")
)
View Source
var Locations = map[string]*Location{
	"brasilia":     {"brasilia", "br", -15.793876, -47.8835327},
	"hongkong":     {"hongkong", "hk", 22.3106806, 114.1700546},
	"tokyo":        {"tokyo", "jp", 35.680938, 139.7674114},
	"london":       {"london", "uk", 51.5072493, -0.1288861},
	"moscow":       {"moscow", "ru", 55.7497248, 37.615989},
	"beijing":      {"beijing", "cn", 39.8721243, 116.4077473},
	"paris":        {"paris", "fr", 48.8626026, 2.3477229},
	"sanfrancisco": {"sanfrancisco", "us", 37.7540028, -122.4429967},
	"newyork":      {"newyork", "us", 40.7200876, -74.0220945},
	"yishun":       {"yishun", "sg", 1.4230218, 103.8404728},
	"delhi":        {"delhi", "in", 28.6251287, 77.1960896},
	"monterrey":    {"monterrey", "mx", 25.6881435, -100.3073485},
	"berlin":       {"berlin", "de", 52.5168128, 13.4009469},
	"maputo":       {"maputo", "mz", -25.9579267, 32.5760444},
	"honolulu":     {"honolulu", "us", 20.8247065, -156.918706},
	"seoul":        {"seoul", "kr", 37.6086268, 126.7179721},
	"osaka":        {"osaka", "jp", 34.6952743, 135.5006967},
	"shanghai":     {"shanghai", "cn", 31.2292105, 121.4661666},
	"urumqi":       {"urumqi", "cn", 43.8256624, 87.6058564},
	"ottawa":       {"ottawa", "ca", 45.4161836, -75.7035467},
	"capetown":     {"capetown", "za", -33.9391993, 18.4316716},
	"sydney":       {"sydney", "au", -33.8966622, 151.1731861},
	"perth":        {"perth", "au", -31.9551812, 115.8591904},
	"warsaw":       {"warsaw", "pl", 52.2396659, 21.0129345},
	"kampala":      {"kampala", "ug", 0.3070027, 32.5675581},
	"bangkok":      {"bangkok", "th", 13.7248936, 100.493026},
}

Locations TODO more location need to added

Functions

func PrintCityList added in v1.2.0

func PrintCityList()

func SetUnit added in v1.7.0

func SetUnit(unit UnitType)

SetUnit Set global output units

func StandardDeviation added in v1.6.7

func StandardDeviation(vector []int64) (mean, variance, stdDev, min, max int64)

func Version added in v1.3.0

func Version() string

Types

type ByDistance

type ByDistance struct {
	Servers
}

ByDistance for sorting servers.

func (ByDistance) Less

func (b ByDistance) Less(i, j int) bool

Less compares the distance. For sorting servers.

type ByteRate added in v1.7.0

type ByteRate float64

func (ByteRate) Byte added in v1.7.0

func (r ByteRate) Byte(formatType UnitType) string

Byte Specifies the format output byte rate

func (ByteRate) Gbps added in v1.7.4

func (r ByteRate) Gbps() float64

func (ByteRate) Mbps added in v1.7.4

func (r ByteRate) Mbps() float64

func (ByteRate) String added in v1.7.0

func (r ByteRate) String() string

type Chunk added in v1.4.0

type Chunk interface {
	UploadHandler(size int64) Chunk
	DownloadHandler(r io.Reader) error

	GetRate() float64
	GetDuration() time.Duration
	GetParent() Manager

	Read(b []byte) (n int, err error)
}

type DataChunk added in v1.4.0

type DataChunk struct {
	ContentLength int64
	// contains filtered or unexported fields
}

func (*DataChunk) DownloadHandler added in v1.4.0

func (dc *DataChunk) DownloadHandler(r io.Reader) error

DownloadHandler No value will be returned here, because the error will interrupt the test. The error chunk is generally caused by the remote server actively closing the connection.

func (*DataChunk) GetDuration added in v1.4.0

func (dc *DataChunk) GetDuration() time.Duration

func (*DataChunk) GetParent added in v1.4.0

func (dc *DataChunk) GetParent() Manager

func (*DataChunk) GetRate added in v1.4.0

func (dc *DataChunk) GetRate() float64

func (*DataChunk) Read added in v1.4.0

func (dc *DataChunk) Read(b []byte) (n int, err error)

func (*DataChunk) UploadHandler added in v1.4.0

func (dc *DataChunk) UploadHandler(size int64) Chunk

type DataManager added in v1.4.0

type DataManager struct {
	SnapshotStore *Snapshots
	Snapshot      *Snapshot
	sync.Mutex
	// contains filtered or unexported fields
}

func NewDataManager added in v1.4.0

func NewDataManager() *DataManager

func (*DataManager) AddTotalDownload added in v1.4.0

func (dm *DataManager) AddTotalDownload(value int64)

func (*DataManager) AddTotalUpload added in v1.4.0

func (dm *DataManager) AddTotalUpload(value int64)

func (*DataManager) GetAvgDownloadRate added in v1.4.0

func (dm *DataManager) GetAvgDownloadRate() float64

func (*DataManager) GetAvgUploadRate added in v1.4.0

func (dm *DataManager) GetAvgUploadRate() float64

func (*DataManager) GetEWMADownloadRate added in v1.7.0

func (dm *DataManager) GetEWMADownloadRate() float64

func (*DataManager) GetEWMAUploadRate added in v1.7.0

func (dm *DataManager) GetEWMAUploadRate() float64

func (*DataManager) GetTotalDownload added in v1.4.0

func (dm *DataManager) GetTotalDownload() int64

func (*DataManager) GetTotalUpload added in v1.4.0

func (dm *DataManager) GetTotalUpload() int64

func (*DataManager) NewChunk added in v1.4.0

func (dm *DataManager) NewChunk() Chunk

func (*DataManager) NewDataDirection added in v1.7.0

func (dm *DataManager) NewDataDirection(testType int) *TestDirection

func (*DataManager) RegisterDownloadHandler added in v1.5.0

func (dm *DataManager) RegisterDownloadHandler(fn func()) *TestDirection

func (*DataManager) RegisterUploadHandler added in v1.5.0

func (dm *DataManager) RegisterUploadHandler(fn func()) *TestDirection

func (*DataManager) Reset added in v1.4.0

func (dm *DataManager) Reset()

func (*DataManager) SetCallbackDownload added in v1.7.0

func (dm *DataManager) SetCallbackDownload(callback func(downRate ByteRate))

func (*DataManager) SetCallbackUpload added in v1.7.0

func (dm *DataManager) SetCallbackUpload(callback func(upRate ByteRate))

func (*DataManager) SetCaptureTime added in v1.4.0

func (dm *DataManager) SetCaptureTime(duration time.Duration) Manager

func (*DataManager) SetNThread added in v1.4.0

func (dm *DataManager) SetNThread(n int) Manager

func (*DataManager) SetRateCaptureFrequency added in v1.4.0

func (dm *DataManager) SetRateCaptureFrequency(duration time.Duration) Manager

func (*DataManager) Snapshots added in v1.6.7

func (dm *DataManager) Snapshots() *Snapshots

func (*DataManager) Wait added in v1.4.0

func (dm *DataManager) Wait()

type DataType added in v1.4.0

type DataType int32

type Debug added in v1.5.1

type Debug struct {
	// contains filtered or unexported fields
}

func NewDebug added in v1.5.1

func NewDebug() *Debug

func (*Debug) Enable added in v1.5.1

func (d *Debug) Enable()

func (*Debug) Printf added in v1.5.1

func (d *Debug) Printf(format string, v ...any)

func (*Debug) Println added in v1.5.1

func (d *Debug) Println(v ...any)

type Location added in v1.2.0

type Location struct {
	Name string
	CC   string
	Lat  float64
	Lon  float64
}

func GetLocation added in v1.5.1

func GetLocation(locationName string) (*Location, error)

func NewLocation added in v1.5.1

func NewLocation(locationName string, latitude float64, longitude float64) *Location

NewLocation new a Location

func ParseLocation added in v1.5.1

func ParseLocation(locationName string, coordinateStr string) (*Location, error)

ParseLocation parse latitude and longitude string

func (*Location) String added in v1.5.1

func (l *Location) String() string

type Manager added in v1.4.0

type Manager interface {
	SetRateCaptureFrequency(duration time.Duration) Manager
	SetCaptureTime(duration time.Duration) Manager

	NewChunk() Chunk

	GetTotalDownload() int64
	GetTotalUpload() int64
	AddTotalDownload(value int64)
	AddTotalUpload(value int64)

	GetAvgDownloadRate() float64
	GetAvgUploadRate() float64

	GetEWMADownloadRate() float64
	GetEWMAUploadRate() float64

	SetCallbackDownload(callback func(downRate ByteRate))
	SetCallbackUpload(callback func(upRate ByteRate))

	RegisterDownloadHandler(fn func()) *TestDirection
	RegisterUploadHandler(fn func()) *TestDirection

	// Wait for the upload or download task to end to avoid errors caused by core occupation
	Wait()
	Reset()
	Snapshots() *Snapshots

	SetNThread(n int) Manager
}

type Option added in v1.1.5

type Option func(*Speedtest)

Option is a function that can be passed to New to modify the Client.

func WithDoer added in v1.1.5

func WithDoer(doer *http.Client) Option

WithDoer sets the http.Client used to make requests.

func WithUserConfig added in v1.4.0

func WithUserConfig(userConfig *UserConfig) Option

WithUserConfig adds a custom user config for speedtest. This configuration may be overwritten again by WithDoer, because client and transport are parent-child relationship: `New(WithDoer(myDoer), WithUserAgent(myUserAgent), WithDoer(myDoer))`

type PacketLossAnalyzer added in v1.7.1

type PacketLossAnalyzer struct {
	// contains filtered or unexported fields
}

func NewPacketLossAnalyzer added in v1.7.1

func NewPacketLossAnalyzer(options *PacketLossAnalyzerOptions) *PacketLossAnalyzer

func (*PacketLossAnalyzer) Run added in v1.7.1

func (pla *PacketLossAnalyzer) Run(host string, callback func(packetLoss *transport.PLoss)) error

func (*PacketLossAnalyzer) RunMulti added in v1.7.4

func (pla *PacketLossAnalyzer) RunMulti(hosts []string) (float64, error)

RunMulti Mix all servers to get the average packet loss.

func (*PacketLossAnalyzer) RunMultiWithContext added in v1.7.4

func (pla *PacketLossAnalyzer) RunMultiWithContext(ctx context.Context, hosts []string) (float64, error)

func (*PacketLossAnalyzer) RunWithContext added in v1.7.1

func (pla *PacketLossAnalyzer) RunWithContext(ctx context.Context, host string, callback func(packetLoss *transport.PLoss)) error

type PacketLossAnalyzerOptions added in v1.7.1

type PacketLossAnalyzerOptions struct {
	RemoteSamplingInterval time.Duration
	SamplingDuration       time.Duration
	PacketSendingInterval  time.Duration
	PacketSendingTimeout   time.Duration
	SourceInterface        string      // source interface
	TCPDialer              *net.Dialer // tcp dialer for sampling
	UDPDialer              *net.Dialer // udp dialer for sending packet

}

type Proto added in v1.6.7

type Proto int
const (
	HTTP Proto = iota
	TCP
	ICMP
)

type Server

type Server struct {
	URL          string          `xml:"url,attr" json:"url"`
	Lat          string          `xml:"lat,attr" json:"lat"`
	Lon          string          `xml:"lon,attr" json:"lon"`
	Name         string          `xml:"name,attr" json:"name"`
	Country      string          `xml:"country,attr" json:"country"`
	Sponsor      string          `xml:"sponsor,attr" json:"sponsor"`
	ID           string          `xml:"id,attr" json:"id"`
	Host         string          `xml:"host,attr" json:"host"`
	Distance     float64         `json:"distance"`
	Latency      time.Duration   `json:"latency"`
	MaxLatency   time.Duration   `json:"max_latency"`
	MinLatency   time.Duration   `json:"min_latency"`
	Jitter       time.Duration   `json:"jitter"`
	DLSpeed      ByteRate        `json:"dl_speed"`
	ULSpeed      ByteRate        `json:"ul_speed"`
	TestDuration TestDuration    `json:"test_duration"`
	PacketLoss   transport.PLoss `json:"packet_loss"`

	Context *Speedtest `json:"-"`
}

Server information

func CustomServer added in v1.4.0

func CustomServer(host string) (*Server, error)

CustomServer use defaultClient, given a URL string, return a new Server object, with as much filled in as we can

func FetchServerByID added in v1.6.3

func FetchServerByID(serverID string) (*Server, error)

FetchServerByID retrieves a server by given serverID.

func (*Server) CheckResultValid

func (s *Server) CheckResultValid() bool

CheckResultValid checks that results are logical given UL and DL speeds

func (*Server) DownloadTest

func (s *Server) DownloadTest() error

DownloadTest executes the test to measure download speed

func (*Server) DownloadTestContext added in v1.1.3

func (s *Server) DownloadTestContext(ctx context.Context) error

DownloadTestContext executes the test to measure download speed, observing the given context.

func (*Server) HTTPPing added in v1.4.2

func (s *Server) HTTPPing(
	ctx context.Context,
	echoTimes int,
	echoFreq time.Duration,
	callback func(latency time.Duration),
) (latencies []int64, err error)

func (*Server) ICMPPing added in v1.4.2

func (s *Server) ICMPPing(
	ctx context.Context,
	readTimeout time.Duration,
	echoTimes int,
	echoFreq time.Duration,
	callback func(latency time.Duration),
) (latencies []int64, err error)

ICMPPing privileged method

func (*Server) MultiDownloadTestContext added in v1.5.0

func (s *Server) MultiDownloadTestContext(ctx context.Context, servers Servers) error

func (*Server) MultiUploadTestContext added in v1.5.0

func (s *Server) MultiUploadTestContext(ctx context.Context, servers Servers) error

func (*Server) PingTest

func (s *Server) PingTest(callback func(latency time.Duration)) error

PingTest executes test to measure latency

func (*Server) PingTestContext added in v1.1.3

func (s *Server) PingTestContext(ctx context.Context, callback func(latency time.Duration)) (err error)

PingTestContext executes test to measure latency, observing the given context.

func (*Server) String

func (s *Server) String() string

String representation of Server

func (*Server) TCPPing added in v1.6.7

func (s *Server) TCPPing(
	ctx context.Context,
	echoTimes int,
	echoFreq time.Duration,
	callback func(latency time.Duration),
) (latencies []int64, err error)

func (*Server) TestAll added in v1.6.3

func (s *Server) TestAll() error

TestAll executes ping, download and upload tests one by one

func (*Server) UploadTest

func (s *Server) UploadTest() error

UploadTest executes the test to measure upload speed

func (*Server) UploadTestContext added in v1.1.3

func (s *Server) UploadTestContext(ctx context.Context) error

UploadTestContext executes the test to measure upload speed, observing the given context.

type ServerList

type ServerList struct {
	Servers []*Server `xml:"servers>server"`
	Users   []User    `xml:"client"`
}

ServerList list of Server Users(Client) also exists with @param speedTestServersAdvanced

func (ServerList) String

func (servers ServerList) String() string

String representation of ServerList

type Servers

type Servers []*Server

Servers for sorting servers.

func FetchServerListContext added in v1.1.3

func FetchServerListContext(ctx context.Context) (Servers, error)

FetchServerListContext retrieves a list of available servers, observing the given context.

func FetchServers added in v1.1.5

func FetchServers() (Servers, error)

FetchServers retrieves a list of available servers

func (Servers) Available added in v1.5.0

func (servers Servers) Available() *Servers

func (Servers) FindServer added in v1.1.5

func (servers Servers) FindServer(serverID []int) (Servers, error)

FindServer finds server by serverID in given server list. If the id is not found in the given list, return the server with the lowest latency.

func (Servers) Hosts added in v1.7.5

func (servers Servers) Hosts() []string

Hosts return hosts of servers

func (Servers) Len

func (servers Servers) Len() int

Len finds length of servers. For sorting servers.

func (Servers) String added in v1.1.5

func (servers Servers) String() string

String representation of Servers

func (Servers) Swap

func (servers Servers) Swap(i, j int)

Swap swaps i-th and j-th. For sorting servers.

type Snapshot added in v1.6.7

type Snapshot []*DataChunk

type Snapshots added in v1.6.7

type Snapshots struct {
	// contains filtered or unexported fields
}

func (*Snapshots) All added in v1.6.7

func (rs *Snapshots) All() []*Snapshot

func (*Snapshots) Clean added in v1.6.7

func (rs *Snapshots) Clean()

func (*Snapshots) Latest added in v1.6.7

func (rs *Snapshots) Latest() *Snapshot

type Speedtest added in v1.1.5

type Speedtest struct {
	User *User
	Manager
	// contains filtered or unexported fields
}

Speedtest is a speedtest client.

func New added in v1.1.5

func New(opts ...Option) *Speedtest

New creates a new speedtest client.

func (*Speedtest) CustomServer added in v1.4.0

func (s *Speedtest) CustomServer(host string) (*Server, error)

CustomServer given a URL string, return a new Server object, with as much filled in as we can

func (*Speedtest) FetchServerByID added in v1.6.3

func (s *Speedtest) FetchServerByID(serverID string) (*Server, error)

FetchServerByID retrieves a server by given serverID.

func (*Speedtest) FetchServerByIDContext added in v1.6.3

func (s *Speedtest) FetchServerByIDContext(ctx context.Context, serverID string) (*Server, error)

FetchServerByIDContext retrieves a server by given serverID, observing the given context.

func (*Speedtest) FetchServerListContext added in v1.1.5

func (s *Speedtest) FetchServerListContext(ctx context.Context) (Servers, error)

FetchServerListContext retrieves a list of available servers, observing the given context.

func (*Speedtest) FetchServers added in v1.1.5

func (s *Speedtest) FetchServers() (Servers, error)

FetchServers retrieves a list of available servers

func (*Speedtest) FetchUserInfo added in v1.1.5

func (s *Speedtest) FetchUserInfo() (*User, error)

FetchUserInfo returns information about caller determined by speedtest.net

func (*Speedtest) FetchUserInfoContext added in v1.1.5

func (s *Speedtest) FetchUserInfoContext(ctx context.Context) (*User, error)

FetchUserInfoContext returns information about caller determined by speedtest.net, observing the given context.

func (*Speedtest) JSON added in v1.6.0

func (s *Speedtest) JSON(servers Servers) ([]byte, error)

func (*Speedtest) NewUserConfig added in v1.4.0

func (s *Speedtest) NewUserConfig(uc *UserConfig)

func (*Speedtest) RoundTrip added in v1.4.0

func (s *Speedtest) RoundTrip(req *http.Request) (*http.Response, error)

type TestDirection added in v1.7.0

type TestDirection struct {
	TestType int // test type

	RateSequence []int64 // rate history sequence
	// contains filtered or unexported fields
}

func (TestDirection) Add added in v1.7.0

func (f TestDirection) Add(fn func())

func (*TestDirection) Start added in v1.7.0

func (td *TestDirection) Start(cancel context.CancelFunc, mainRequestHandlerIndex int)

type TestDuration added in v1.6.3

type TestDuration struct {
	Ping     *time.Duration `json:"ping"`
	Download *time.Duration `json:"download"`
	Upload   *time.Duration `json:"upload"`
	Total    *time.Duration `json:"total"`
}

type UnitType added in v1.7.0

type UnitType int

type User

type User struct {
	IP  string `xml:"ip,attr"`
	Lat string `xml:"lat,attr"`
	Lon string `xml:"lon,attr"`
	Isp string `xml:"isp,attr"`
}

User represents information determined about the caller by speedtest.net

func FetchUserInfo

func FetchUserInfo() (*User, error)

FetchUserInfo returns information about caller determined by speedtest.net

func FetchUserInfoContext added in v1.1.3

func FetchUserInfoContext(ctx context.Context) (*User, error)

FetchUserInfoContext returns information about caller determined by speedtest.net, observing the given context.

func (*User) String

func (u *User) String() string

String representation of User

type UserConfig added in v1.4.0

type UserConfig struct {
	T             *http.Transport
	UserAgent     string
	Proxy         string
	Source        string
	DnsBindSource bool
	DialerControl func(network, address string, c syscall.RawConn) error
	Debug         bool
	PingMode      Proto

	SavingMode     bool
	MaxConnections int

	CityFlag     string
	LocationFlag string
	Location     *Location

	Keyword string // Fuzzy search
}

type Users

type Users struct {
	Users []User `xml:"client"`
}

Users for decode xml

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL