FetcherRequest
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
package lib
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
@@ -16,7 +18,33 @@ type Fetcher interface {
|
||||
Fetch() []Entry
|
||||
}
|
||||
|
||||
func getJSON(req *http.Request, target interface{}) error {
|
||||
// FetcherRequest represents a common HTTP request configuration.
|
||||
type FetcherRequest struct {
|
||||
BaseURL string
|
||||
Path string
|
||||
Method string
|
||||
Headers map[string]string
|
||||
Body []byte
|
||||
}
|
||||
|
||||
// Run executes the HTTP request and decodes the JSON response into target.
|
||||
func (r FetcherRequest) Run(target interface{}) error {
|
||||
url := r.BaseURL + r.Path
|
||||
|
||||
var body io.Reader
|
||||
if r.Body != nil {
|
||||
body = bytes.NewBuffer(r.Body)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(r.Method, url, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for key, value := range r.Headers {
|
||||
req.Header.Set(key, value)
|
||||
}
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
Reference in New Issue
Block a user