checkly

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2020 License: MIT Imports: 10 Imported by: 1

README

GoDocGo Report CardCircleCI

checkly

checkly is a Go library for the Checkly website monitoring service. It allows you to create new checks, get data on existing checks, and delete checks.

While you can manage your Checkly checks entirely in Go code, using this library, you may prefer to use Terraform. In that case, you can use the Checkly Terraform provider (which in turn uses this library):

https://github.com/bitfield/terraform-provider-checkly

Setting your API key

To use the client library with your Checkly account, you will need an API Key for the account. Go to the Account Settings: API Keys page and click 'Create API Key'.

Using the Go library

Import the library using:

import "github.com/bitfield/checkly"

Creating a client

Create a new Client object by calling checkly.NewClient() with your API key:

apiKey := "3a4405dfb5894f4580785b40e48e6e10"
client := checkly.NewClient(apiKey)

Or read the key from an environment variable:

client := checkly.NewClient(os.Getenv("CHECKLY_API_KEY"))

Creating a new check

Once you have a client, you can create a check. First, populate a Check struct with the required parameters:

check := checkly.Check{
		Name:      "My Awesome Check",
		Type:      checkly.TypeAPI,
		Frequency: 5,
		Activated: true,
		Locations: []string{"eu-west-1"},
		Request: checkly.Request{
			    Method: http.MethodGet,
			    URL:    "http://example.com",
		},
}

Now you can pass it to client.Create() to create a check. This returns the ID string of the newly-created check:

ID, err := client.Create(check)

Retrieving a check

client.Get(ID) finds an existing check by ID and returns a Check struct containing its details:

check, err := client.Get("87dd7a8d-f6fd-46c0-b73c-b35712f56d72")
fmt.Println(check.Name)
// Output: My Awesome Check

Updating a check

client.Update(ID, check) updates an existing check with the specified details. For example, to change the name of a check:

ID := "87dd7a8d-f6fd-46c0-b73c-b35712f56d72"
check, err := client.Get(ID)
check.Name = "My updated check name"
client.Update(ID, check)

Deleting a check

Use client.Delete(ID) to delete a check by ID.

err := client.Delete("73d29ea2-6540-4bb5-967e-e07fa2c9465e")

A complete example program

You can see an example program which creates a Checkly check in the examples/demo folder.

Debugging

If things aren't working as you expect, you can assign an io.Writer to client.Debug to receive debug output. If client.Debug is non-nil, then all API requests and responses will be dumped to the specified writer (for example, os.Stderr).

Regardless of the debug setting, if a request fails with HTTP status 400 Bad Request), the full response will be dumped (to standard error if no debug writer is set):

client.Debug = os.Stderr

Example request and response dump:

POST /v1/checks HTTP/1.1
Host: api.checklyhq.com
User-Agent: Go-http-client/1.1
Content-Length: 852
Authorization: Bearer XXX
Content-Type: application/json
Accept-Encoding: gzip

{"id":"","name":"integrationTestCreate","checkType":"API","frequency":5,"activated":true,"muted":false,"shouldFail":false,"locations":["eu-west-1"],"created_at":"0001-01-01T00:00:00Z","updated_at":"0001-01-01T00:00:00Z","environment_variables":null,"doubleCheck":false,"sslCheck":false,"sslCheckDomain":"example.com","alertSettings":{"runBasedEscalation":{"failedRunThreshold":1},"timeBasedEscalation":{"minutesFailingThreshold":5},"reminders":{"interval":5},"sslCertificates":{"enabled":false,"alertThreshold":3}},"useGlobalAlertSettings":false,"request":{"method":"GET","url":"http://example.com","followRedirects":false,"body":"","bodyType":"NONE","headers":[],"queryParameters":[],"assertions":[{"edit":false,"order":0,"arrayIndex":0,"arraySelector":0,"source":"STATUS_CODE","property":"","comparison":"EQUALS","target":"200"}]}}

HTTP/1.1 201 Created
Transfer-Encoding: chunked
Cache-Control: no-cache
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Date: Thu, 18 Jul 2019 15:48:21 GMT
Server: Cowboy
Vary: origin,accept-encoding
Via: 1.1 vegur

3c8
{"name":"integrationTestCreate","checkType":"API","frequency":5,"activated":true,"muted":false,"shouldFail":false,"locations":["eu-west-1"],"doubleCheck":false,"sslCheck":false,"sslCheckDomain":"example.com","alertSettings":{"runBasedEscalation":{"failedRunThreshold":1},"timeBasedEscalation":{"minutesFailingThreshold":5},"reminders":{"interval":5,"amount":0},"sslCertificates":{"enabled":false,"alertThreshold":3}},"useGlobalAlertSettings":false,"request":{"method":"GET","url":"http://example.com","followRedirects":false,"body":"","bodyType":"NONE","headers":[],"queryParameters":[],"assertions":[{"source":"STATUS_CODE","property":"","comparison":"EQUALS","target":"200"}],"basicAuth":{"username":"","password":"f15c6e9c867c529b74b9dd2f9585ba76:1c97b45322f1cd139122666eb13c7562"}},"setupSnippetId":null,"tearDownSnippetId":null,"localSetupScript":null,"localTearDownScript":null,"created_at":"2019-07-18T15:48:21.844Z","id":"763fa73d-1d14-4046-88e6-14f883ceddc9"}
0

Bugs and feature requests

If you find a bug in the checkly client or library, please open an issue. Similarly, if you'd like a feature added or improved, let me know via an issue.

Not all the functionality of the Checkly API is implemented yet.

Pull requests welcome!

Documentation

Index

Constants

View Source
const Contains = "CONTAINS"

Contains asserts that the source contains a specified value.

View Source
const Equals = "EQUALS"

Equals asserts that the source and target are equal.

View Source
const GreaterThan = "GREATER_THAN"

GreaterThan asserts that the source is greater than the target.

View Source
const Headers = "HEADERS"

Headers identifies the HTTP headers as an assertion source.

View Source
const IsEmpty = "IS_EMPTY"

IsEmpty asserts that the source is empty.

View Source
const JSONBody = "JSON_BODY"

JSONBody identifies the JSON body data as an assertion source.

View Source
const LessThan = "LESS_THAN"

LessThan asserts that the source is less than the target.

View Source
const NotContains = "NOT_CONTAINS"

NotContains asserts that the source does not contain a specified value.

View Source
const NotEmpty = "NOT_EMPTY"

NotEmpty asserts that the source is not empty.

View Source
const NotEquals = "NOT_EQUALS"

NotEquals asserts that the source and target are not equal.

View Source
const ResponseTime = "RESPONSE_TIME"

ResponseTime identifies the response time as an assertion source.

View Source
const RunBased = "RUN_BASED"

RunBased identifies a run-based escalation type, for use with an AlertSettings.

View Source
const StatusCode = "STATUS_CODE"

StatusCode identifies the HTTP status code as an assertion source.

View Source
const TextBody = "TEXT_BODY"

TextBody identifies the response body text as an assertion source.

View Source
const TimeBased = "TIME_BASED"

TimeBased identifies a time-based escalation type, for use with an AlertSettings.

View Source
const TypeAPI = "API"

TypeAPI is used to identify an API check.

View Source
const TypeBrowser = "BROWSER"

TypeBrowser is used to identify a browser check.

Variables

This section is empty.

Functions

This section is empty.

Types

type AlertChannel added in v0.2.0

type AlertChannel struct {
	ID        string                 `json:"id"`
	Type      string                 `json:"type,omitempty"`
	Config    map[string]interface{} `json:"config,omitempty"`
	CreatedAt time.Time              `json:"created_at,omitempty"`
	UpdatedAt time.Time              `json:"updated_at,omitempty"`
}

AlertChannel represents an alert channel and its subscribed checks. The API defines this data as read-only.

type AlertSettings added in v0.0.2

type AlertSettings struct {
	EscalationType      string              `json:"escalationType,omitempty"`
	RunBasedEscalation  RunBasedEscalation  `json:"runBasedEscalation,omitempty"`
	TimeBasedEscalation TimeBasedEscalation `json:"timeBasedEscalation,omitempty"`
	Reminders           Reminders           `json:"reminders,omitempty"`
	SSLCertificates     SSLCertificates     `json:"sslCertificates,omitempty"`
}

AlertSettings represents an alert configuration.

type Assertion added in v0.0.4

type Assertion struct {
	Edit          bool   `json:"edit"`
	Order         int    `json:"order"`
	ArrayIndex    int    `json:"arrayIndex"`
	ArraySelector int    `json:"arraySelector"`
	Source        string `json:"source"`
	Property      string `json:"property"`
	Comparison    string `json:"comparison"`
	Target        string `json:"target"`
}

Assertion represents an assertion about an API response, which will be verified as part of the check.

type BasicAuth added in v0.0.7

type BasicAuth struct {
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
}

BasicAuth represents the HTTP basic authentication credentials for a request.

type Check

type Check struct {
	ID                        string                `json:"id"`
	Name                      string                `json:"name"`
	Type                      string                `json:"checkType"`
	Frequency                 int                   `json:"frequency"`
	Activated                 bool                  `json:"activated"`
	Muted                     bool                  `json:"muted"`
	ShouldFail                bool                  `json:"shouldFail"`
	Locations                 []string              `json:"locations"`
	DegradedResponseTime      int                   `json:"degradedResponseTime"`
	MaxResponseTime           int                   `json:"maxResponseTime"`
	Script                    string                `json:"script,omitempty"`
	CreatedAt                 time.Time             `json:"created_at,omitempty"`
	UpdatedAt                 time.Time             `json:"updated_at,omitempty"`
	EnvironmentVariables      []EnvironmentVariable `json:"environmentVariables"`
	DoubleCheck               bool                  `json:"doubleCheck"`
	Tags                      []string              `json:"tags,omitempty"`
	SSLCheck                  bool                  `json:"sslCheck"`
	SSLCheckDomain            string                `json:"sslCheckDomain"`
	SetupSnippetID            int64                 `json:"setupSnippetId,omitempty"`
	TearDownSnippetID         int64                 `json:"tearDownSnippetId,omitempty"`
	LocalSetupScript          string                `json:"localSetupScript,omitempty"`
	LocalTearDownScript       string                `json:"localTearDownScript,omitempty"`
	AlertSettings             AlertSettings         `json:"alertSettings,omitempty"`
	UseGlobalAlertSettings    bool                  `json:"useGlobalAlertSettings"`
	Request                   Request               `json:"request"`
	AlertChannelSubscriptions []Subscription        `json:"alertChannelSubscriptions"`
}

Check represents the parameters for an existing check.

type Client

type Client struct {
	URL        string
	HTTPClient *http.Client
	Debug      io.Writer
	// contains filtered or unexported fields
}

Client represents a Checkly client. If the Debug field is set to an io.Writer (for example os.Stdout), then the client will dump API requests and responses to it. To use a non-default HTTP client (for example, for testing, or to set a timeout), assign to the HTTPClient field. To set a non-default URL (for example, for testing), assign to the URL field.

func NewClient

func NewClient(apiKey string) Client

NewClient takes a Checkly API key, and returns a Client ready to use.

func (*Client) Create

func (c *Client) Create(check Check) (string, error)

Create creates a new check with the specified details. It returns the check ID of the newly-created check, or an error.

func (*Client) Delete

func (c *Client) Delete(ID string) error

Delete deletes the check with the specified ID. It returns a non-nil error if the request failed.

func (*Client) Get

func (c *Client) Get(ID string) (Check, error)

Get takes the ID of an existing check, and returns the check parameters, or an error.

func (*Client) MakeAPICall

func (c *Client) MakeAPICall(method string, URL string, data []byte) (statusCode int, response string, err error)

MakeAPICall calls the Checkly API with the specified URL and data, and returns the HTTP status code and string data of the response.

func (*Client) Update added in v0.0.6

func (c *Client) Update(ID string, check Check) error

Update updates an existing check with the specified details. It returns a non-nil error if the request failed.

type EnvironmentVariable added in v0.0.2

type EnvironmentVariable struct {
	Key    string `json:"key"`
	Value  string `json:"value"`
	Locked bool   `json:"locked"`
}

EnvironmentVariable represents a key-value pair for setting environment values during check execution.

type KeyValue added in v0.0.4

type KeyValue struct {
	Key    string `json:"key"`
	Value  string `json:"value"`
	Locked bool   `json:"locked"`
}

KeyValue represents a key-value pair, for example a request header setting, or a query parameter.

type Reminders added in v0.0.2

type Reminders struct {
	Amount   int `json:"amount,omitempty"`
	Interval int `json:"interval,omitempty"`
}

Reminders represents the number of reminders to send after an alert notification, and the time interval between them.

type Request

type Request struct {
	Method          string      `json:"method"`
	URL             string      `json:"url"`
	FollowRedirects bool        `json:"followRedirects"`
	Body            string      `json:"body"`
	BodyType        string      `json:"bodyType,omitempty"`
	Headers         []KeyValue  `json:"headers"`
	QueryParameters []KeyValue  `json:"queryParameters"`
	Assertions      []Assertion `json:"assertions"`
	BasicAuth       BasicAuth   `json:"basicAuth,omitempty"`
}

Request represents the parameters for the request made by the check.

type RunBasedEscalation added in v0.0.2

type RunBasedEscalation struct {
	FailedRunThreshold int `json:"failedRunThreshold,omitempty"`
}

RunBasedEscalation represents an alert escalation based on a number of failed check runs.

type SSLCertificates added in v0.0.2

type SSLCertificates struct {
	Enabled        bool `json:"enabled"`
	AlertThreshold int  `json:"alertThreshold"`
}

SSLCertificates represents alert settings for expiring SSL certificates.

type Subscription added in v0.2.0

type Subscription struct {
	ID             string `json:"id,omitempty"`
	CheckID        string `json:"checkId,omitempty"`
	AlertChannelID int64  `json:"alertChannelId,omitempty"`
	Activated      bool   `json:"activated"`
}

Subscription represents a subscription to an alert channel. The API defines this data as read-only.

type TimeBasedEscalation added in v0.0.2

type TimeBasedEscalation struct {
	MinutesFailingThreshold int `json:"minutesFailingThreshold,omitempty"`
}

TimeBasedEscalation represents an alert escalation based on the number of minutes after a check first starts failing.

Jump to

Keyboard shortcuts

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