Path: blob/master/lib/remote/suppliers/numverify.go
994 views
package suppliers12import (3"encoding/json"4"errors"5"fmt"6"github.com/sirupsen/logrus"7"net/http"8)910type NumverifySupplierInterface interface {11Request() NumverifySupplierRequestInterface12}1314type NumverifySupplierRequestInterface interface {15SetApiKey(string) NumverifySupplierRequestInterface16ValidateNumber(string) (*NumverifyValidateResponse, error)17}1819type NumverifyErrorResponse struct {20Message string `json:"message"`21}2223// NumverifyValidateResponse REST API response24type NumverifyValidateResponse struct {25Valid bool `json:"valid"`26Number string `json:"number"`27LocalFormat string `json:"local_format"`28InternationalFormat string `json:"international_format"`29CountryPrefix string `json:"country_prefix"`30CountryCode string `json:"country_code"`31CountryName string `json:"country_name"`32Location string `json:"location"`33Carrier string `json:"carrier"`34LineType string `json:"line_type"`35}3637type NumverifySupplier struct {38Uri string39}4041func NewNumverifySupplier() *NumverifySupplier {42return &NumverifySupplier{43Uri: "https://api.apilayer.com",44}45}4647type NumverifyRequest struct {48apiKey string49uri string50}5152func (s *NumverifySupplier) Request() NumverifySupplierRequestInterface {53return &NumverifyRequest{uri: s.Uri}54}5556func (r *NumverifyRequest) SetApiKey(k string) NumverifySupplierRequestInterface {57r.apiKey = k58return r59}6061func (r *NumverifyRequest) ValidateNumber(internationalNumber string) (res *NumverifyValidateResponse, err error) {62logrus.63WithField("number", internationalNumber).64Debug("Running validate operation through Numverify API")6566url := fmt.Sprintf("%s/number_verification/validate?number=%s", r.uri, internationalNumber)6768// Build the request69client := &http.Client{}70req, _ := http.NewRequest("GET", url, nil)71req.Header.Set("Apikey", r.apiKey)7273response, err := client.Do(req)7475if err != nil {76return nil, err77}78defer response.Body.Close()7980// Fill the response with the data from the JSON81var result NumverifyValidateResponse8283if response.StatusCode >= 400 {84errorResponse := NumverifyErrorResponse{}85if err := json.NewDecoder(response.Body).Decode(&errorResponse); err != nil {86return nil, err87}88return nil, errors.New(errorResponse.Message)89}9091// Use json.Decode for reading streams of JSON data92if err := json.NewDecoder(response.Body).Decode(&result); err != nil {93return nil, err94}9596res = &NumverifyValidateResponse{97Valid: result.Valid,98Number: result.Number,99LocalFormat: result.LocalFormat,100InternationalFormat: result.InternationalFormat,101CountryPrefix: result.CountryPrefix,102CountryCode: result.CountryCode,103CountryName: result.CountryName,104Location: result.Location,105Carrier: result.Carrier,106LineType: result.LineType,107}108109return res, nil110}111112113