checkhim

package module
v0.0.0-...-24bf0d0 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2025 License: MIT Imports: 7 Imported by: 0

README

CheckHim Go SDK

Go Reference Go Report Card License Coverage Status

The official Go SDK for the CheckHim phone number verification API. Verify phone numbers quickly and reliably with our global verification service.

Features

  • Simple API - Easy-to-use interface with minimal setup
  • Global Coverage - Verify phone numbers from around the world
  • High Performance - Optimized for speed and reliability
  • Secure - Built-in security best practices
  • Error Handling - Comprehensive error handling and recovery
  • Rich Response Data - Get detailed information about verified numbers
  • Context Support - Full context.Context support for cancellation and timeouts
  • Well Tested - Extensive test coverage with examples

Installation

go get github.com/checkhim/go-sdk

Quick Start

package main

import (
    "fmt"
    "log"
    
    "github.com/checkhim/go-sdk"
)

func main() {
    // Create a new client with your API key
    client := checkhim.New("your-api-key-here")
    
    // Verify a phone number
    result, err := client.Verify(checkhim.VerifyRequest{
        Number: "+5511984339000",
    })
    if err != nil {
        log.Fatal(err)
    }
    
    // Use the results
    fmt.Printf("Valid: %v, Carrier: %s\n", result.Valid, result.Carrier)
}

Usage Examples

Basic Verification
client := checkhim.New("your-api-key")

result, err := client.Verify(checkhim.VerifyRequest{
    Number: "+1234567890",
})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Valid: %v\n", result.Valid)
fmt.Printf("Carrier: %s\n", result.Carrier)
With Context and Timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

result, err := client.VerifyWithContext(ctx, checkhim.VerifyRequest{
    Number: "+5511984339000",
})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Valid: %v, Carrier: %s\n", result.Valid, result.Carrier)
Custom Configuration
client := checkhim.New("your-api-key", checkhim.Config{
    BaseURL: "https://api.checkhim.tech", // Custom API endpoint
    Timeout: 30 * time.Second,            // Custom timeout
})

result, err := client.Verify(checkhim.VerifyRequest{
    Number: "+244921204020",
})
Error Handling
result, err := client.Verify(checkhim.VerifyRequest{
    Number: "+invalid-number",
})
if err != nil {
    // Check if it's an API error
    if apiErr, ok := err.(*checkhim.APIError); ok {
        fmt.Printf("API Error - Status: %d, Message: %s, Code: %s\n",
            apiErr.StatusCode, apiErr.Message, apiErr.Code)
        
        // Handle specific error codes
        switch apiErr.Code {
        case "unauthorized":
            log.Fatal("Invalid API key")
        case "rate_limit_exceeded":
            log.Fatal("Rate limit exceeded")
        default:
            log.Printf("API error: %v", apiErr)
        }
    } else {
        log.Printf("Network error: %v", err)
    }
    return
}

// Process successful result
fmt.Printf("Valid: %v\n", result.Valid)
Batch Verification
phoneNumbers := []string{
    "+1234567890",
    "+5511984339000", 
    "+244921204020",
}

for _, number := range phoneNumbers {
    result, err := client.Verify(checkhim.VerifyRequest{Number: number})
    if err != nil {
        log.Printf("Error verifying %s: %v", number, err)
        continue
    }
    
    fmt.Printf("%s: Valid=%v, Carrier=%s\n", 
        number, result.Valid, result.Carrier)
}

API Reference

Client
New(apiKey string, configs ...Config) *Client

Creates a new CheckHim client.

Parameters:

  • apiKey - Your CheckHim API key (required)
  • configs - Optional configuration (see Config struct)
Verify(req VerifyRequest) (*VerifyResponse, error)

Verifies a phone number.

VerifyWithContext(ctx context.Context, req VerifyRequest) (*VerifyResponse, error)

Verifies a phone number with context support.

Types
VerifyRequest
type VerifyRequest struct {
    Number string `json:"number"` // Phone number with country code (e.g., "+1234567890")
}
VerifyResponse
type VerifyResponse struct {
    Carrier string `json:"carrier"` // Mobile carrier name (e.g., "UNITEL")
    Valid   bool   `json:"valid"`   // Whether the number is valid
}
Config
type Config struct {
    BaseURL    string        // Custom API base URL
    Timeout    time.Duration // HTTP request timeout
    HTTPClient *http.Client  // Custom HTTP client
}
APIError
type APIError struct {
    StatusCode int                    // HTTP status code
    Message    string                 // Error message
    Code       string                 // Error code
    Details    map[string]interface{} // Additional error details
}

Error Codes

Common error codes returned by the API:

Code Description
unauthorized Invalid or missing API key
invalid_request Malformed request or missing required fields
rate_limit_exceeded Too many requests, please slow down
invalid_number Phone number format is invalid
insufficient_credits Account has insufficient credits
service_unavailable Temporary service unavailability

Configuration

Environment Variables

You can set default configuration using environment variables:

export CHECKHIM_API_KEY="your-api-key"
export CHECKHIM_BASE_URL="https://api.checkhim.tech"
export CHECKHIM_TIMEOUT="30s"
Custom HTTP Client
customHTTPClient := &http.Client{
    Timeout: 60 * time.Second,
    Transport: &http.Transport{
        MaxIdleConns:        100,
        MaxIdleConnsPerHost: 10,
        IdleConnTimeout:     90 * time.Second,
    },
}

client := checkhim.New("your-api-key", checkhim.Config{
    HTTPClient: customHTTPClient,
})

Testing

Run the test suite:

go test ./...

Run tests with coverage:

go test -race -coverprofile=coverage.out ./...
go tool cover -html=coverage.out

Run benchmarks:

go test -bench=. -benchmem

Examples

Check out the examples directory for more comprehensive usage examples:

  • Basic Usage - Complete example with various use cases

To run the examples:

cd examples
go mod tidy
go run main.go

Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup
  1. Fork the repository
  2. Clone your fork: git clone https://github.com/your-username/go-sdk.git
  3. Create a feature branch: git checkout -b feature/amazing-feature
  4. Make your changes and add tests
  5. Run tests: go test ./...
  6. Commit your changes: git commit -m 'Add amazing feature'
  7. Push to the branch: git push origin feature/amazing-feature
  8. Open a Pull Request
Code Style
  • Follow Go conventions and best practices
  • Use gofmt to format your code
  • Add tests for new functionality
  • Update documentation as needed

Support

Changelog

See CHANGELOG.md for version history and updates.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Security

If you discover a security vulnerability, please send an e-mail to security@checkhim.tech. All security vulnerabilities will be promptly addressed.


Made with ❤️ by the CheckHim team

Documentation

Overview

Package checkhim provides a Go SDK for phone number verification using the CheckHim API.

This SDK allows you to verify phone numbers by checking if they are valid and active. It provides a simple interface to interact with the CheckHim verification service.

Basic usage:

client := checkhim.New("your-api-key")
result, err := client.Verify(checkhim.VerifyRequest{
	Number: "+1234567890",
})
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Valid: %v, Carrier: %s\n", result.Valid, result.Carrier)

Index

Examples

Constants

View Source
const (
	// DefaultBaseURL is the default base URL for the CheckHim API
	DefaultBaseURL = "http://api.checkhim.tech"

	// DefaultTimeout is the default timeout for HTTP requests
	DefaultTimeout = 30 * time.Second

	// APIVersion is the current API version
	APIVersion = "v1"
)
View Source
const (
	ErrorCodeRejectedNetwork           = "REJECTED_NETWORK"
	ErrorCodeRejectedPrefixMissing     = "REJECTED_PREFIX_MISSING"
	ErrorCodeRejectedFormat            = "REJECTED_FORMAT"
	ErrorCodeRejectedSubscriberAbsent  = "REJECTED_SUBSCRIBER_ABSENT"
	ErrorCodeRejectedUnknownSubscriber = "REJECTED_UNKNOWN_SUBSCRIBER"
	ErrorCodeRejectedUndeliverable     = "REJECTED_UNDELIVERABLE"
	ErrorCodeUndeliverableNotDelivered = "UNDELIVERABLE_NOT_DELIVERED"
	ErrorCodeTemporaryFailure          = "TEMPORARY_FAILURE"
	ErrorCodeServiceUnavailable        = "SERVICE_UNAVAILABLE"
)

Códigos de erro (sandbox / produção)

View Source
const (
	DeliveryStatusDeliveredToHandset = "DELIVERED_TO_HANDSET"
)

Códigos de status de entrega (sucesso)

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
	Code       string
	Details    map[string]interface{}
}

APIError represents an API error

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface

func (*APIError) IsNetworkRelated

func (e *APIError) IsNetworkRelated() bool

IsNetworkRelated indica erros relacionados à rede/assinante

func (*APIError) IsNumberInvalid

func (e *APIError) IsNumberInvalid() bool

IsNumberInvalid indica erros de formato/prefixo/número inválido

func (*APIError) IsTemporary

func (e *APIError) IsTemporary() bool

IsTemporary indica se o erro é temporário e pode ser re-tentado

type Client

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

Client represents a CheckHim API client

func New

func New(apiKey string, configs ...Config) *Client

New creates a new CheckHim client with the provided API key

Example

Example tests that demonstrate usage

client := New("your-api-key")

result, err := client.Verify(VerifyRequest{
	Number: "+1234567890",
})
if err != nil {
	panic(err)
}

println(result.Valid, result.Carrier)

func (*Client) Verify

func (c *Client) Verify(req VerifyRequest) (*VerifyResponse, error)

Verify verifies a phone number using the CheckHim API

Example
client := New("your-api-key")

result, err := client.Verify(VerifyRequest{
	Number: "+5511984339000",
})
if err != nil {
	panic(err)
}

println(result.Valid, result.Carrier)

func (*Client) VerifyWithContext

func (c *Client) VerifyWithContext(ctx context.Context, req VerifyRequest) (*VerifyResponse, error)

VerifyWithContext verifies a phone number with a custom context

Example
client := New("your-api-key")

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

result, err := client.VerifyWithContext(ctx, VerifyRequest{
	Number: "+1234567890",
})
if err != nil {
	panic(err)
}

println(result.Valid, result.Carrier)

type Config

type Config struct {
	// BaseURL is the base URL for the CheckHim API (optional)
	BaseURL string

	// Timeout is the timeout for HTTP requests (optional)
	Timeout time.Duration

	// HTTPClient is a custom HTTP client (optional)
	HTTPClient *http.Client
}

Config holds configuration options for the Client

type ErrorResponse

type ErrorResponse struct {
	// Error is the error message
	Error string `json:"error"`

	// Code is the error code
	Code string `json:"code,omitempty"`

	// Details provides additional error details
	Details map[string]interface{} `json:"details,omitempty"`
}

ErrorResponse represents an error response from the API

type VerifyRequest

type VerifyRequest struct {
	// Number is the phone number to verify (required)
	// Should include country code (e.g., "+1234567890")
	Number string `json:"number"`
}

VerifyRequest represents a phone number verification request

type VerifyResponse

type VerifyResponse struct {
	// Carrier is the name of the mobile carrier
	Carrier string `json:"carrier"`

	// Valid indicates whether the phone number is valid and active
	Valid bool `json:"valid"`

	// Status (opcional) - quando disponível, ex: "DELIVERED_TO_HANDSET"
	Status string `json:"status,omitempty"`
}

VerifyResponse represents the response from a phone number verification

Jump to

Keyboard shortcuts

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