various improvements to request API

This commit is contained in:
Michael 2020-01-10 07:22:35 +00:00
parent ae40a233ce
commit 0de748d779
2 changed files with 12 additions and 10 deletions

10
api.go
View File

@ -8,7 +8,6 @@ import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"strings"
"time" "time"
) )
@ -23,7 +22,7 @@ type Request struct {
// Options Request Options // Options Request Options
type Options struct { type Options struct {
URL string URL string
Headers []string Headers map[string]string
} }
// Req HTTP Request // Req HTTP Request
@ -42,9 +41,8 @@ func API(method string, r *Options, path string, data []byte) (*Request, error)
if err != nil { if err != nil {
return Req(method, http.StatusInternalServerError, req.URL, nil), err return Req(method, http.StatusInternalServerError, req.URL, nil), err
} }
for i := 0; i < len(r.Headers); i++ { for k, v := range r.Headers {
header := strings.Split(r.Headers[i], ",") req.Header.Set(k, v)
req.Header.Set(header[0], header[1])
} }
client := &http.Client{Timeout: time.Second * 10} client := &http.Client{Timeout: time.Second * 10}
resp, err := client.Do(req) resp, err := client.Do(req)
@ -61,7 +59,7 @@ func API(method string, r *Options, path string, data []byte) (*Request, error)
return Req(method, resp.StatusCode, resp.Request.URL, body), nil return Req(method, resp.StatusCode, resp.Request.URL, body), nil
} }
e := fmt.Sprintf("api: %s/%s - %d %s", r.URL, path, resp.StatusCode, http.StatusText(resp.StatusCode)) e := fmt.Sprintf("api: %s/%s - %d %s", r.URL, path, resp.StatusCode, http.StatusText(resp.StatusCode))
return Req(method, http.StatusInternalServerError, req.URL, nil), errors.New(e) return Req(method, resp.StatusCode, req.URL, nil), errors.New(e)
} }
// JSONReq Request // JSONReq Request

12
file.go
View File

@ -6,14 +6,18 @@ import (
"os" "os"
) )
// File reads request json file // File reads data from file
func File(path string) ([]byte, error) { func File(path string) ([]byte, error) {
jsonFile, err := os.Open(path) file, err := os.Open(path)
if err != nil { if err != nil {
log.Println("Error reading request. ", err) log.Println("Error reading request. ", err)
return nil, err return nil, err
} }
defer jsonFile.Close() defer file.Close()
byteValue, _ := ioutil.ReadAll(jsonFile) byteValue, _ := ioutil.ReadAll(file)
if err != nil {
log.Println(err)
return nil, err
}
return byteValue, nil return byteValue, nil
} }