https://github.com/pantani/request
Client request abstraction.
https://github.com/pantani/request
client golang http request
Last synced: 8 months ago
JSON representation
Client request abstraction.
- Host: GitHub
- URL: https://github.com/pantani/request
- Owner: Pantani
- License: mit
- Created: 2020-03-28T18:12:33.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2021-04-17T17:24:05.000Z (almost 5 years ago)
- Last Synced: 2024-12-29T13:23:05.069Z (over 1 year ago)
- Topics: client, golang, http, request
- Language: Go
- Size: 17.6 KB
- Stars: 1
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://pkg.go.dev/github.com/Pantani/request)
[](https://codecov.io/gh/Pantani/request)
# Client request abstraction
Simple abstraction for client requests with memory cache.
Initialize the client:
```go
import "github.com/Pantani/request"
client := request.InitClient("http://127.0.0.1:8080")
// OR
client := request.Request{
HttpClient: request.DefaultClient,
ErrorHandler: request.DefaultErrorHandler,
BaseUrl: "http://127.0.0.1:8080",
Headers: map[string]string{
"Content-Type": "application/json",
"Accept": "application/json",
},
}
```
## Methods
### GET
```go
var result CustomResult
err := client.Get(&result, "api/v1/object", url.Values{"id": {"69"}})
// with cache
err := request.GetWithCache(&result, "api/v1/object", url.Values{"id": {"69"}}, time.Hour*1)
```
### POST
```go
var result CustomResult
err := client.Post(&result, "api/v1/object", Request{Name: "name", Id: "id"})
// with cache
err := request.PostWithCache(&result, "api/v1/object", Request{Name: "name", Id: "id"}, time.Hour*1)
```
## Parameters
- Add Error Handler:
```go
client.ErrorHandler = func(res *http.Response, desc string) error {
switch res.StatusCode {
case http.StatusBadRequest:
return getAPIError(res, desc)
case http.StatusNotFound:
return blockatlas.ErrNotFound
case http.StatusOK:
return nil
default:
return errors.E("getHTTPError error", errors.Params{"status": res.Status})
}
}
```
- Set timeout:
```go
client.SetTimeout(35)
```
- Add header:
```go
client.Headers["X-API-KEY"] = ""
```