generated from NdoleStudio/go-http-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit d66dc10
Showing
16 changed files
with
690 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
name: Build | ||
|
||
'on': | ||
push: | ||
branches: | ||
- main | ||
|
||
jobs: | ||
Validate: | ||
runs-on: ubuntu-latest | ||
steps: | ||
- name: Checkout | ||
uses: actions/checkout@v2 | ||
|
||
- name: Setup Go | ||
uses: actions/setup-go@v2 | ||
|
||
- name: Setup Dependencies | ||
run: | | ||
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sudo sh -s -- -b $GOPATH/bin v1.24.0 | ||
golangci-lint --version | ||
go get golang.org/x/tools/cmd/cover | ||
go get -t -v ./... | ||
- name: Golang CI Lint | ||
run: golangci-lint run | ||
|
||
Test: | ||
runs-on: ubuntu-latest | ||
steps: | ||
- name: Checkout | ||
uses: actions/checkout@v2 | ||
|
||
- name: Setup Go | ||
uses: actions/setup-go@v2 | ||
|
||
- name: Setup Dependencies | ||
run: | | ||
go get golang.org/x/tools/cmd/cover | ||
go get -t -v ./... | ||
- name: Run Tests | ||
run: go test -v -race -coverprofile=coverage.txt -covermode=atomic | ||
|
||
- name: Upload coverage to Codecov | ||
run: bash <(curl -s https://codecov.io/bash) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
# Binaries for programs and plugins | ||
*.exe | ||
*.exe~ | ||
*.dll | ||
*.so | ||
*.dylib | ||
|
||
# Test binary, built with `go test -c` | ||
*.test | ||
|
||
# Output of the go coverage tool, specifically when used with LiteIDE | ||
*.out | ||
|
||
# Dependency directories (remove the comment below to include it) | ||
# vendor/ | ||
$path | ||
.idea |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
repos: | ||
- repo: https://github.com/tekwizely/pre-commit-golang | ||
rev: master | ||
hooks: | ||
- id: go-fumpt | ||
- id: go-mod-tidy | ||
- id: go-lint | ||
- id: go-imports | ||
- repo: https://github.com/pre-commit/pre-commit-hooks | ||
rev: v2.3.0 | ||
hooks: | ||
- id: check-yaml | ||
- id: end-of-file-fixer | ||
- id: trailing-whitespace |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2021 Ndole Studio | ||
|
||
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
# go-http-client | ||
|
||
[![Build](https://github.com/NdoleStudio/go-http-client/actions/workflows/main.yml/badge.svg)](https://github.com/NdoleStudio/go-http-client/actions/workflows/main.yml) | ||
[![codecov](https://codecov.io/gh/NdoleStudio/go-http-client/branch/main/graph/badge.svg)](https://codecov.io/gh/NdoleStudio/go-http-client) | ||
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/NdoleStudio/go-http-client/badges/quality-score.png?b=main)](https://scrutinizer-ci.com/g/NdoleStudio/go-http-client/?branch=main) | ||
[![Go Report Card](https://goreportcard.com/badge/github.com/NdoleStudio/go-http-client)](https://goreportcard.com/report/github.com/NdoleStudio/go-http-client) | ||
[![GitHub contributors](https://img.shields.io/github/contributors/NdoleStudio/go-http-client)](https://github.com/NdoleStudio/go-http-client/graphs/contributors) | ||
[![GitHub license](https://img.shields.io/github/license/NdoleStudio/go-http-client?color=brightgreen)](https://github.com/NdoleStudio/go-http-client/blob/master/LICENSE) | ||
[![PkgGoDev](https://pkg.go.dev/badge/github.com/NdoleStudio/go-http-client)](https://pkg.go.dev/github.com/NdoleStudio/go-http-client) | ||
|
||
|
||
This package provides a generic `go` client template for an HTTP API | ||
|
||
## Installation | ||
|
||
`go-http-client` is compatible with modern Go releases in module mode, with Go installed: | ||
|
||
```bash | ||
go get github.com/NdoleStudio/go-http-client | ||
``` | ||
|
||
Alternatively the same can be achieved if you use `import` in a package: | ||
|
||
```go | ||
import "github.com/NdoleStudio/go-http-client" | ||
``` | ||
|
||
|
||
## Implemented | ||
|
||
- [Status Codes](#status-codes) | ||
- `GET /200`: OK | ||
|
||
## Usage | ||
|
||
### Initializing the Client | ||
|
||
An instance of the client can be created using `New()`. | ||
|
||
```go | ||
package main | ||
|
||
import ( | ||
"github.com/NdoleStudio/go-http-client" | ||
) | ||
|
||
func main() { | ||
statusClient := client.New(client.WithDelay(200)) | ||
} | ||
``` | ||
|
||
### Error handling | ||
|
||
All API calls return an `error` as the last return object. All successful calls will return a `nil` error. | ||
|
||
```go | ||
status, response, err := statusClient.Status.Ok(context.Background()) | ||
if err != nil { | ||
//handle error | ||
} | ||
``` | ||
|
||
### Status Codes | ||
|
||
#### `GET /200`: OK | ||
|
||
```go | ||
status, response, err := statusClient.Status.Ok(context.Background()) | ||
|
||
if err != nil { | ||
log.Fatal(err) | ||
} | ||
|
||
log.Println(status.Description) // OK | ||
``` | ||
|
||
## Testing | ||
|
||
You can run the unit tests for this client from the root directory using the command below: | ||
|
||
```bash | ||
go test -v | ||
``` | ||
|
||
## License | ||
|
||
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
package client | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"io" | ||
"io/ioutil" | ||
"net/http" | ||
"strconv" | ||
) | ||
|
||
type service struct { | ||
client *Client | ||
} | ||
|
||
// Client is the campay API client. | ||
// Do not instantiate this client with Client{}. Use the New method instead. | ||
type Client struct { | ||
httpClient *http.Client | ||
common service | ||
baseURL string | ||
delay int | ||
|
||
Status *statusService | ||
} | ||
|
||
// New creates and returns a new campay.Client from a slice of campay.ClientOption. | ||
func New(options ...Option) *Client { | ||
config := defaultClientConfig() | ||
|
||
for _, option := range options { | ||
option.apply(config) | ||
} | ||
|
||
client := &Client{ | ||
httpClient: config.httpClient, | ||
delay: config.delay, | ||
baseURL: config.baseURL, | ||
} | ||
|
||
client.common.client = client | ||
client.Status = (*statusService)(&client.common) | ||
return client | ||
} | ||
|
||
// newRequest creates an API request. A relative URL can be provided in uri, | ||
// in which case it is resolved relative to the BaseURL of the Client. | ||
// URI's should always be specified without a preceding slash. | ||
func (client *Client) newRequest(ctx context.Context, method, uri string, body interface{}) (*http.Request, error) { | ||
var buf io.ReadWriter | ||
if body != nil { | ||
buf = &bytes.Buffer{} | ||
enc := json.NewEncoder(buf) | ||
enc.SetEscapeHTML(false) | ||
err := enc.Encode(body) | ||
if err != nil { | ||
return nil, err | ||
} | ||
} | ||
|
||
req, err := http.NewRequestWithContext(ctx, method, client.baseURL+uri, buf) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
req.Header.Set("Content-Type", "application/json") | ||
req.Header.Set("Accept", "application/json") | ||
|
||
if client.delay > 0 { | ||
client.addURLParams(req, map[string]string{"sleep": strconv.Itoa(client.delay)}) | ||
} | ||
|
||
return req, nil | ||
} | ||
|
||
// addURLParams adds urls parameters to an *http.Request | ||
func (client *Client) addURLParams(request *http.Request, params map[string]string) *http.Request { | ||
q := request.URL.Query() | ||
for key, value := range params { | ||
q.Add(key, value) | ||
} | ||
request.URL.RawQuery = q.Encode() | ||
return request | ||
} | ||
|
||
// do carries out an HTTP request and returns a Response | ||
func (client *Client) do(req *http.Request) (*Response, error) { | ||
if req == nil { | ||
return nil, fmt.Errorf("%T cannot be nil", req) | ||
} | ||
|
||
httpResponse, err := client.httpClient.Do(req) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
defer func() { _ = httpResponse.Body.Close() }() | ||
|
||
resp, err := client.newResponse(httpResponse) | ||
if err != nil { | ||
return resp, err | ||
} | ||
|
||
_, err = io.Copy(ioutil.Discard, httpResponse.Body) | ||
if err != nil { | ||
return resp, err | ||
} | ||
|
||
return resp, nil | ||
} | ||
|
||
// newResponse converts an *http.Response to *Response | ||
func (client *Client) newResponse(httpResponse *http.Response) (*Response, error) { | ||
if httpResponse == nil { | ||
return nil, fmt.Errorf("%T cannot be nil", httpResponse) | ||
} | ||
|
||
resp := new(Response) | ||
resp.HTTPResponse = httpResponse | ||
|
||
buf, err := ioutil.ReadAll(resp.HTTPResponse.Body) | ||
if err != nil { | ||
return nil, err | ||
} | ||
resp.Body = &buf | ||
|
||
return resp, resp.Error() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package client | ||
|
||
import "net/http" | ||
|
||
type clientConfig struct { | ||
httpClient *http.Client | ||
delay int | ||
baseURL string | ||
} | ||
|
||
func defaultClientConfig() *clientConfig { | ||
return &clientConfig{ | ||
httpClient: http.DefaultClient, | ||
delay: 0, | ||
baseURL: "https://httpstat.us", | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package client | ||
|
||
import ( | ||
"net/http" | ||
"strings" | ||
) | ||
|
||
// Option is options for constructing a client | ||
type Option interface { | ||
apply(config *clientConfig) | ||
} | ||
|
||
type clientOptionFunc func(config *clientConfig) | ||
|
||
func (fn clientOptionFunc) apply(config *clientConfig) { | ||
fn(config) | ||
} | ||
|
||
// WithHTTPClient sets the underlying HTTP client used for API requests. | ||
// By default, http.DefaultClient is used. | ||
func WithHTTPClient(httpClient *http.Client) Option { | ||
return clientOptionFunc(func(config *clientConfig) { | ||
if httpClient != nil { | ||
config.httpClient = httpClient | ||
} | ||
}) | ||
} | ||
|
||
// WithBaseURL set's the base url for the flutterwave API | ||
func WithBaseURL(baseURL string) Option { | ||
return clientOptionFunc(func(config *clientConfig) { | ||
if baseURL != "" { | ||
config.baseURL = strings.TrimRight(baseURL, "/") | ||
} | ||
}) | ||
} | ||
|
||
// WithDelay sets the delay in milliseconds before a response is gotten. | ||
// The delay must be > 0 for it to be used. | ||
func WithDelay(delay int) Option { | ||
return clientOptionFunc(func(config *clientConfig) { | ||
if delay > 0 { | ||
config.delay = delay | ||
} | ||
}) | ||
} |
Oops, something went wrong.