speedtest

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 21, 2023 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const PingTimeout = -1

Variables

View Source
var (
	DefaultUserAgent = fmt.Sprintf("SantiiRepair/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 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

func PrintCityList()

func StandardDeviation

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

func Version

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 Chunk

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

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

func (*DataChunk) DownloadHandler

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

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

func (*DataChunk) GetParent

func (dc *DataChunk) GetParent() Manager

func (*DataChunk) GetRate

func (dc *DataChunk) GetRate() float64

func (*DataChunk) Read

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

func (*DataChunk) UploadHandler

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

type DataManager

type DataManager struct {
	DownloadRateSequence []int64
	UploadRateSequence   []int64

	SnapshotStore *Snapshots
	Snapshot      *Snapshot
	sync.Mutex
	// contains filtered or unexported fields
}

func NewDataManager

func NewDataManager() *DataManager

func (*DataManager) AddTotalDownload

func (dm *DataManager) AddTotalDownload(value int64)

func (*DataManager) AddTotalUpload

func (dm *DataManager) AddTotalUpload(value int64)

func (*DataManager) CallbackDownloadRate

func (dm *DataManager) CallbackDownloadRate(callback func(downRate float64)) *time.Ticker

func (*DataManager) CallbackUploadRate

func (dm *DataManager) CallbackUploadRate(callback func(upRate float64)) *time.Ticker

func (*DataManager) GetAvgDownloadRate

func (dm *DataManager) GetAvgDownloadRate() float64

func (*DataManager) GetAvgUploadRate

func (dm *DataManager) GetAvgUploadRate() float64

func (*DataManager) GetTotalDownload

func (dm *DataManager) GetTotalDownload() int64

func (*DataManager) GetTotalUpload

func (dm *DataManager) GetTotalUpload() int64

func (*DataManager) NewChunk

func (dm *DataManager) NewChunk() Chunk

func (*DataManager) RegisterDownloadHandler

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

func (*DataManager) RegisterUploadHandler

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

func (*DataManager) Reset

func (dm *DataManager) Reset()

func (*DataManager) SetCaptureTime

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

func (*DataManager) SetNThread

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

func (*DataManager) SetRateCaptureFrequency

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

func (*DataManager) Snapshots

func (dm *DataManager) Snapshots() *Snapshots

func (*DataManager) Wait

func (dm *DataManager) Wait()

type DataType

type DataType int32

type Debug

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

func NewDebug

func NewDebug() *Debug

func (*Debug) Enable

func (d *Debug) Enable()

func (*Debug) Printf

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

func (*Debug) Println

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

type Location

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

func GetLocation

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

func NewLocation

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

NewLocation new a Location

func ParseLocation

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

ParseLocation parse latitude and longitude string

func (*Location) String

func (l *Location) String() string

type Manager

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

	CallbackDownloadRate(callback func(downRate float64)) *time.Ticker
	CallbackUploadRate(callback func(upRate float64)) *time.Ticker

	RegisterDownloadHandler(fn func()) *funcGroup
	RegisterUploadHandler(fn func()) *funcGroup

	// 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

type Option func(*Speedtest)

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

func WithDoer

func WithDoer(doer *http.Client) Option

WithDoer sets the http.Client used to make requests.

func WithUserConfig

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 Proto

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      float64       `json:"dl_speed"`
	ULSpeed      float64       `json:"ul_speed"`
	TestDuration TestDuration  `json:"test_duration"`

	Context *Speedtest `json:"-"`
}

Server information

func CustomServer

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

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

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

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

func (*Server) HTTPPing

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

func (*Server) ICMPPing

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

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

func (*Server) MultiUploadTestContext

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

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

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

func (*Server) TestAll

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

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

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

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

func FetchServers

func FetchServers() (Servers, error)

FetchServers retrieves a list of available servers

func (Servers) Available

func (servers Servers) Available() *Servers

func (Servers) FindServer

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) Len

func (servers Servers) Len() int

Len finds length of servers. For sorting servers.

func (Servers) String

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

type Snapshot []*DataChunk

type Snapshots

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

func (*Snapshots) All

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

func (*Snapshots) Clean

func (rs *Snapshots) Clean()

func (*Snapshots) Latest

func (rs *Snapshots) Latest() *Snapshot

type Speedtest

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

Speedtest is a speedtest client.

func New

func New(opts ...Option) *Speedtest

New creates a new speedtest client.

func (*Speedtest) CustomServer

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

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

FetchServerByID retrieves a server by given serverID.

func (*Speedtest) FetchServerByIDContext

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

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

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

func (*Speedtest) FetchServers

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

FetchServers retrieves a list of available servers

func (*Speedtest) FetchUserInfo

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

FetchUserInfo returns information about caller determined by speedtest.net

func (*Speedtest) FetchUserInfoContext

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

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

func (*Speedtest) NewUserConfig

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

func (*Speedtest) RoundTrip

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

func (*Speedtest) Share

func (s *Speedtest) Share(sv *Server) (string, error)

type TestDuration

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

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

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

type UserConfig struct {
	T         *http.Transport
	UserAgent string
	Proxy     string
	Source    string
	Debug     bool
	PingMode  Proto

	SavingMode bool

	CityFlag     string
	LocationFlag string
	Location     *Location

	Keyword string // Fuzzy search

	NoDownload bool
	NoUpload   bool
}

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