Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
whoisxmlapi committed Sep 26, 2022
0 parents commit 933e100
Show file tree
Hide file tree
Showing 11 changed files with 1,065 additions and 0 deletions.
33 changes: 33 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: Test

on: [push, pull_request]

jobs:
test:
strategy:
matrix:
go-version: [1.17.x, 1.18.x]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: ${{ matrix.go-version }}

- name: Cache Go
uses: actions/cache@v3
with:
path: |
~/go/pkg/mod
~/.cache/go-build
key: ${{ runner.os }}-go-${{ matrix.go-version }}-${{ hashFiles('go.mod') }}
restore-keys: |
${{ runner.os }}-go-${{ matrix.go-version }}-
- name: Build
run: go build -v ./

- name: Test
run: go test -v ./
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2022 WHOIS API, Inc

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
105 changes: 105 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
[![reverse-ip-go license](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
[![reverse-ip-go made-with-Go](https://img.shields.io/badge/Made%20with-Go-1f425f.svg)](https://pkg.go.dev/github.com/whois-api-llc/reverse-ip-go)
[![reverse-ip-go test](https://github.com/whois-api-llc/reverse-ip-go/workflows/Test/badge.svg)](https://github.com/whois-api-llc/reverse-ip-go/actions/)

# Overview

The client library for
[Reverse IP/DNS API](https://dns-history.whoisxmlapi.com/)
in Go language.

The minimum go version is 1.17.

# Installation

The library is distributed as a Go module

```bash
go get github.com/whois-api-llc/reverse-ip-go
```

# Examples

Full API documentation available [here](https://dns-history.whoisxmlapi.com/api/documentation/making-requests)

You can find all examples in `example` directory.

## Create a new client

To start making requests you need the API Key.
You can find it on your profile page on [whoisxmlapi.com](https://whoisxmlapi.com/).
Using the API Key you can create Client.

Most users will be fine with `NewBasicClient` function.
```go
client := reverseip.NewBasicClient(apiKey)
```

If you want to set custom `http.Client` to use proxy then you can use `NewClient` function.
```go
transport := &http.Transport{Proxy: http.ProxyURL(proxyUrl)}

client := reverseip.NewClient(apiKey, reverseip.ClientParams{
HTTPClient: &http.Client{
Transport: transport,
Timeout: 20 * time.Second,
},
})
```

## Make basic requests

Reverse IP/DNS API lets you get a list of all domains associated with an IP address.

```go

// Make request to get a list of all domains by IP address as a model instance.
reverseIPResp, _, err := client.Get(ctx, []byte{8,8,8,8})
if err != nil {
log.Fatal(err)
}

for _, obj := range reverseIPResp.Result {
log.Println(obj.Name, obj.FirstSeen, obj.LastVisit)
}

// Make request to get raw data in XML.
resp, err := client.GetRaw(context.Background(), net.IP{1, 1, 1, 1},
reverseip.OptionOutputFormat("XML"))
if err != nil {
log.Fatal(err)
}

log.Println(string(resp.Body))

```
## Advanced usage

Pagination

```go

// Each response is limited to 300 records.
const limit = 300
from := "1"

for {
reverseIPResp, _, err := client.Get(context.Background(), []byte{8, 8, 8, 8},
// This option results in the next page is retrieved.
reverseip.OptionFrom(from))
if err != nil {
log.Fatal(err)
}

for _, obj := range reverseIPResp.Result {
log.Println(obj.Name)
}

// Break the loop when the last page is reached.
if reverseIPResp.Size < limit {
break
}
from = reverseIPResp.Result[reverseIPResp.Size-1].Name
}

```
143 changes: 143 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
package reverseip

import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
)

const (
libraryVersion = "1.0.0"
userAgent = "reverse-ip-go/" + libraryVersion
mediaType = "application/json"
)

// defaultReverseIPURL is the default Reverse IP/DNS API URL.
const defaultReverseIPURL = `https://dns-history.whoisxmlapi.com/api/v1`

// ClientParams is used to create Client. None of parameters are mandatory and
// leaving this struct empty works just fine for most cases.
type ClientParams struct {
// HTTPClient is the client used to access API endpoint
// If it's nil then value API client uses http.DefaultClient
HTTPClient *http.Client

// ReverseIPBaseURL is the endpoint for 'Reverse IP/DNS API' service
ReverseIPBaseURL *url.URL
}

// NewBasicClient creates Client with recommended parameters.
func NewBasicClient(apiKey string) *Client {
return NewClient(apiKey, ClientParams{})
}

// NewClient creates Client with specified parameters.
func NewClient(apiKey string, params ClientParams) *Client {
var err error

apiBaseURL := params.ReverseIPBaseURL
if apiBaseURL == nil {
apiBaseURL, err = url.Parse(defaultReverseIPURL)
if err != nil {
panic(err)
}
}

httpClient := http.DefaultClient
if params.HTTPClient != nil {
httpClient = params.HTTPClient
}

client := &Client{
client: httpClient,
userAgent: userAgent,
apiKey: apiKey,
}

client.ReverseIP = &reverseIPServiceOp{client: client, baseURL: apiBaseURL}

return client
}

// Client is the client for Reverse IP/DNS API services.
type Client struct {
client *http.Client

userAgent string
apiKey string

// ReverseIP is an interface for Reverse IP/DNS API
ReverseIP
}

// NewRequest creates a basic API request.
func (c *Client) NewRequest(method string, u *url.URL, body io.Reader) (*http.Request, error) {
var err error

var req *http.Request

req, err = http.NewRequest(method, u.String(), body)
if err != nil {
return nil, err
}

req.Header.Add("Content-Type", mediaType)
req.Header.Add("Accept", mediaType)
req.Header.Add("User-Agent", c.userAgent)

return req, nil
}

// Do sends the API request and returns the API response.
func (c *Client) Do(ctx context.Context, req *http.Request, v io.Writer) (response *http.Response, err error) {
req = req.WithContext(ctx)

resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("cannot execute request: %w", err)
}

defer func() {
if rerr := resp.Body.Close(); err == nil && rerr != nil {
err = fmt.Errorf("cannot close response: %w", rerr)
}
}()

_, err = io.Copy(v, resp.Body)
if err != nil {
return resp, fmt.Errorf("cannot read response: %w", err)
}

return resp, err
}

// ErrorResponse is returned when the response status code is not 2xx.
type ErrorResponse struct {
Response *http.Response
Message string
}

// Error returns error message as a string.
func (e *ErrorResponse) Error() string {
if e.Message != "" {
return "API failed with status code: " + strconv.Itoa(e.Response.StatusCode) + " (" + e.Message + ")"
}

return "API failed with status code: " + strconv.Itoa(e.Response.StatusCode)
}

// checkResponse checks if the response status code is not 2xx.
func checkResponse(r *http.Response) error {
if c := r.StatusCode; c >= 200 && c <= 299 {
return nil
}

var errorResponse = ErrorResponse{
Response: r,
}

return &errorResponse
}
Loading

0 comments on commit 933e100

Please sign in to comment.