Initial cloud-services repo - gateway service + pkg modules
This commit is contained in:
65
pkg/httpclient/client.go
Normal file
65
pkg/httpclient/client.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package httpclient
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// HTTPClient interface
|
||||
type HTTPClient interface {
|
||||
Do(req *http.Request) (*http.Response, error)
|
||||
}
|
||||
|
||||
// Global
|
||||
var (
|
||||
Client HTTPClient
|
||||
)
|
||||
|
||||
func init() {
|
||||
Client = &http.Client{Timeout: 10 * time.Second}
|
||||
}
|
||||
|
||||
// Get sends a get request to the URL
|
||||
func Get(url string, headers http.Header) (*http.Response, error) {
|
||||
request, err := http.NewRequest(http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request.Header = headers
|
||||
return Client.Do(request)
|
||||
}
|
||||
|
||||
// Post sends a post request to the URL with the body
|
||||
func Post(url string, body interface{}, headers http.Header) (*http.Response, error) {
|
||||
jsonBytes, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(jsonBytes))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request.Header = headers
|
||||
return Client.Do(request)
|
||||
}
|
||||
|
||||
// Delete sends a delete request to the URL with the body
|
||||
func Delete(url string, body interface{}, headers http.Header) (*http.Response, error) {
|
||||
jsonBytes, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request, err := http.NewRequest(http.MethodDelete, url, bytes.NewReader(jsonBytes))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request.Header = headers
|
||||
return Client.Do(request)
|
||||
}
|
||||
|
||||
// Do sends the request
|
||||
func Do(request *http.Request) (*http.Response, error) {
|
||||
return Client.Do(request)
|
||||
}
|
||||
Reference in New Issue
Block a user