From 0de748d77933ea9e15407c091ab07fbc63c18a8f Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 10 Jan 2020 07:22:35 +0000 Subject: [PATCH] various improvements to request API --- api.go | 10 ++++------ file.go | 12 ++++++++---- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/api.go b/api.go index 3e0082e..926e41b 100755 --- a/api.go +++ b/api.go @@ -8,7 +8,6 @@ import ( "io/ioutil" "net/http" "net/url" - "strings" "time" ) @@ -23,7 +22,7 @@ type Request struct { // Options Request Options type Options struct { URL string - Headers []string + Headers map[string]string } // Req HTTP Request @@ -42,9 +41,8 @@ func API(method string, r *Options, path string, data []byte) (*Request, error) if err != nil { return Req(method, http.StatusInternalServerError, req.URL, nil), err } - for i := 0; i < len(r.Headers); i++ { - header := strings.Split(r.Headers[i], ",") - req.Header.Set(header[0], header[1]) + for k, v := range r.Headers { + req.Header.Set(k, v) } client := &http.Client{Timeout: time.Second * 10} 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 } 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 diff --git a/file.go b/file.go index 1321ced..8bf0b99 100644 --- a/file.go +++ b/file.go @@ -6,14 +6,18 @@ import ( "os" ) -// File reads request json file +// File reads data from file func File(path string) ([]byte, error) { - jsonFile, err := os.Open(path) + file, err := os.Open(path) if err != nil { log.Println("Error reading request. ", err) return nil, err } - defer jsonFile.Close() - byteValue, _ := ioutil.ReadAll(jsonFile) + defer file.Close() + byteValue, _ := ioutil.ReadAll(file) + if err != nil { + log.Println(err) + return nil, err + } return byteValue, nil }