globalping

package
v1.4.4 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2024 License: MPL-2.0 Imports: 16 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrTypeExchangeFailed      = "exchange_failed"
	ErrTypeRefreshFailed       = "refresh_failed"
	ErrTypeRevokeFailed        = "revoke_failed"
	ErrTypeIntrospectionFailed = "introspection_failed"
	ErrTypeInvalidGrant        = "invalid_grant"
	ErrTypeNotAuthorized       = "not_authorized"
)
View Source
var (
	StatusUnauthorizedWithTokenRefreshed = 1000
)

Functions

func DecodeHTTPHeaders added in v1.4.0

func DecodeHTTPHeaders(headers json.RawMessage) (map[string]string, error)

Types

type AuthorizeError added in v1.4.0

type AuthorizeError struct {
	Code        int    `json:"-"`
	ErrorType   string `json:"error"`
	Description string `json:"error_description"`
}

func (*AuthorizeError) Error added in v1.4.0

func (e *AuthorizeError) Error() string

type AuthorizeResponse added in v1.4.0

type AuthorizeResponse struct {
	AuthorizeURL string
	CallbackURL  string
}

type CacheEntry added in v1.4.0

type CacheEntry struct {
	ETag     string
	Data     []byte
	ExpireAt int64 // Unix timestamp
}

type Client

type Client interface {
	// Creates a new measurement with parameters set in the request body. The measurement runs asynchronously and you can retrieve its current state at the URL returned in the Location header.
	//
	// https://globalping.io/docs/api.globalping.io#post-/v1/measurements
	CreateMeasurement(measurement *MeasurementCreate) (*MeasurementCreateResponse, error)
	// Returns the status and results of an existing measurement. Measurements are typically available for up to 7 days after creation.
	//
	// https://globalping.io/docs/api.globalping.io#get-/v1/measurements/-id-
	GetMeasurement(id string) (*Measurement, error)
	// Returns the status and results of an existing measurement. Measurements are typically available for up to 7 days after creation.
	//
	// https://globalping.io/docs/api.globalping.io#get-/v1/measurements/-id-
	GetMeasurementRaw(id string) ([]byte, error)
	// Returns a link to be used for authorization and listens for the authorization callback.
	//
	// onTokenRefresh will be called if the authorization is successful.
	Authorize(callback func(error)) (*AuthorizeResponse, error)
	// Returns the introspection response for the token.
	//
	// If the token is empty, the client's current token will be used.
	TokenIntrospection(token string) (*IntrospectionResponse, error)
	// Removes the current token from the client. It also revokes the tokens if the refresh token is available.
	//
	// onTokenRefresh will be called if the token is successfully removed.
	Logout() error
	// Revokes the token.
	RevokeToken(token string) error
	// Returns the rate limits for the current user or IP address.
	Limits() (*LimitsResponse, error)
}

func NewClient

func NewClient(config Config) Client

NewClient creates a new client with the given configuration. The client will not have a cache cleanup goroutine, therefore cached responses will never be removed. If you want a cache cleanup goroutine, use NewClientWithCacheCleanup.

func NewClientWithCacheCleanup added in v1.4.0

func NewClientWithCacheCleanup(config Config, t *time.Ticker, cacheExpireSeconds int64) Client

NewClientWithCacheCleanup creates a new client with a cache cleanup goroutine that runs every t. The cache cleanup goroutine will remove entries that have expired. If cacheExpireSeconds is 0, the cache entries will never expire.

type Config added in v1.4.0

type Config struct {
	HTTPClient *http.Client // If set, this client will be used for API requests and authorization

	APIURL       string
	DashboardURL string

	AuthURL          string
	AuthClientID     string
	AuthClientSecret string
	AuthToken        *Token
	OnTokenRefresh   func(*Token)

	UserAgent string
}

type CreateLimitType added in v1.4.0

type CreateLimitType string
const (
	CreateLimitTypeIP   CreateLimitType = "ip"
	CreateLimitTypeUser CreateLimitType = "user"
)

type CreditLimits added in v1.4.0

type CreditLimits struct {
	Remaining int64 `json:"remaining"`
}

type DNSAnswer added in v1.4.0

type DNSAnswer struct {
	Name  string `json:"name"`  // The record domain name.
	Type  string `json:"type"`  // The record type.
	TTL   int    `json:"ttl"`   // The record time-to-live value in seconds.
	Class string `json:"class"` // The record class.
	Value string `json:"value"` // The record value.
}

func DecodeDNSAnswers added in v1.4.0

func DecodeDNSAnswers(answers json.RawMessage) ([]DNSAnswer, error)

type DNSTimings

type DNSTimings struct {
	Total float64 `json:"total"` // The total query time in milliseconds.
}

func DecodeDNSTimings

func DecodeDNSTimings(timings json.RawMessage) (*DNSTimings, error)

type HTTPTLSCertificate added in v1.4.0

type HTTPTLSCertificate struct {
	Authorized     bool                  `json:"authorized"`     // Indicates whether a trusted authority signed the certificate
	Error          string                `json:"error"`          // The reason for rejecting the certificate if authorized is false
	CreatedAt      time.Time             `json:"createdAt"`      // The creation date and time of the certificate
	ExpiresAt      time.Time             `json:"expiresAt"`      // The expiration date and time of the certificate
	Subject        TLSCertificateSubject `json:"subject"`        // Information about the certificate subject.
	Issuer         TLSCertificateIssuer  `json:"issuer"`         // Information about the certificate issuer.
	KeyType        string                `json:"keyType"`        // The type of the used key, or null for unrecognized types.
	KeyBits        int                   `json:"keyBits"`        // The size of the used key, or null for unrecognized types.
	SerialNumber   string                `json:"serialNumber"`   // The certificate serial number as a : separated HEX string
	Fingerprint256 string                `json:"fingerprint256"` // The SHA-256 digest of the DER-encoded certificate as a : separated HEX string
	PublicKey      string                `json:"publicKey"`      // The public key as a : separated HEX string, or null for unrecognized types.
}

func DecodeHTTPTLS added in v1.4.0

func DecodeHTTPTLS(tls json.RawMessage) (*HTTPTLSCertificate, error)

type HTTPTimings

type HTTPTimings struct {
	Total     int `json:"total"`     // The total HTTP request time
	DNS       int `json:"dns"`       // The time required to perform the DNS lookup.
	TCP       int `json:"tcp"`       // The time from performing the DNS lookup to establishing the TCP connection.
	TLS       int `json:"tls"`       // The time from establishing the TCP connection to establishing the TLS session.
	FirstByte int `json:"firstByte"` // The time from establishing the TCP/TLS connection to the first response byte.
	Download  int `json:"download"`  // The time from the first byte to downloading the whole response.
}

func DecodeHTTPTimings

func DecodeHTTPTimings(timings json.RawMessage) (*HTTPTimings, error)

type IPVersion added in v1.4.0

type IPVersion int
const (
	IPVersion4 IPVersion = 4
	IPVersion6 IPVersion = 6
)

type IntrospectionResponse added in v1.4.0

type IntrospectionResponse struct {
	// Required fields
	Active bool `json:"active"`

	// Optional fields
	Scope     string `json:"scope"`
	ClientID  string `json:"client_id"`
	Username  string `json:"username"`
	TokenType string `json:"token_type"`
	Exp       int64  `json:"exp"` // Expiration Time. Unix timestamp
	Iat       int64  `json:"iat"` // Issued At. Unix timestamp
	Nbf       int64  `json:"nbf"` // Not to be used before. Unix timestamp
	Sub       string `json:"sub"` // Subject
	Aud       string `json:"aud"` // Audience
	Iss       string `json:"iss"` // Issuer
	Jti       string `json:"jti"` // JWT ID
}

https://datatracker.ietf.org/doc/html/rfc7662#section-2.1

type LimitsError added in v1.4.0

type LimitsError struct {
	Code    int    `json:"-"`
	Type    string `json:"type"`
	Message string `json:"message"`
}

func (*LimitsError) Error added in v1.4.0

func (e *LimitsError) Error() string

type LimitsErrorResponse added in v1.4.0

type LimitsErrorResponse struct {
	Error *LimitsError `json:"error"`
}

type LimitsResponse added in v1.4.0

type LimitsResponse struct {
	RateLimits RateLimits   `json:"rateLimit"`
	Credits    CreditLimits `json:"credits"` // Only for authenticated requests
}

https://globalping.io/docs/api.globalping.io#get-/v1/limits

type Locations

type Locations struct {
	Magic string `json:"magic"`
}

type MTRHop added in v1.4.0

type MTRHop struct {
	ResolvedAddress  string      `json:"resolvedAddress"`  // The resolved IP address of the target
	ResolvedHostname string      `json:"resolvedHostname"` // The resolved hostname of the target
	ASN              []int       `json:"asn"`              // An array containing the ASNs assigned to this hop.
	Stats            MTRStats    `json:"stats"`            // Summary rtt and packet loss statistics. All times are in milliseconds.
	Timings          []MTRTiming `json:"timings"`          // An array containing details for each packet. All times are in milliseconds.
}

func DecodeMTRHops added in v1.4.0

func DecodeMTRHops(hops json.RawMessage) ([]MTRHop, error)

type MTRStats added in v1.4.0

type MTRStats struct {
	Min   float64 `json:"min"`   // The lowest rtt value.
	Avg   float64 `json:"avg"`   // The average rtt value.
	Max   float64 `json:"max"`   // The highest rtt value.
	StDev float64 `json:"stDev"` // The standard deviation of the rtt values.

	JMin  float64 `json:"jMin"`  // The lowest jitter value.
	JAvg  float64 `json:"jAvg"`  // The average jitter value.
	JMax  float64 `json:"jMax"`  // The highest jitter value.
	Total int     `json:"total"` // The number of sent packets.
	Rcv   int     `json:"rcv"`   // The number of received packets.
	Drop  int     `json:"drop"`  // The number of dropped packets (total - rcv).

	Loss float64 `json:"loss"` // The percentage of dropped packets.
}

type MTRTiming added in v1.4.0

type MTRTiming struct {
	RTT float64 `json:"rtt"` // The round-trip time for this packet.
}

type Measurement

type Measurement struct {
	ID          string             `json:"id"`
	Type        string             `json:"type"`
	Status      MeasurementStatus  `json:"status"`
	CreatedAt   string             `json:"createdAt"`
	UpdatedAt   string             `json:"updatedAt"`
	Target      string             `json:"target"`
	ProbesCount int                `json:"probesCount"`
	Results     []ProbeMeasurement `json:"results"`
}

type MeasurementCreate

type MeasurementCreate struct {
	Limit             int                 `json:"limit"`
	Locations         []Locations         `json:"locations"`
	Type              string              `json:"type"`
	Target            string              `json:"target"`
	InProgressUpdates bool                `json:"inProgressUpdates"`
	Options           *MeasurementOptions `json:"measurementOptions,omitempty"`
}

type MeasurementCreateResponse

type MeasurementCreateResponse struct {
	ID          string `json:"id"`
	ProbesCount int    `json:"probesCount"`
}

type MeasurementError added in v1.4.0

type MeasurementError struct {
	Code    int                    `json:"-"`
	Message string                 `json:"message"`
	Type    string                 `json:"type"`
	Params  map[string]interface{} `json:"params,omitempty"`
}

func (*MeasurementError) Error added in v1.4.0

func (e *MeasurementError) Error() string

type MeasurementErrorResponse added in v1.4.0

type MeasurementErrorResponse struct {
	Error *MeasurementError `json:"error"`
}

type MeasurementOptions

type MeasurementOptions struct {
	Query     *QueryOptions   `json:"query,omitempty"`
	Request   *RequestOptions `json:"request,omitempty"`
	Protocol  string          `json:"protocol,omitempty"`
	Port      int             `json:"port,omitempty"`
	Resolver  string          `json:"resolver,omitempty"`
	Trace     bool            `json:"trace,omitempty"`
	Packets   int             `json:"packets,omitempty"`
	IPVersion IPVersion       `json:"ipVersion,omitempty"`
}

type MeasurementStatus

type MeasurementStatus string
const (
	StatusInProgress MeasurementStatus = "in-progress"
	StatusFailed     MeasurementStatus = "failed"
	StatusOffline    MeasurementStatus = "offline"
	StatusFinished   MeasurementStatus = "finished"
)

type MeasurementsCreateLimits added in v1.4.0

type MeasurementsCreateLimits struct {
	Type      CreateLimitType `json:"type"`
	Limit     int64           `json:"limit"`
	Remaining int64           `json:"remaining"`
	Reset     int64           `json:"reset"`
}

type MeasurementsLimits added in v1.4.0

type MeasurementsLimits struct {
	Create MeasurementsCreateLimits `json:"create"`
}

type PingStats

type PingStats struct {
	Min   float64 `json:"min"`   // The lowest rtt value.
	Avg   float64 `json:"avg"`   // The average rtt value.
	Max   float64 `json:"max"`   // The highest rtt value.
	Total int     `json:"total"` // The number of sent packets.
	Rcv   int     `json:"rcv"`   // The number of received packets.
	Drop  int     `json:"drop"`  // The number of dropped packets (total - rcv).
	Loss  float64 `json:"loss"`  // The percentage of dropped packets.
	Mdev  float64 `json:"mdev"`  // The mean deviation of the rtt values.
}

func DecodePingStats

func DecodePingStats(stats json.RawMessage) (*PingStats, error)

type PingTiming

type PingTiming struct {
	RTT float64 `json:"rtt"` // The round-trip time for this packet.
	TTL int     `json:"ttl"` // The packet time-to-live value.
}

func DecodePingTimings

func DecodePingTimings(timings json.RawMessage) ([]PingTiming, error)

type ProbeDetails

type ProbeDetails struct {
	Continent string   `json:"continent"`
	Region    string   `json:"region"`
	Country   string   `json:"country"`
	City      string   `json:"city"`
	State     string   `json:"state,omitempty"`
	ASN       int      `json:"asn"`
	Network   string   `json:"network,omitempty"`
	Tags      []string `json:"tags,omitempty"`
}

type ProbeMeasurement

type ProbeMeasurement struct {
	Probe  ProbeDetails `json:"probe"`
	Result ProbeResult  `json:"result"`
}

type ProbeResult

type ProbeResult struct {
	Status    MeasurementStatus `json:"status"`    // The current measurement status.
	RawOutput string            `json:"rawOutput"` //  The raw output of the test. Can be presented to users but is not meant to be parsed by clients.

	// Common
	ResolvedAddress  string `json:"resolvedAddress"`  // The resolved IP address of the target
	ResolvedHostname string `json:"resolvedHostname"` // The resolved hostname of the target

	// Ping
	StatsRaw json.RawMessage `json:"stats,omitempty"` // Summary rtt and packet loss statistics. All times are in milliseconds.

	// DNS
	StatusCode     int             `json:"statusCode"`        // The HTTP status code.
	StatusCodeName string          `json:"statusCodeName"`    // The HTTP status code name.
	Resolver       string          `json:"resolver"`          // The hostname or IP of the resolver that answered the query.
	AnswersRaw     json.RawMessage `json:"answers,omitempty"` // An array of the received resource records.

	// HTTP
	RawHeaders string          `json:"rawHeaders"`        // The raw HTTP response headers.
	RawBody    string          `json:"rawBody"`           // The raw HTTP response body or null if there was no body in response. Note that only the first 10 kb are returned.
	Truncated  bool            `json:"truncated"`         // Indicates whether the rawBody value was truncated due to being too big.
	HeadersRaw json.RawMessage `json:"headers,omitempty"` // The HTTP response headers.
	TLSRaw     json.RawMessage `json:"tls,omitempty"`     // Information about the TLS certificate or null if no TLS certificate is available.

	// Common
	HopsRaw    json.RawMessage `json:"hops,omitempty"`
	TimingsRaw json.RawMessage `json:"timings,omitempty"`
}

type QueryOptions

type QueryOptions struct {
	Type string `json:"type,omitempty"`
}

type RateLimits added in v1.4.0

type RateLimits struct {
	Measurements MeasurementsLimits `json:"measurements"`
}

type RequestOptions

type RequestOptions struct {
	Headers map[string]string `json:"headers,omitempty"`
	Path    string            `json:"path,omitempty"`
	Host    string            `json:"host,omitempty"`
	Query   string            `json:"query,omitempty"`
	Method  string            `json:"method,omitempty"`
}

type TLSCertificateIssuer added in v1.4.0

type TLSCertificateIssuer struct {
	Country      string `json:"C"`  // The issuer's country.
	Organization string `json:"O"`  // The issuer's organization.
	CommonName   string `json:"CN"` // The issuer's common name.
}

type TLSCertificateSubject added in v1.4.0

type TLSCertificateSubject struct {
	CommonName      string `json:"CN"`  // The subject's common name.
	AlternativeName string `json:"alt"` // The subject's alternative name.
}

type Token added in v1.4.0

type Token struct {
	AccessToken  string    `json:"access_token"`
	TokenType    string    `json:"token_type,omitempty"`
	RefreshToken string    `json:"refresh_token,omitempty"`
	ExpiresIn    int64     `json:"expires_in,omitempty"`
	Expiry       time.Time `json:"expiry,omitempty"`
}

type TraceDNSHop added in v1.4.0

type TraceDNSHop struct {
	Resolver string      `json:"resolver"` // The hostname or IP of the resolver that answered the query.
	Answers  []DNSAnswer `json:"answers"`  // An array of the received resource records.
	Timings  DNSTimings  `json:"timings"`  // Details about the query times. All times are in milliseconds.
}

func DecodeTraceDNSHops added in v1.4.0

func DecodeTraceDNSHops(hops json.RawMessage) ([]TraceDNSHop, error)

type TracerouteHop added in v1.4.0

type TracerouteHop struct {
	ResolvedAddress  string             `json:"resolvedAddress"`  // The resolved IP address of the target
	ResolvedHostname string             `json:"resolvedHostname"` // The resolved hostname of the target
	Timings          []TracerouteTiming `json:"timings"`          // An array containing details for each packet. All times are in milliseconds.
}

func DecodeTracerouteHops added in v1.4.0

func DecodeTracerouteHops(hops json.RawMessage) ([]TracerouteHop, error)

type TracerouteTiming added in v1.4.0

type TracerouteTiming struct {
	RTT float64 `json:"rtt"` // The round-trip time for this packet.
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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