### Install HostTracker SDK Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/llms.txt Command to install the HostTracker Go SDK package. ```bash go get github.com/HostTracker/hosttracker-sdk-go ``` -------------------------------- ### Initialize and Use HostTracker Client Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/llms.txt Demonstrates client initialization, listing monitors, creating a new monitor, running an instant check, and verifying webhook signatures. ```go package main import ( "context" "fmt" "log" "os" hosttracker "github.com/HostTracker/hosttracker-sdk-go" ) func main() { c, err := hosttracker.New(os.Getenv("HT_TOKEN")) if err != nil { log.Fatal(err) } ctx := context.Background() // List monitors. Any 4xx/5xx arrives as a typed error, so err != nil is enough. resp, err := c.ListMonitorWithResponse(ctx, &hosttracker.ListMonitorParams{ Limit: hosttracker.Ptr(int32(10)), State: &[]hosttracker.ListMonitorParamsState{"down"}, }) if err != nil { log.Fatal(err) } for _, m := range resp.JSON200.Data { fmt.Println(m.Id, *m.Name, hosttracker.FromUnix(*m.Created)) } // Create one. created, err := c.CreateMonitorWithResponse(ctx, nil, hosttracker.MonitorWriteRequest{ Type: hosttracker.MonitorWriteRequestTypeHttp, Url: hosttracker.Ptr("https://example.com"), Name: hosttracker.Ptr("Marketing site"), Interval: hosttracker.Ptr(int64(5)), Locations: &hosttracker.MonitorLocations{Pools: &[]string{"allworld"}}, }) // Run an instant check; RunCheck follows the resultUrl the server returned. res, err := c.RunCheck(ctx, hosttracker.IcCreateRequest{ Url: "https://www.host-tracker.com", Type: hosttracker.Ptr(hosttracker.IcCreateRequestTypeHttp), }, nil) // Verify a webhook on the exact bytes received, before parsing. err = hosttracker.VerifyWebhookSignature(header, body, secrets, nil) } ``` -------------------------------- ### Create a Monitor Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/README.md Create a new monitor by providing configuration details to the CreateMonitorWithResponse method. ```go resp, err := c.CreateMonitorWithResponse(ctx, nil, hosttracker.MonitorWriteRequest{ Type: hosttracker.MonitorWriteRequestTypeHttp, Url: hosttracker.Ptr("https://example.com"), Name: hosttracker.Ptr("Marketing site"), Interval: hosttracker.Ptr(int64(5)), Locations: &hosttracker.MonitorLocations{Pools: &[]string{"allworld"}}, }) if err != nil { log.Fatal(err) } fmt.Println("created", resp.JSON201.Id) ``` -------------------------------- ### Initialize HostTracker Client Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/README.md Configure the client using functional options for HTTP transport, timeouts, retries, and request hooks. ```go c, err := hosttracker.New(token, hosttracker.WithBaseURL("https://api2.host-tracker.com"), // default hosttracker.WithHTTPClient(&http.Client{Transport: tr}), // your transport, jar, proxy hosttracker.WithTimeout(30*time.Second), // per attempt; default 30s hosttracker.WithMaxRetries(2), // default 2 hosttracker.WithMaxRetryDelay(60*time.Second), // default 60s hosttracker.WithUserAgent("acme-ops/2.1"), // appended to the SDK's own hosttracker.WithIdempotency(true), // default true hosttracker.WithRequestEditorFn(addTenantHeader), // per-request hook ) ``` -------------------------------- ### Run SDK tests Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/README.md Execute unit tests or opt-in live smoke tests. Live tests require specific environment variables and are read-only. ```bash go test ./... # unit tests, mocked transport HT_BASE_URL=https://api2.host-tracker.com HT_TOKEN_FILE=/path/to/token \ go test -tags live -run TestLive ./... # opt-in live smoke, read-only ``` -------------------------------- ### Run an Instant Check Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/README.md Execute an instant check and follow the result URL until completion. ```go res, err := c.RunCheck(ctx, hosttracker.IcCreateRequest{ Url: "https://www.host-tracker.com", Type: hosttracker.Ptr(hosttracker.IcCreateRequestTypeHttp), }, nil) if err != nil { log.Fatal(err) } for _, ev := range *res.Events { fmt.Println(*ev.Location, hosttracker.FromUnix(ev.DoneAt), ev.Error) } ``` -------------------------------- ### List Monitors Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/README.md Retrieve a list of monitors using the client's ListMonitorWithResponse method. ```go package main import ( "context" "fmt" "log" "os" hosttracker "github.com/HostTracker/hosttracker-sdk-go" ) func main() { c, err := hosttracker.New(os.Getenv("HT_TOKEN")) if err != nil { log.Fatal(err) } resp, err := c.ListMonitorWithResponse(context.Background(), &hosttracker.ListMonitorParams{ Limit: hosttracker.Ptr(int32(10)), State: &[]hosttracker.ListMonitorParamsState{"down"}, }) if err != nil { log.Fatal(err) // any 4xx/5xx arrives here, typed } for _, m := range resp.JSON200.Data { fmt.Println(m.Id, *m.Name, hosttracker.FromUnix(*m.Created)) } } ``` -------------------------------- ### Execute and wait for bulk mutation jobs Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/README.md Initiates a bulk creation request and uses WaitForJob to poll until the job reaches a terminal state. ```go accepted, err := c.BulkCreateMonitorWithResponse(ctx, nil, hosttracker.MonitorBulkCreateRequest{ Items: []hosttracker.MonitorBulkItem{ {Type: hosttracker.Ptr(hosttracker.MonitorBulkItemTypeHttp), Url: hosttracker.Ptr("https://one.example")}, }, }) if err != nil { return err } job, err := c.WaitForJob(ctx, accepted.JSON202.JobId, nil) if err != nil { return err } switch *job.State { case hosttracker.JobViewStateSucceeded, hosttracker.JobViewStatePartial: for _, item := range *job.Results { fmt.Println(item.Index, *item.Status, item.EntityId) // a failed item's Error is a full problem document } case hosttracker.JobViewStateInterrupted: // The server running it died. Resume continues, skipping concluded items. _, err = c.ResumeJobWithResponse(ctx, job.Id, nil) } ``` -------------------------------- ### Paginate through monitor collections Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/README.md Uses the Paginate helper to iterate over items across multiple pages, automatically handling cursor management. ```go list := func(ctx context.Context, cursor *string) ([]hosttracker.MonitorView, *string, error) { resp, err := c.ListMonitorWithResponse(ctx, &hosttracker.ListMonitorParams{ Cursor: cursor, Limit: hosttracker.Ptr(int32(200)), // default 50, max 500 }) if err != nil { return nil, nil, err } return resp.JSON200.Data, resp.JSON200.NextCursor, nil } for monitor, err := range hosttracker.Paginate(ctx, list) { if err != nil { return err } fmt.Println(monitor.Id) } ``` -------------------------------- ### Regenerate the SDK client Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/README.md Use these commands to regenerate the client code from the OpenAPI specification. Never edit the generated files manually. ```bash ./scripts/regen.sh # fetch the published spec HT_SPEC=../openapi/openapi-3.0.json ./scripts/regen.sh # or use a local copy go generate ./... # same thing ``` -------------------------------- ### Configure Idempotency Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/README.md Provide custom idempotency keys for specific calls or disable automatic idempotency globally. ```go c.CreateMonitorWithResponse(ctx, nil, body, hosttracker.IdempotencyKey("order-4711")) hosttracker.New(token, hosttracker.WithIdempotency(false)) ``` -------------------------------- ### Verify a Webhook Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/README.md Verify the signature of an incoming webhook request before parsing the event data. ```go func handler(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) // Verify the exact bytes received, before parsing. if err := hosttracker.VerifyWebhookSignature(r.Header, body, secrets, nil); err != nil { http.Error(w, "bad signature", http.StatusBadRequest) return } ev, err := hosttracker.ParseWebhookEvent(body) if err != nil { http.Error(w, "bad body", http.StatusBadRequest) return } switch ev.Event { // ev.ID (= HT-Delivery) is stable across retries: dedupe on it case "monitor.down", "monitor.up": var alert hosttracker.WebhookMonitorAlert _ = ev.DataAs(&alert) log.Printf("%s is %s", alert.Monitor.Name, ev.Event) default: // The event vocabulary is open - never fail on an unknown one. } w.WriteHeader(http.StatusOK) } ``` -------------------------------- ### Handle API Errors Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/README.md Use hosttracker.IsCode and hosttracker.AsError to branch on specific error conditions rather than HTTP status codes. ```go resp, err := c.GetMonitorWithResponse(ctx, id, nil) switch { case err == nil: use(resp.JSON200) case hosttracker.IsCode(err, hosttracker.CodeNotFound): // gone, or never ours case hosttracker.IsCode(err, hosttracker.CodeQuotaExceeded): e, _ := hosttracker.AsError(err) log.Printf("quota spent; resets in %v s", e.RateLimit.Reset) default: e, _ := hosttracker.AsError(err) log.Printf("%s (%d) on %s: %s [requestId=%s fields=%v]", e.Code, e.Status, e.Instance, e.Detail, e.RequestID, e.FieldPointers()) } ``` -------------------------------- ### Convert Unix Timestamps Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/README.md Convert between Unix seconds and time.Time objects, as the API uses Unix seconds for all instant fields. ```go t := hosttracker.FromUnix(*monitor.Created) // time.Time, UTC sec := hosttracker.ToUnix(time.Now()) ``` -------------------------------- ### Access Response Metadata Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/README.md Extract metadata from successful HTTP responses using the MetaOf helper. ```go meta := hosttracker.MetaOf(resp.HTTPResponse) meta.RequestID meta.RateLimit.Metered() // false when the policy is the literal "none" meta.IdempotencyReplayed // true when this was a replayed write meta.RetryAfter ``` -------------------------------- ### ParseWebhookEvent Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/README.md Parses the raw webhook body into a structured event envelope. ```APIDOC ## ParseWebhookEvent ### Description Parses the raw JSON body into an envelope containing metadata and the event data. The event data remains as raw JSON until decoded via DataAs. ### Method Function Call ### Parameters - **body** ([]byte) - Required - The raw JSON body of the webhook event. ### Response - **envelope** (WebhookEnvelope) - Returns an object containing ID, Event, OccurredAt, APIVersion, and Data. ``` -------------------------------- ### VerifyWebhookSignature Source: https://github.com/hosttracker/hosttracker-sdk-go/blob/main/README.md Verifies the authenticity of an incoming webhook request by checking the provided signatures against the configured secrets. ```APIDOC ## VerifyWebhookSignature ### Description Verifies the webhook signature using either the HT-Signature or Standard Webhooks scheme. It enforces a replay window and performs constant-time comparison. ### Method Function Call ### Parameters - **header** (http.Header) - Required - The request headers containing signature information. - **body** ([]byte) - Required - The raw request body. - **secrets** ([]string) - Required - A slice of currently valid secrets for verification. - **options** (*hosttracker.VerifyOptions) - Optional - Configuration options including tolerance window and scheme enforcement. ### Response - **error** (error) - Returns nil on success, or a sentinel error (ErrNoSignature, ErrSignatureFormat, ErrSignatureExpired, ErrSignatureInvalid, ErrNoSecrets) on failure. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.