initial commit

This commit is contained in:
Patrick Nagurny
2018-10-19 15:31:41 -04:00
commit e2dd29259f
203 changed files with 44839 additions and 0 deletions

58
vendor/github.com/sendgrid/rest/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,58 @@
# Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## [2.4.1] - 2018-4-09
### Fixed
- Pull #71, Solves #70
- Fix Travis CI Build
- Special thanks to [Vasko Zdravevski](https://github.com/vaskoz) for the PR!
## [2.4.0] - 2017-4-10
### Added
- Pull #18, Solves #17
- Add RestError Struct for an error handling
- Special thanks to [Takahiro Ikeuchi](https://github.com/iktakahiro) for the PR!
## [2.3.1] - 2016-10-14
### Changed
- Pull #15, solves Issue #7
- Moved QueryParams processing into BuildRequestObject
- Special thanks to [Gábor Lipták](https://github.com/gliptak) for the PR!
## [2.3.0] - 2016-10-04
### Added
- Pull [#10] [Allow for custom Content-Types](https://github.com/sendgrid/rest/issues/10)
## [2.2.0] - 2016-07-28
### Added
- Pull [#9](https://github.com/sendgrid/rest/pull/9): Allow for setting a custom HTTP client
- [Here](https://github.com/sendgrid/rest/blob/master/rest_test.go#L127) is an example of usage
- This enables usage of the [sendgrid-go library](https://github.com/sendgrid/sendgrid-go) on [Google App Engine (GAE)](https://cloud.google.com/appengine/)
- Special thanks to [Chris Broadfoot](https://github.com/broady) and [Sridhar Venkatakrishnan](https://github.com/sridharv) for providing code and feedback!
## [2.1.0] - 2016-06-10
### Added
- Automatically add Content-Type: application/json when there is a request body
## [2.0.0] - 2016-06-03
### Changed
- Made the Request and Response variables non-redundant. e.g. request.RequestBody becomes request.Body
## [1.0.2] - 2016-04-07
### Added
- these changes are thanks to [deckarep](https://github.com/deckarep). Thanks!
- more updates to error naming convention
- more error handing on HTTP request
## [1.0.1] - 2016-04-07
### Added
- these changes are thanks to [deckarep](https://github.com/deckarep). Thanks!
- update error naming convention
- explicitly define supported HTTP verbs
- better error handing on HTTP request
## [1.0.0] - 2016-04-05
### Added
- We are live!

41
vendor/github.com/sendgrid/rest/CODE_OF_CONDUCT.md generated vendored Normal file
View File

@@ -0,0 +1,41 @@
# SendGrid Community Code of Conduct
The SendGrid open source community is made up of members from around the globe with a diverse set of skills, personalities, and experiences. It is through these differences that our community experiences successes and continued growth. When you're working with members of the community, we encourage you to follow these guidelines, which help steer our interactions and strive to maintain a positive, successful and growing community.
### Be Open
Members of the community are open to collaboration, whether it's on pull requests, code reviews, approvals, issues or otherwise. We're receptive to constructive comments and criticism, as the experiences and skill sets of all members contribute to the whole of our efforts. We're accepting of all who wish to take part in our activities, fostering an environment where anyone can participate, and everyone can make a difference.
### Be Considerate
Members of the community are considerate of their peers, which include other contributors and users of SendGrid. We're thoughtful when addressing the efforts of others, keeping in mind that often the labor was completed with the intent of the good of the community. We're attentive in our communications, whether in person or online, and we're tactful when approaching differing views.
### Be Respectful
Members of the community are respectful. We're respectful of others, their positions, their skills, their commitments and their efforts. We're respectful of the volunteer efforts that permeate the SendGrid community. We're respectful of the processes outlined in the community, and we work within them. When we disagree, we are courteous in raising our issues. Overall, we're good to each other. We contribute to this community not because we have to, but because we want to. If we remember that, these guidelines will come naturally.
## Additional Guidance
### Disclose Potential Conflicts of Interest
Community discussions often involve interested parties. We expect participants to be aware when they are conflicted due to employment or other projects they are involved in and disclose those interests to other project members. When in doubt, over-disclose. Perceived conflicts of interest are important to address so that the communitys decisions are credible even when unpopular, difficult or favorable to the interests of one group over another.
### Interpretation
This Code is not exhaustive or complete. It is not a rulebook; it serves to distill our common understanding of a collaborative, shared environment and goals. We expect it to be followed in spirit as much as in the letter. When in doubt, try to abide by [SendGrids cultural values](https://sendgrid.com/blog/employee-engagement-the-4h-way) defined by our “4Hs”: Happy, Hungry, Humble and Honest.
### Enforcement
Most members of the SendGrid community always comply with this Code, not because of the existence of this Code, but because they have long experience participating in open source communities where the conduct described above is normal and expected. However, failure to observe this Code may be grounds for suspension, reporting the user for abuse or changing permissions for outside contributors.
## If you have concerns about someones conduct
**Initiate Direct Contact** - It is always appropriate to email a community member (if contact information is available), mention that you think their behavior was out of line, and (if necessary) point them to this Code.
**Discuss Publicly** - Discussing publicly is always acceptable. Note, though, that approaching the person directly may be better, as it tends to make them less defensive, and it respects the time of other community members, so you probably want to try direct contact first.
**Contact the Moderators** - You can reach the SendGrid moderators by emailing dx@sendgrid.com.
## Submission to SendGrid Repositories
Finally, just a reminder, changes to the SendGrid repositories will only be accepted upon completion of the [SendGrid Contributor Agreement](https://cla.sendgrid.com).
## Attribution
SendGrid thanks the following, on which it draws for content and inspiration:
* [Python Community Code of Conduct](https://www.python.org/psf/codeofconduct/)
* [Open Source Initiative General Code of Conduct](https://opensource.org/codeofconduct)
* [Apache Code of Conduct](https://www.apache.org/foundation/policies/conduct.html)

185
vendor/github.com/sendgrid/rest/CONTRIBUTING.md generated vendored Normal file
View File

@@ -0,0 +1,185 @@
Hello! Thank you for choosing to help contribute to one of the SendGrid open source projects. There are many ways you can contribute and help is always welcome. We simply ask that you follow the following contribution policies.
- [CLAs and CCLAs](#cla)
- [Roadmap & Milestones](#roadmap)
- [Feature Request](#feature-request)
- [Submit a Bug Report](#submit-a-bug-report)
- [Improvements to the Codebase](#improvements-to-the-codebase)
- [Understanding the Code Base](#understanding-the-codebase)
- [Testing](#testing)
- [Style Guidelines & Naming Conventions](#style-guidelines-and-naming-conventions)
- [Creating a Pull Request](#creating-a-pull-request)
<a name="roadmap"></a>
We use [Milestones](https://github.com/sendgrid/rest/milestones) to help define current roadmaps, please feel free to grab an issue from the current milestone. Please indicate that you have begun work on it to avoid collisions. Once a PR is made, community review, comments, suggestions and additional PRs are welcomed and encouraged.
<a name="cla"></a>
## CLAs and CCLAs
Before you get started, SendGrid requires that a SendGrid Contributor License Agreement (CLA) be filled out by every contributor to a SendGrid open source project.
Our goal with the CLA is to clarify the rights of our contributors and reduce other risks arising from inappropriate contributions. The CLA also clarifies the rights SendGrid holds in each contribution and helps to avoid misunderstandings over what rights each contributor is required to grant to SendGrid when making a contribution. In this way the CLA encourages broad participation by our open source community and helps us build strong open source projects, free from any individual contributor withholding or revoking rights to any contribution.
SendGrid does not merge a pull request made against a SendGrid open source project until that pull request is associated with a signed CLA. Copies of the CLA are available [here](https://gist.github.com/SendGridDX/98b42c0a5d500058357b80278fde3be8#file-sendgrid-cla).
When you create a Pull Request, after a few seconds, a comment will appear with a link to the CLA. Click the link and fill out the brief form and then click the "I agree" button and you are all set. You will not be asked to re-sign the CLA unless we make a change.
There are a few ways to contribute, which we'll enumerate below:
<a name="feature-request"></a>
## Feature Request
If you'd like to make a feature request, please read this section.
The GitHub issue tracker is the preferred channel for library feature requests, but please respect the following restrictions:
- Please **search for existing issues** in order to ensure we don't have duplicate bugs/feature requests.
- Please be respectful and considerate of others when commenting on issues
<a name="submit-a-bug-report"></a>
## Submit a Bug Report
Note: DO NOT include your credentials in ANY code examples, descriptions, or media you make public.
A software bug is a demonstrable issue in the code base. In order for us to diagnose the issue and respond as quickly as possible, please add as much detail as possible into your bug report.
Before you decide to create a new issue, please try the following:
1. Check the Github issues tab if the identified issue has already been reported, if so, please add a +1 to the existing post.
2. Update to the latest version of this code and check if issue has already been fixed
3. Copy and fill in the Bug Report Template we have provided below
### Please use our Bug Report Template
In order to make the process easier, we've included a [sample bug report template](https://github.com/sendgrid/rest/.github/ISSUE_TEMPLATE) (borrowed from [Ghost](https://github.com/TryGhost/Ghost/)). The template uses [GitHub flavored markdown](https://help.github.com/articles/github-flavored-markdown/) for formatting.
<a name="improvements-to-the-codebase"></a>
## Improvements to the Codebase
We welcome direct contributions to the rest code base. Thank you!
### Development Environment ###
#### Install and Run Locally ####
##### Prerequisites #####
- Go version 1.6
##### Initial setup: #####
```bash
git clone https://github.com/sendgrid/rest.git
cd rest
```
##### Execute: #####
See the [examples folder](https://github.com/sendgrid/rest/tree/master/examples) to get started quickly.
If you want to try the SendGrid example:
First, get your free SendGrid account [here](https://sendgrid.com/free?source=rest).
You will need to setup the following environment to use the SendGrid example:
```
echo "export SENDGRID-API-KEY='YOUR-API-KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
go run examples/example.go
```
<a name="understanding-the-codebase"></a>
## Understanding the Code Base
**/examples**
Working examples that demonstrate usage.
**rest.go**
There is a struct to hold both the request and response to the API server.
The main function that does the heavy lifting (and external entry point) is `API`.
<a name="testing"></a>
## Testing
All PRs require passing tests before the PR will be reviewed.
All test files are in [`rest-test.go`](https://github.com/sendgrid/rest/blob/master/rest_test.go).
For the purposes of contributing to this repo, please update the [`rest-test.go`](https://github.com/sendgrid/rest/blob/master/rest_test.go) file with unit tests as you modify the code.
Run the test:
```bash
go test -v
```
<a name="style-guidelines-and-naming-conventions"></a>
## Style Guidelines & Naming Conventions
Generally, we follow the style guidelines as suggested by the official language. However, we ask that you conform to the styles that already exist in the library. If you wish to deviate, please explain your reasoning.
- [Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments)
Please run your code through:
- [fmt](https://blog.golang.org/go-fmt-your-code)
## Creating a Pull Request<a name="creating-a-pull-request"></a>
1. [Fork](https://help.github.com/fork-a-repo/) the project, clone your fork,
and configure the remotes:
```bash
# Clone your fork of the repo into the current directory
git clone https://github.com/sendgrid/rest
# Navigate to the newly cloned directory
cd rest
# Assign the original repo to a remote called "upstream"
git remote add upstream https://github.com/sendgrid/rest
```
2. If you cloned a while ago, get the latest changes from upstream:
```bash
git checkout <dev-branch>
git pull upstream <dev-branch>
```
3. Create a new topic branch (off the main project development branch) to
contain your feature, change, or fix:
```bash
git checkout -b <topic-branch-name>
```
4. Commit your changes in logical chunks. Please adhere to these [git commit
message guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
or your code is unlikely be merged into the main project. Use Git's
[interactive rebase](https://help.github.com/articles/interactive-rebase)
feature to tidy up your commits before making them public.
4a. Create tests.
4b. Create or update the example code that demonstrates the functionality of this change to the code.
5. Locally merge (or rebase) the upstream development branch into your topic branch:
```bash
git pull [--rebase] upstream master
```
6. Push your topic branch up to your fork:
```bash
git push origin <topic-branch-name>
```
7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/)
with a clear title and description against the `master` branch. All tests must be passing before we will review the PR.
If you have any additional questions, please feel free to [email](mailto:dx@sendgrid.com) us or create an issue in this repo.

21
vendor/github.com/sendgrid/rest/LICENSE.txt generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016-2018 SendGrid, 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.

162
vendor/github.com/sendgrid/rest/README.md generated vendored Normal file
View File

@@ -0,0 +1,162 @@
![SendGrid Logo](https://uiux.s3.amazonaws.com/2016-logos/email-logo%402x.png)
[![Build Status](https://travis-ci.org/sendgrid/rest.svg?branch=master)](https://travis-ci.org/sendgrid/rest)
[![GoDoc](https://godoc.org/github.com/sendgrid/rest?status.png)](http://godoc.org/github.com/sendgrid/rest)
[![Go Report Card](https://goreportcard.com/badge/github.com/sendgrid/rest)](https://goreportcard.com/report/github.com/sendgrid/rest)
[![Email Notifications Badge](https://dx.sendgrid.com/badge/go)](https://dx.sendgrid.com/newsletter/go)
[![Twitter Follow](https://img.shields.io/twitter/follow/sendgrid.svg?style=social&label=Follow)](https://twitter.com/sendgrid)
[![GitHub contributors](https://img.shields.io/github/contributors/sendgrid/rest.svg)](https://github.com/sendgrid/rest/graphs/contributors)
[![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE.txt)
**Quickly and easily access any RESTful or RESTful-like API.**
If you are looking for the SendGrid API client library, please see [this repo](https://github.com/sendgrid/sendgrid-go).
# Announcements
All updates to this library is documented in our [CHANGELOG](https://github.com/sendgrid/rest/blob/master/CHANGELOG.md).
# Table of Contents
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Usage](#usage)
- [Roadmap](#roadmap)
- [How to Contribute](#contribute)
- [About](#about)
- [License](#license)
<a name="installation"></a>
# Installation
## Prerequisites
- Go version 1.6.X, 1.7.X, 1.8.X, 1.9.X or 1.10.X
## Install Package
```bash
go get github.com/sendgrid/rest
```
## Setup Environment Variables
### Initial Setup
```bash
cp .env_sample .env
```
### Environment Variable
Update the development environment with your [SENDGRID_API_KEY](https://app.sendgrid.com/settings/api_keys), for example:
```bash
echo "export SENDGRID_API_KEY='YOUR_API_KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
```
<a name="quick-start"></a>
# Quick Start
`GET /your/api/{param}/call`
```go
package main
import "github.com/sendgrid/rest"
import "fmt"
func main() {
const host = "https://api.example.com"
param := "myparam"
endpoint := "/your/api/" + param + "/call"
baseURL := host + endpoint
method := rest.Get
request := rest.Request{
Method: method,
BaseURL: baseURL,
}
response, err := rest.Send(request)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(response.StatusCode)
fmt.Println(response.Body)
fmt.Println(response.Headers)
}
}
```
`POST /your/api/{param}/call` with headers, query parameters and a request body.
```go
package main
import "github.com/sendgrid/rest"
import "fmt"
func main() {
const host = "https://api.example.com"
param := "myparam"
endpoint := "/your/api/" + param + "/call"
baseURL := host + endpoint
Headers := make(map[string]string)
key := os.Getenv("API_KEY")
Headers["Authorization"] = "Bearer " + key
Headers["X-Test"] = "Test"
var Body = []byte(`{"some": 0, "awesome": 1, "data": 3}`)
queryParams := make(map[string]string)
queryParams["hello"] = "0"
queryParams["world"] = "1"
method := rest.Post
request = rest.Request{
Method: method,
BaseURL: baseURL,
Headers: Headers,
QueryParams: queryParams,
Body: Body,
}
response, err := rest.Send(request)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(response.StatusCode)
fmt.Println(response.Body)
fmt.Println(response.Headers)
}
}
```
<a name="usage"></a>
# Usage
- [Usage Examples](USAGE.md)
<a name="roadmap"></a>
# Roadmap
If you are interested in the future direction of this project, please take a look at our [milestones](https://github.com/sendgrid/rest/milestones). We would love to hear your feedback.
<a name="contribute"></a>
# How to Contribute
We encourage contribution to our projects, please see our [CONTRIBUTING](https://github.com/sendgrid/rest/blob/master/CONTRIBUTING.md) guide for details.
Quick links:
- [Feature Request](https://github.com/sendgrid/rest/blob/master/CONTRIBUTING.md#feature-request)
- [Bug Reports](https://github.com/sendgrid/rest/blob/master/CONTRIBUTING.md#submit-a-bug-report)
- [Sign the CLA to Create a Pull Request](https://github.com/sendgrid/rest/blob/master/CONTRIBUTING.md#cla)
- [Improvements to the Codebase](https://github.com/sendgrid/rest/blob/master/CONTRIBUTING.md#improvements-to-the-codebase)
<a name="about"></a>
# About
rest is guided and supported by the SendGrid [Developer Experience Team](mailto:dx@sendgrid.com).
rest is maintained and funded by SendGrid, Inc. The names and logos for rest are trademarks of SendGrid, Inc.
<a name="license"></a>
# License
[The MIT License (MIT)](LICENSE.txt)

62
vendor/github.com/sendgrid/rest/TROUBLESHOOTING.md generated vendored Normal file
View File

@@ -0,0 +1,62 @@
## Table of Contents
* [Viewing the Request Body](#request-body)
<a name="request-body"></a>
## Viewing the Request Body
When debugging or testing, it may be useful to exampine the raw request body to compare against the [documented format](https://sendgrid.com/docs/API_Reference/api_v3.html).
Example Code
```go
package main
import "github.com/sendgrid/rest"
import "fmt"
func main() {
const host = "https://api.example.com"
param := "myparam"
endpoint := "/your/api/" + param + "/call"
baseURL := host + endpoint
Headers := make(map[string]string)
key := os.Getenv("API_KEY")
Headers["Authorization"] = "Bearer " + key
Headers["X-Test"] = "Test"
var Body = []byte(`{"some": 0, "awesome": 1, "data": 3}`)
queryParams := make(map[string]string)
queryParams["hello"] = "0"
queryParams["world"] = "1"
method := rest.Post
request = rest.Request{
Method: method,
BaseURL: baseURL,
Headers: Headers,
QueryParams: queryParams,
Body: Body,
}
response, err := rest.API(request)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(response.StatusCode)
fmt.Println(response.Body)
fmt.Println(response.Headers)
}
}
```
You can do this right before you call
`response, err := rest.API(request)` like so:
```go
fmt.Printf("Request Body: %v \n", string(request.Body))
req, e := BuildRequestObject(request)
requestDump, err := httputil.DumpRequest(req, true)
if err != nil {
t.Errorf("Error : %v", err)
}
fmt.Printf("Request : %v \n", string(requestDump))
```

211
vendor/github.com/sendgrid/rest/USAGE.md generated vendored Normal file
View File

@@ -0,0 +1,211 @@
# Usage
Usage examples for SendGrid REST library
## Initialization
```go
package main
import (
"encoding/json"
"fmt"
"os"
"github.com/sendgrid/rest"
)
// Build the URL
const host = "https://api.sendgrid.com"
endpoint := "/v3/api_keys"
baseURL := host + endpoint
// Build the request headers
key := os.Getenv("SENDGRID_API_KEY")
Headers := make(map[string]string)
Headers["Authorization"] = "Bearer " + key
```
## Table of Contents
- [GET](#get)
- [DELETE](#delete)
- [POST](#post)
- [PUT](#put)
- [PATCH](#patch)
<a name="get"></a>
## GET
#### GET Single
```go
method = rest.Get
// Make the API call
request = rest.Request{
Method: method,
BaseURL: baseURL + "/" + apiKey,
Headers: Headers,
}
response, err = rest.API(request)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(response.StatusCode)
fmt.Println(response.Body)
fmt.Println(response.Headers)
}
```
#### GET Collection
```go
method := rest.Get
// Build the query parameters
queryParams := make(map[string]string)
queryParams["limit"] = "100"
queryParams["offset"] = "0"
// Make the API call
request := rest.Request{
Method: method,
BaseURL: baseURL,
Headers: Headers,
QueryParams: queryParams,
}
response, err := rest.API(request)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(response.StatusCode)
fmt.Println(response.Body)
fmt.Println(response.Headers)
}
```
<a name="delete"></a>
## DELETE
```go
method = rest.Delete
// Make the API call
request = rest.Request{
Method: method,
BaseURL: baseURL + "/" + apiKey,
Headers: Headers,
QueryParams: queryParams,
}
response, err = rest.API(request)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(response.StatusCode)
fmt.Println(response.Headers)
}
```
<a name="post"></a>
## POST
```go
method = rest.Post
// Build the request body
var Body = []byte(`{
"name": "My API Key",
"scopes": [
"mail.send",
"alerts.create",
"alerts.read"
]
}`)
// Make the API call
request = rest.Request{
Method: method,
BaseURL: baseURL,
Headers: Headers,
QueryParams: queryParams,
Body: Body,
}
response, err = rest.API(request)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(response.StatusCode)
fmt.Println(response.Body)
fmt.Println(response.Headers)
}
// Get a particular return value.
// Note that you can unmarshall into a struct if
// you know the JSON structure in advance.
b := []byte(response.Body)
var f interface{}
err = json.Unmarshal(b, &f)
if err != nil {
fmt.Println(err)
}
m := f.(map[string]interface{})
apiKey := m["api_key_id"].(string)
```
<a name="put"></a>
## PUT
```go
method = rest.Put
// Build the request body
Body = []byte(`{
"name": "A New Hope",
"scopes": [
"user.profile.read",
"user.profile.update"
]
}`)
// Make the API call
request = rest.Request{
Method: method,
BaseURL: baseURL + "/" + apiKey,
Headers: Headers,
Body: Body,
}
response, err = rest.API(request)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(response.StatusCode)
fmt.Println(response.Body)
fmt.Println(response.Headers)
}
```
<a name="patch"></a>
## PATCH
```go
method = rest.Patch
// Build the request body
Body = []byte(`{
"name": "A New Hope"
}`)
// Make the API call
request = rest.Request{
Method: method,
BaseURL: baseURL + "/" + apiKey,
Headers: Headers,
Body: Body,
}
response, err = rest.API(request)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(response.StatusCode)
fmt.Println(response.Body)
fmt.Println(response.Headers)
}
```

145
vendor/github.com/sendgrid/rest/rest.go generated vendored Normal file
View File

@@ -0,0 +1,145 @@
// Package rest allows for quick and easy access any REST or REST-like API.
package rest
import (
"bytes"
"io/ioutil"
"net/http"
"net/url"
)
// Method contains the supported HTTP verbs.
type Method string
// Supported HTTP verbs.
const (
Get Method = "GET"
Post Method = "POST"
Put Method = "PUT"
Patch Method = "PATCH"
Delete Method = "DELETE"
)
// Request holds the request to an API Call.
type Request struct {
Method Method
BaseURL string // e.g. https://api.sendgrid.com
Headers map[string]string
QueryParams map[string]string
Body []byte
}
// RestError is a struct for an error handling.
type RestError struct {
Response *Response
}
// Error is the implementation of the error interface.
func (e *RestError) Error() string {
return e.Response.Body
}
// DefaultClient is used if no custom HTTP client is defined
var DefaultClient = &Client{HTTPClient: http.DefaultClient}
// Client allows modification of client headers, redirect policy
// and other settings
// See https://golang.org/pkg/net/http
type Client struct {
HTTPClient *http.Client
}
// Response holds the response from an API call.
type Response struct {
StatusCode int // e.g. 200
Body string // e.g. {"result: success"}
Headers map[string][]string // e.g. map[X-Ratelimit-Limit:[600]]
}
// AddQueryParameters adds query parameters to the URL.
func AddQueryParameters(baseURL string, queryParams map[string]string) string {
baseURL += "?"
params := url.Values{}
for key, value := range queryParams {
params.Add(key, value)
}
return baseURL + params.Encode()
}
// BuildRequestObject creates the HTTP request object.
func BuildRequestObject(request Request) (*http.Request, error) {
// Add any query parameters to the URL.
if len(request.QueryParams) != 0 {
request.BaseURL = AddQueryParameters(request.BaseURL, request.QueryParams)
}
req, err := http.NewRequest(string(request.Method), request.BaseURL, bytes.NewBuffer(request.Body))
if err != nil {
return req, err
}
for key, value := range request.Headers {
req.Header.Set(key, value)
}
_, exists := req.Header["Content-Type"]
if len(request.Body) > 0 && !exists {
req.Header.Set("Content-Type", "application/json")
}
return req, err
}
// MakeRequest makes the API call.
func MakeRequest(req *http.Request) (*http.Response, error) {
return DefaultClient.HTTPClient.Do(req)
}
// BuildResponse builds the response struct.
func BuildResponse(res *http.Response) (*Response, error) {
body, err := ioutil.ReadAll(res.Body)
response := Response{
StatusCode: res.StatusCode,
Body: string(body),
Headers: res.Header,
}
res.Body.Close() // nolint
return &response, err
}
// API supports old implementation (deprecated)
func API(request Request) (*Response, error) {
return Send(request)
}
// Send uses the DefaultClient to send your request
func Send(request Request) (*Response, error) {
return DefaultClient.Send(request)
}
// The following functions enable the ability to define a
// custom HTTP Client
// MakeRequest makes the API call.
func (c *Client) MakeRequest(req *http.Request) (*http.Response, error) {
return c.HTTPClient.Do(req)
}
// API supports old implementation (deprecated)
func (c *Client) API(request Request) (*Response, error) {
return c.Send(request)
}
// Send will build your request, make the request, and build your response.
func (c *Client) Send(request Request) (*Response, error) {
// Build the HTTP request object.
req, err := BuildRequestObject(request)
if err != nil {
return nil, err
}
// Build the HTTP client and make the request.
res, err := c.MakeRequest(req)
if err != nil {
return nil, err
}
// Build Response object.
return BuildResponse(res)
}