pax_global_header 0000666 0000000 0000000 00000000064 14212206142 0014504 g ustar 00root root 0000000 0000000 52 comment=e57bc908da6d0fce76457392c6c8444031032ff4
rest-2.6.9/ 0000775 0000000 0000000 00000000000 14212206142 0012477 5 ustar 00root root 0000000 0000000 rest-2.6.9/.env_sample 0000664 0000000 0000000 00000000032 14212206142 0014624 0 ustar 00root root 0000000 0000000 export SENDGRID_API_KEY='' rest-2.6.9/.github/ 0000775 0000000 0000000 00000000000 14212206142 0014037 5 ustar 00root root 0000000 0000000 rest-2.6.9/.github/ISSUE_TEMPLATE/ 0000775 0000000 0000000 00000000000 14212206142 0016222 5 ustar 00root root 0000000 0000000 rest-2.6.9/.github/ISSUE_TEMPLATE/config.yml 0000664 0000000 0000000 00000000555 14212206142 0020217 0 ustar 00root root 0000000 0000000 contact_links:
- name: Twilio SendGrid Support
url: https://support.sendgrid.com
about: Get Support
- name: Stack Overflow
url: https://stackoverflow.com/questions/tagged/rest+or+sendgrid+go
about: Ask questions on Stack Overflow
- name: Documentation
url: https://sendgrid.com/docs/for-developers/
about: View Reference Documentation
rest-2.6.9/.github/workflows/ 0000775 0000000 0000000 00000000000 14212206142 0016074 5 ustar 00root root 0000000 0000000 rest-2.6.9/.github/workflows/test.yml 0000664 0000000 0000000 00000004225 14212206142 0017601 0 ustar 00root root 0000000 0000000 name: Test and Deploy
on:
push:
branches: [ '*' ]
tags: [ '*' ]
pull_request:
branches: [ main ]
schedule:
# Run automatically at 8AM PST Monday-Friday
- cron: '0 15 * * 1-5'
workflow_dispatch:
jobs:
test:
name: Build & Test
runs-on: ubuntu-latest
timeout-minutes: 20
strategy:
matrix:
go: [ '1.14', '1.15', '1.16', '1.17' ]
steps:
- name: Checkout rest
uses: actions/checkout@v2
- name: Setup Go environment
uses: actions/setup-go@v2
with:
go-version: ${{ matrix.go }}
- name: Set Go env vars
run: |
echo "GOPATH=$HOME" >> $GITHUB_ENV
echo "GOBIN=$HOME/bin" >> $GITHUB_ENV
echo "GO111MODULE=off" >> $GITHUB_ENV
- name: Run Tests
run: make test
deploy:
name: Deploy
if: success() && github.ref_type == 'tag'
needs: [ test ]
runs-on: ubuntu-latest
steps:
- name: Checkout rest
uses: actions/checkout@v2
- name: Create GitHub Release
uses: sendgrid/dx-automator/actions/release@main
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Submit metric to Datadog
uses: sendgrid/dx-automator/actions/datadog-release-metric@main
env:
DD_API_KEY: ${{ secrets.DATADOG_API_KEY }}
notify-on-failure:
name: Slack notify on failure
if: failure() && github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.ref_type == 'tag')
needs: [ test, deploy ]
runs-on: ubuntu-latest
steps:
- uses: rtCamp/action-slack-notify@v2
env:
SLACK_COLOR: failure
SLACK_ICON_EMOJI: ':github:'
SLACK_MESSAGE: ${{ format('Test *{0}*, Deploy *{1}*, {2}/{3}/actions/runs/{4}', needs.test.result, needs.deploy.result, github.server_url, github.repository, github.run_id) }}
SLACK_TITLE: Action Failure - ${{ github.repository }}
SLACK_USERNAME: GitHub Actions
SLACK_MSG_AUTHOR: twilio-dx
SLACK_FOOTER: Posted automatically using GitHub Actions
SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
MSG_MINIMAL: true
rest-2.6.9/.gitignore 0000664 0000000 0000000 00000000447 14212206142 0014474 0 ustar 00root root 0000000 0000000 # Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof
.env
.settings.json
temp.go
rest-2.6.9/CHANGELOG.md 0000664 0000000 0000000 00000015107 14212206142 0014314 0 ustar 00root root 0000000 0000000 # Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
[2022-03-09] Version 2.6.9
--------------------------
**Library - Chore**
- [PR #110](https://github.com/sendgrid/rest/pull/110): push Datadog Release Metric upon deploy success. Thanks to [@eshanholtz](https://github.com/eshanholtz)!
[2022-02-09] Version 2.6.8
--------------------------
**Library - Chore**
- [PR #109](https://github.com/sendgrid/rest/pull/109): upgrade supported language versions. Thanks to [@childish-sambino](https://github.com/childish-sambino)!
- [PR #108](https://github.com/sendgrid/rest/pull/108): add gh release to workflow. Thanks to [@shwetha-manvinkurke](https://github.com/shwetha-manvinkurke)!
[2022-01-12] Version 2.6.7
--------------------------
**Library - Chore**
- [PR #107](https://github.com/sendgrid/rest/pull/107): update license year. Thanks to [@JenniferMah](https://github.com/JenniferMah)!
[2021-12-15] Version 2.6.6
--------------------------
**Library - Chore**
- [PR #106](https://github.com/sendgrid/rest/pull/106): migrate to gh actions. Thanks to [@beebzz](https://github.com/beebzz)!
[2021-09-22] Version 2.6.5
--------------------------
**Library - Chore**
- [PR #105](https://github.com/sendgrid/rest/pull/105): add tests against v1.16. Thanks to [@shwetha-manvinkurke](https://github.com/shwetha-manvinkurke)!
[2021-05-05] Version 2.6.4
--------------------------
**Library - Chore**
- [PR #103](https://github.com/sendgrid/rest/pull/103): follow up context.Context support. Thanks to [@johejo](https://github.com/johejo)!
[2021-03-15] Version 2.6.3
--------------------------
**Library - Fix**
- [PR #92](https://github.com/sendgrid/rest/pull/92): add SendWithContext function. Thanks to [@someone1](https://github.com/someone1)!
[2020-10-14] Version 2.6.2
--------------------------
**Library - Fix**
- [PR #101](https://github.com/sendgrid/rest/pull/101): Pass empty client instead of http.DefaultClient. Thanks to [@mateorider](https://github.com/mateorider)!
[2020-08-19] Version 2.6.1
--------------------------
**Library - Chore**
- [PR #100](https://github.com/sendgrid/rest/pull/100): update GitHub branch references to use HEAD. Thanks to [@thinkingserious](https://github.com/thinkingserious)!
[2020-02-19] Version 2.6.0
--------------------------
**Library - Feature**
- [PR #73](https://github.com/sendgrid/rest/pull/73): Dockerize sendgrid/rest. Thanks to [@graystevens](https://github.com/graystevens)!
[2020-02-05] Version 2.5.1
--------------------------
**Library - Docs**
- [PR #77](https://github.com/sendgrid/rest/pull/77): Run Grammarly on *.md files. Thanks to [@obahareth](https://github.com/obahareth)!
- [PR #86](https://github.com/sendgrid/rest/pull/86): Fixed link to bug report template. Thanks to [@alxshelepenok](https://github.com/alxshelepenok)!
[2020-01-30] Version 2.5.0
--------------------------
**Library - Docs**
- [PR #97](https://github.com/sendgrid/rest/pull/97): baseline all the templated markdown docs. Thanks to [@childish-sambino](https://github.com/childish-sambino)!
- [PR #88](https://github.com/sendgrid/rest/pull/88): add our Developer Experience Engineer career opportunity to the README. Thanks to [@mptap](https://github.com/mptap)!
- [PR #65](https://github.com/sendgrid/rest/pull/65): added "Code Review" section to CONTRIBUTING.md. Thanks to [@aleien](https://github.com/aleien)!
- [PR #80](https://github.com/sendgrid/rest/pull/80): add first timers guide for newcomers. Thanks to [@daniloff200](https://github.com/daniloff200)!
- [PR #82](https://github.com/sendgrid/rest/pull/82): update contribution guide with new workflow. Thanks to [@radlinskii](https://github.com/radlinskii)!
- [PR #62](https://github.com/sendgrid/rest/pull/62): update CONTRIBUTING.md with environment variables section. Thanks to [@thepriefy](https://github.com/thepriefy)!
**Library - Chore**
- [PR #96](https://github.com/sendgrid/rest/pull/96): prep repo for automation. Thanks to [@thinkingserious](https://github.com/thinkingserious)!
- [PR #94](https://github.com/sendgrid/rest/pull/94): add current Go version to Travis. Thanks to [@pangaunn](https://github.com/pangaunn)!
- [PR #93](https://github.com/sendgrid/rest/pull/93): add current Go versions to Travis. Thanks to [@gliptak](https://github.com/gliptak)!
- [PR #83](https://github.com/sendgrid/rest/pull/83): follow godoc deprecation standards. Thanks to [@vaskoz](https://github.com/vaskoz)!
- [PR #74](https://github.com/sendgrid/rest/pull/74): create README.md in use-cases. Thanks to [@ajloria](https://github.com/ajloria)!
**Library - Feature**
- [PR #72](https://github.com/sendgrid/rest/pull/72): do not swallow the error code. Thanks to [@Succo](https://github.com/Succo)!
[2018-04-09] Version 2.4.1
--------------------------
### 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](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 handling on HTTP request
## [1.0.0] - 2016-04-05
### Added
- We are live!
rest-2.6.9/CODE_OF_CONDUCT.md 0000664 0000000 0000000 00000006263 14212206142 0015305 0 ustar 00root root 0000000 0000000 # Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or
advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at open-source@twilio.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
rest-2.6.9/CONTRIBUTING.md 0000664 0000000 0000000 00000013471 14212206142 0014736 0 ustar 00root root 0000000 0000000 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.
- [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)
- [Code Reviews](#code-reviews)
## 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
## 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](ISSUE_TEMPLATE.md).
## Improvements to the Codebase
We welcome direct contributions to the rest code base. Thank you!
### Development Environment ###
#### Install and Run Locally ####
##### Supported Versions #####
- Go version 1.14, 1.15 or 1.16
##### Initial setup: #####
```bash
git clone https://github.com/sendgrid/rest.git
cd rest
```
### Environment Variables
First, get your free SendGrid account [here](https://sendgrid.com/free?source=rest).
Next, update your environment with your [SENDGRID_API_KEY](https://app.sendgrid.com/settings/api_keys) if you will test with Swift Mailer.
```
echo "export SENDGRID-API-KEY='YOUR-API-KEY'" > sendgrid.env
echo "sendgrid.env" >> .gitignore
source ./sendgrid.env
go run examples/example.go
```
##### Execute: #####
See the [examples folder](examples) to get started quickly.
## 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`.
## Testing
All PRs require passing tests before the PR will be reviewed.
All test files are in [`rest-test.go`](rest_test.go).
For the purposes of contributing to this repo, please update the [`rest-test.go`](rest_test.go) file with unit tests as you modify the code.
Run the test:
```bash
go test -v
```
## 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
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 development
git pull upstream development
```
3. Create a new topic branch off the `development` branch to
contain your feature, change, or fix:
```bash
git checkout -b
```
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 to 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 development
```
6. Push your topic branch up to your fork:
```bash
git push origin
```
7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/)
with a clear title and description against the `development` branch. All tests must be passing before we will review the PR.
## Code Reviews
If you can, please look at open PRs and review them. Give feedback and help us merge these PRs much faster! If you don't know how, Github has some great [information on how to review a Pull Request](https://help.github.com/articles/about-pull-request-reviews/).
rest-2.6.9/FIRST_TIMERS.md 0000664 0000000 0000000 00000015124 14212206142 0014776 0 ustar 00root root 0000000 0000000 # How To Contribute to Twilio SendGrid Repositories via GitHub
Contributing to the Twilio SendGrid repositories is easy! All you need to do is find an open issue (see the bottom of this page for a list of repositories containing open issues), fix it and submit a pull request. Once you have submitted your pull request, the team can easily review it before it is merged into the repository.
To make a pull request, follow these steps:
1. Log into GitHub. If you do not already have a GitHub account, you will have to create one in order to submit a change. Click the Sign up link in the upper right-hand corner to create an account. Enter your username, password, and email address. If you are an employee of Twilio SendGrid, please use your full name with your GitHub account and enter Twilio SendGrid as your company so we can easily identify you.
2. __[Fork](https://help.github.com/fork-a-repo/)__ the [rest](https://github.com/sendgrid/rest) repository:
3. __Clone__ your fork via the following commands:
```bash
# Clone your fork of the repo into the current directory
git clone https://github.com/your_username/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
```
> Don't forget to replace *your_username* in the URL by your real GitHub username.
4. __Create a new topic branch__ (off the main project development branch) to contain your feature, change, or fix:
```bash
git checkout -b
```
5. __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. Probably you will also have to create tests (if needed) or create or update the example code that demonstrates the functionality of this change to the code.
6. __Locally merge (or rebase)__ the upstream development branch into your topic branch:
```bash
git pull [--rebase] upstream main
```
7. __Push__ your topic branch up to your fork:
```bash
git push origin
```
8. __[Open a Pull Request](https://help.github.com/articles/creating-a-pull-request/#changing-the-branch-range-and-destination-repository/)__ with a clear title and description against the `main` branch. All tests must be passing before we will review the PR.
## Important notice
Before creating a pull request, make sure that you respect the repository's constraints regarding contributions. You can find them in the [CONTRIBUTING.md](CONTRIBUTING.md) file.
## Repositories with Open, Easy, Help Wanted, Issue Filters
* [Python SDK](https://github.com/sendgrid/sendgrid-python/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [PHP SDK](https://github.com/sendgrid/sendgrid-php/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [C# SDK](https://github.com/sendgrid/sendgrid-csharp/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [Ruby SDK](https://github.com/sendgrid/sendgrid-ruby/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [Node.js SDK](https://github.com/sendgrid/sendgrid-nodejs/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [Java SDK](https://github.com/sendgrid/sendgrid-java/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [Go SDK](https://github.com/sendgrid/sendgrid-go/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [Python SMTPAPI Client](https://github.com/sendgrid/smtpapi-python/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [PHP SMTPAPI Client](https://github.com/sendgrid/smtpapi-php/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [C# SMTPAPI Client](https://github.com/sendgrid/smtpapi-csharp/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [Ruby SMTPAPI Client](https://github.com/sendgrid/smtpapi-ruby/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [Node.js SMTPAPI Client](https://github.com/sendgrid/smtpapi-nodejs/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [Java SMTPAPI Client](https://github.com/sendgrid/smtpapi-java/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [Go SMTPAPI Client](https://github.com/sendgrid/smtpapi-go/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [Python HTTP Client](https://github.com/sendgrid/python-http-client/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [PHP HTTP Client](https://github.com/sendgrid/php-http-client/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [C# HTTP Client](https://github.com/sendgrid/csharp-http-client/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [Java HTTP Client](https://github.com/sendgrid/java-http-client/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [Ruby HTTP Client](https://github.com/sendgrid/ruby-http-client/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [Go HTTP Client](https://github.com/sendgrid/rest/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [Open API Definition](https://github.com/sendgrid/sendgrid-oai/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [DX Automator](https://github.com/sendgrid/dx-automator/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
* [Documentation](https://github.com/sendgrid/docs/issues?utf8=%E2%9C%93&q=is%3Aopen+label%3A%22difficulty%3A+easy%22+label%3A%22status%3A+help+wanted%22)
rest-2.6.9/ISSUE_TEMPLATE.md 0000664 0000000 0000000 00000001332 14212206142 0015203 0 ustar 00root root 0000000 0000000
### Issue Summary
A summary of the issue and the environment in which it occurs. If suitable, include the steps required to reproduce the bug. Please feel free to include screenshots, screencasts, or code examples.
### Steps to Reproduce
1. This is the first step
2. This is the second step
3. Further steps, etc.
### Code Snippet
```go
# paste code here
```
### Exception/Log
```
# paste exception/log here
```
### Technical details:
* rest version:
* go version:
rest-2.6.9/LICENSE 0000664 0000000 0000000 00000002111 14212206142 0013477 0 ustar 00root root 0000000 0000000 MIT License
Copyright (C) 2022, Twilio 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.
rest-2.6.9/Makefile 0000664 0000000 0000000 00000000141 14212206142 0014133 0 ustar 00root root 0000000 0000000 .PHONY: test install
install:
go get -t -v ./...
test: install
go test -race -cover -v ./...
rest-2.6.9/PULL_REQUEST_TEMPLATE.md 0000664 0000000 0000000 00000003142 14212206142 0016300 0 ustar 00root root 0000000 0000000
# Fixes #
A short description of what this PR does.
### Checklist
- [x] I acknowledge that all my contributions will be made under the project's license
- [ ] I have made a material change to the repo (functionality, testing, spelling, grammar)
- [ ] I have read the [Contribution Guidelines](https://github.com/sendgrid/rest/blob/main/CONTRIBUTING.md) and my PR follows them
- [ ] I have titled the PR appropriately
- [ ] I have updated my branch with the main branch
- [ ] I have added tests that prove my fix is effective or that my feature works
- [ ] I have added the necessary documentation about the functionality in the appropriate .md file
- [ ] I have added inline documentation to the code I modified
If you have questions, please file a [support ticket](https://support.sendgrid.com), or create a GitHub Issue in this repository.
rest-2.6.9/README.md 0000664 0000000 0000000 00000013700 14212206142 0013757 0 ustar 00root root 0000000 0000000 
[](https://github.com/sendgrid/rest/actions/workflows/test.yml)
[](http://godoc.org/github.com/sendgrid/rest)
[](https://goreportcard.com/report/github.com/sendgrid/rest)
[](https://twitter.com/sendgrid)
[](https://github.com/sendgrid/rest/graphs/contributors)
[](LICENSE)
**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
**The default branch name for this repository has been changed to `main` as of 07/27/2020.**
All updates to this library is documented in our [CHANGELOG](CHANGELOG.md).
# Table of Contents
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Usage](#usage)
- [How to Contribute](#contribute)
- [About](#about)
- [License](#license)
# Installation
## Supported Versions
This library supports the following Go implementations:
* Go 1.14
* Go 1.15
* Go 1.16
* Go 1.17
## 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
```
## With Docker
A Docker image has been created to allow you to get started with `rest` right away.
```bash
docker-compose up -d --build
# Ensure the container is running with 'docker ps'
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
40c8d984a620 rest_go "tail -f /dev/null" About a minute ago Up About a minute rest_go_1
```
With the container running, you can execute your local `go` scripts using the following:
```bash
# docker exec
docker exec rest_go_1 go run docker/example.go
200
{
"args": {},
"headers": {
"Accept-Encoding": "gzip",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "Go-http-client/1.1"
},
"origin": "86.180.177.202",
"url": "https://httpbin.org/get"
}
map[Access-Control-Allow-Origin:[*] Access-Control-Allow-Credentials:[true] Via:[1.1 vegur] Connection:[keep-alive] Server:[gunicorn/19.9.0] Date:[Tue, 02 Oct 2018 18:20:43 GMT] Content-Type:[application/json] Content-Length:[233]]
# You can install libraries too, using the same command
# NOTE: Any libraries installed will be removed when the container is stopped.
docker exec rest_go_1 go get github.com/uniplaces/carbon
```
Your go files will be executed relative to the root of this directory. So in the example above, to execute the `example.go` file within the `docker` directory, we run `docker exec rest_go_1 go run docker/example.go`. If this file was in the root of this repository (next to README.exe, rest.go etc.), you would run `docker exec rest_go_1 go run my_go_script.go`
# 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)
}
}
```
# Usage
- [Usage Examples](USAGE.md)
# How to Contribute
We encourage contribution to our projects, please see our [CONTRIBUTING](CONTRIBUTING.md) guide for details.
Quick links:
- [Feature Request](CONTRIBUTING.md#feature-request)
- [Bug Reports](CONTRIBUTING.md#submit-a-bug-report)
- [Improvements to the Codebase](CONTRIBUTING.md#improvements-to-the-codebase)
- [Code Reviews](CONTRIBUTING.md#code-reviews)
# About
rest is maintained and funded by Twilio SendGrid, Inc. The names and logos for rest are trademarks of Twilio SendGrid, Inc.
If you need help installing or using the library, please check the [Twilio SendGrid Support Help Center](https://support.sendgrid.com).
If you've instead found a bug in the library or would like new features added, go ahead and open issues or pull requests against this repo!
# License
[The MIT License (MIT)](LICENSE)
rest-2.6.9/TROUBLESHOOTING.md 0000664 0000000 0000000 00000002753 14212206142 0015317 0 ustar 00root root 0000000 0000000 ## Table of Contents
* [Viewing the Request Body](#request-body)
## Viewing the Request Body
When debugging or testing, it may be useful to examine 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))
``` rest-2.6.9/USAGE.md 0000664 0000000 0000000 00000007042 14212206142 0013670 0 ustar 00root root 0000000 0000000 # 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)
## 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)
}
```
## 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)
}
```
## 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)
```
## 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)
}
```
## 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)
}
``` rest-2.6.9/docker-compose.yml 0000664 0000000 0000000 00000000116 14212206142 0016132 0 ustar 00root root 0000000 0000000 version: '3'
services:
go:
build: ./docker/
volumes:
- ./:/app
rest-2.6.9/docker/ 0000775 0000000 0000000 00000000000 14212206142 0013746 5 ustar 00root root 0000000 0000000 rest-2.6.9/docker/Dockerfile 0000664 0000000 0000000 00000000424 14212206142 0015740 0 ustar 00root root 0000000 0000000 FROM golang:1.11
VOLUME ["/app"]
WORKDIR /app
# Get sendgrid-go
RUN mkdir -p /go/src/github.com/sendgrid && \
cd /go/src/github.com/sendgrid && \
git clone https://www.github.com/sendgrid/rest && \
cd rest && \
go get
ENTRYPOINT ["tail", "-f", "/dev/null"]
rest-2.6.9/docker/example.go 0000664 0000000 0000000 00000001012 14212206142 0015722 0 ustar 00root root 0000000 0000000 package main
import "github.com/sendgrid/rest"
import "fmt"
func main() {
const host = "https://httpbin.org"
param := "get"
endpoint := "/" + param
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)
}
}
rest-2.6.9/examples/ 0000775 0000000 0000000 00000000000 14212206142 0014315 5 ustar 00root root 0000000 0000000 rest-2.6.9/examples/example.go 0000664 0000000 0000000 00000006267 14212206142 0016312 0 ustar 00root root 0000000 0000000 package main
import (
"encoding/json"
"fmt"
"os"
"github.com/sendgrid/rest"
)
func main() {
// 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
// GET Collection
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.Send(request)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(response.StatusCode)
fmt.Println(response.Body)
fmt.Println(response.Headers)
}
// POST
method = rest.Post
var Body = []byte(` {
"name": "My API Key",
"scopes": [
"mail.send",
"alerts.create",
"alerts.read"
]
}`)
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)
}
// 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)
// GET Single
method = rest.Get
// Make the API call
request = rest.Request{
Method: method,
BaseURL: baseURL + "/" + apiKey,
Headers: Headers,
}
response, err = rest.Send(request)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(response.StatusCode)
fmt.Println(response.Body)
fmt.Println(response.Headers)
}
// PATCH
method = rest.Patch
Body = []byte(`{
"name": "A New Hope"
}`)
request = rest.Request{
Method: method,
BaseURL: baseURL + "/" + apiKey,
Headers: Headers,
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)
}
// PUT
method = rest.Put
Body = []byte(`{
"name": "A New Hope",
"scopes": [
"user.profile.read",
"user.profile.update"
]
}`)
request = rest.Request{
Method: method,
BaseURL: baseURL + "/" + apiKey,
Headers: Headers,
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)
}
// DELETE
method = rest.Delete
request = rest.Request{
Method: method,
BaseURL: baseURL + "/" + apiKey,
Headers: Headers,
QueryParams: queryParams,
}
response, err = rest.Send(request)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(response.StatusCode)
fmt.Println(response.Headers)
}
}
rest-2.6.9/rest.go 0000664 0000000 0000000 00000010534 14212206142 0014006 0 ustar 00root root 0000000 0000000 // Package rest allows for quick and easy access any REST or REST-like API.
package rest
import (
"bytes"
"context"
"io/ioutil"
"net/http"
"net/url"
)
// Version represents the current version of the rest library
const Version = "2.6.9"
// 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.Client{}}
// 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
}
// Deprecated: API supports old implementation
func API(request Request) (*Response, error) {
return Send(request)
}
// Send uses the DefaultClient to send your request
func Send(request Request) (*Response, error) {
return SendWithContext(context.Background(), request)
}
// SendWithContext uses the DefaultClient to send your request with the provided context.
func SendWithContext(ctx context.Context, request Request) (*Response, error) {
return DefaultClient.SendWithContext(ctx, 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)
}
// Deprecated: API supports old implementation
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) {
return c.SendWithContext(context.Background(), request)
}
// SendWithContext will build your request passing in the provided context, make the request, and build your response.
func (c *Client) SendWithContext(ctx context.Context, request Request) (*Response, error) {
// Build the HTTP request object.
req, err := BuildRequestObject(request)
if err != nil {
return nil, err
}
// Pass in the user provided context
req = req.WithContext(ctx)
// 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)
}
rest-2.6.9/rest_test.go 0000664 0000000 0000000 00000021164 14212206142 0015046 0 ustar 00root root 0000000 0000000 package rest
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/http/httputil"
"os"
"regexp"
"strings"
"testing"
"time"
"golang.org/x/net/context"
)
func TestBuildURL(t *testing.T) {
t.Parallel()
host := "http://api.test.com"
queryParams := make(map[string]string)
queryParams["test"] = "1"
queryParams["test2"] = "2"
testURL := AddQueryParameters(host, queryParams)
if testURL != "http://api.test.com?test=1&test2=2" {
t.Error("Bad BuildURL result")
}
}
func TestBuildRequest(t *testing.T) {
t.Parallel()
method := Get
baseURL := "http://api.test.com"
key := "API_KEY"
Headers := make(map[string]string)
Headers["Content-Type"] = "application/json"
Headers["Authorization"] = "Bearer " + key
queryParams := make(map[string]string)
queryParams["test"] = "1"
queryParams["test2"] = "2"
request := Request{
Method: method,
BaseURL: baseURL,
Headers: Headers,
QueryParams: queryParams,
}
req, e := BuildRequestObject(request)
if e != nil {
t.Errorf("Rest failed to BuildRequest. Returned error: %v", e)
}
if req == nil {
t.Errorf("Failed to BuildRequest.")
}
//Start PrintRequest
requestDump, err := httputil.DumpRequest(req, true)
if err != nil {
t.Errorf("Error : %v", err)
}
fmt.Println("Request : ", string(requestDump))
//End Print Request
}
func TestBuildBadRequest(t *testing.T) {
t.Parallel()
request := Request{
Method: Method("@"),
}
req, e := BuildRequestObject(request)
if e == nil {
t.Errorf("Expected an error for a bad HTTP Method")
}
if req != nil {
t.Errorf("If there's an error there shouldn't be a Request.")
}
}
func TestBuildBadAPI(t *testing.T) {
t.Parallel()
request := Request{
Method: Method("@"),
}
res, e := API(request)
if e == nil {
t.Errorf("Expected an error for a bad HTTP Method")
}
if res != nil {
t.Errorf("If there's an error there shouldn't be a Response.")
}
}
func TestBuildResponse(t *testing.T) {
t.Parallel()
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "{\"message\": \"success\"}")
}))
defer fakeServer.Close()
baseURL := fakeServer.URL
method := Get
request := Request{
Method: method,
BaseURL: baseURL,
}
req, e := BuildRequestObject(request)
if e != nil {
t.Error("Failed to BuildRequestObject", e)
}
res, e := MakeRequest(req)
if e != nil {
t.Error("Failed to MakeRequest", e)
}
response, e := BuildResponse(res)
if response.StatusCode != 200 {
t.Error("Invalid status code in BuildResponse")
}
if len(response.Body) == 0 {
t.Error("Invalid response body in BuildResponse")
}
if len(response.Headers) == 0 {
t.Error("Invalid response headers in BuildResponse")
}
if e != nil {
t.Errorf("Rest failed to make a valid API request. Returned error: %v", e)
}
//Start Print Request
requestDump, err := httputil.DumpRequest(req, true)
if err != nil {
t.Errorf("Error : %v", err)
}
fmt.Println("Request :", string(requestDump))
//End Print Request
}
type panicResponse struct{}
func (*panicResponse) Read([]byte) (n int, err error) {
return 0, errors.New("test error")
}
func (*panicResponse) Close() error {
return nil
}
func TestBuildBadResponse(t *testing.T) {
t.Parallel()
res := &http.Response{
Body: new(panicResponse),
}
_, e := BuildResponse(res)
if e == nil {
t.Errorf("This was a bad response and error should be returned")
}
}
func TestRest(t *testing.T) {
t.Parallel()
testingAPI(t, Send)
testingAPI(t, API)
}
func testingAPI(t *testing.T, fn func(request Request) (*Response, error)) {
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "{\"message\": \"success\"}")
}))
defer fakeServer.Close()
host := fakeServer.URL
endpoint := "/test_endpoint"
baseURL := host + endpoint
key := "API_KEY"
Headers := make(map[string]string)
Headers["Content-Type"] = "application/json"
Headers["Authorization"] = "Bearer " + key
method := Get
queryParams := make(map[string]string)
queryParams["test"] = "1"
queryParams["test2"] = "2"
request := Request{
Method: method,
BaseURL: baseURL,
Headers: Headers,
QueryParams: queryParams,
}
//Start Print Request
req, e := BuildRequestObject(request)
if e != nil {
t.Errorf("Error during BuildRequestObject: %v", e)
}
requestDump, err := httputil.DumpRequest(req, true)
if err != nil {
t.Errorf("Error : %v", err)
}
fmt.Println("Request :", string(requestDump))
//End Print Request
response, e := fn(request)
if response.StatusCode != 200 {
t.Error("Invalid status code")
}
if len(response.Body) == 0 {
t.Error("Invalid response body")
}
if len(response.Headers) == 0 {
t.Error("Invalid response headers")
}
if e != nil {
t.Errorf("Rest failed to make a valid API request. Returned error: %v", e)
}
}
func TestDefaultContentTypeWithBody(t *testing.T) {
t.Parallel()
host := "http://localhost"
method := Get
request := Request{
Method: method,
BaseURL: host,
Body: []byte("Hello World"),
}
response, _ := BuildRequestObject(request)
if response.Header.Get("Content-Type") != "application/json" {
t.Error("Content-Type not set to the correct default value when a body is set.")
}
//Start Print Request
fmt.Println("Request Body: ", string(request.Body))
requestDump, err := httputil.DumpRequest(response, true)
if err != nil {
t.Errorf("Error : %v", err)
}
fmt.Println("Request :", string(requestDump))
//End Print Request
}
func TestCustomContentType(t *testing.T) {
t.Parallel()
host := "http://localhost"
Headers := make(map[string]string)
Headers["Content-Type"] = "custom"
method := Get
request := Request{
Method: method,
BaseURL: host,
Headers: Headers,
Body: []byte("Hello World"),
}
response, _ := BuildRequestObject(request)
if response.Header.Get("Content-Type") != "custom" {
t.Error("Content-Type not modified correctly")
}
//Start Print Request
requestDump, err := httputil.DumpRequest(response, true)
if err != nil {
t.Errorf("Error : %v", err)
}
fmt.Println("Request :", string(requestDump))
//End Print Request
}
func TestCustomHTTPClient(t *testing.T) {
t.Parallel()
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Millisecond * 20)
fmt.Fprintln(w, "{\"message\": \"success\"}")
}))
defer fakeServer.Close()
host := fakeServer.URL
endpoint := "/test_endpoint"
baseURL := host + endpoint
method := Get
request := Request{
Method: method,
BaseURL: baseURL,
}
customClient := &Client{&http.Client{Timeout: time.Millisecond * 10}}
_, err := customClient.Send(request)
if err == nil {
t.Error("A timeout did not trigger as expected")
}
if !strings.Contains(err.Error(), "Client.Timeout exceeded while awaiting headers") {
t.Error("We did not receive the Timeout error")
}
}
func TestRestError(t *testing.T) {
t.Parallel()
headers := make(map[string][]string)
headers["Content-Type"] = []string{"application/json"}
response := &Response{
StatusCode: 400,
Body: `{"result": "failure"}`,
Headers: headers,
}
var err error = &RestError{Response: response}
if err.Error() != `{"result": "failure"}` {
t.Error("Invalid error message.")
}
}
func TestRepoFiles(t *testing.T) {
files := []string{".env_sample", ".gitignore", ".github/workflows/test.yml", "CHANGELOG.md",
"CODE_OF_CONDUCT.md", "CONTRIBUTING.md", "ISSUE_TEMPLATE.md",
"LICENSE", "PULL_REQUEST_TEMPLATE.md", "README.md",
"TROUBLESHOOTING.md", "USAGE.md"}
for _, file := range files {
if _, err := os.Stat(file); os.IsNotExist(err) {
t.Errorf("Repo file does not exist: %v", file)
}
}
}
func TestLicenseYear(t *testing.T) {
t.Parallel()
dat, err := ioutil.ReadFile("LICENSE")
currentYear := time.Now().Year()
r := fmt.Sprintf("%d", currentYear)
match, _ := regexp.MatchString(r, string(dat))
if err != nil {
t.Error("License File Not Found")
}
if !match {
t.Error("Incorrect Year in License Copyright")
}
}
func TestSendWithContext(t *testing.T) {
t.Parallel()
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Millisecond * 20)
fmt.Fprintln(w, "{\"message\": \"success\"}")
}))
defer fakeServer.Close()
host := fakeServer.URL
endpoint := "/test_endpoint"
baseURL := host + endpoint
method := Get
request := Request{
Method: method,
BaseURL: baseURL,
}
ctx, _ := context.WithTimeout(context.Background(), time.Millisecond*10)
_, err := SendWithContext(ctx, request)
if err == nil {
t.Error("A timeout did not trigger as expected")
}
if !strings.Contains(err.Error(), "context deadline exceeded") {
t.Error("We did not receive the Timeout error")
}
}
rest-2.6.9/static/ 0000775 0000000 0000000 00000000000 14212206142 0013766 5 ustar 00root root 0000000 0000000 rest-2.6.9/static/img/ 0000775 0000000 0000000 00000000000 14212206142 0014542 5 ustar 00root root 0000000 0000000 rest-2.6.9/static/img/github-fork.png 0000664 0000000 0000000 00000053152 14212206142 0017477 0 ustar 00root root 0000000 0000000 PNG
IHDR VkE sBITO tEXtSoftware Shutterc IDATxwXSߛf1&R*
:ꨭmV۟:]WV[ku֪UʔYJ`l<<ћss=sC() R` AAAAA@AAB 9sv tXz ">yiB - 4w:A/D=(3 MvKg
HbJ]Wd1} @d2뤩ĀZJҤ{h=묇 \N{wVR{vjq!ڢ^u R)**lԈ ul//:ij1@Ym A4j
qPFpȭ\FS7M4tp@Abo7Do&8qg/|aa` ?EW
@]sF®Gk(70˗CgyOi
Ê3t?+=o&(| RL} 1-gS˹;9bЁ{q37J\םhh];/3Apt-w# T*ˏ?HPT1p;os8ghj-_Eķ5"e`{wq4MٷȄk@9u o1qB R}Jo9AF}ԇIΛQ~$1^boUpuoݾ
!h@Y*..xT*h F="Ѝwy&NR_<{#ޔ˟N&{;gc)g9<^Z)sOy9ǔ˟.OT|d)