From 11933054acf481aff93c2216d5d233aad635b0f6 Mon Sep 17 00:00:00 2001 From: "marko.tikvic" Date: Tue, 23 Jul 2019 14:09:07 +0200 Subject: [PATCH] Added Get, Post and Put methods --- http.go | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ payload.go | 7 ------ 2 files changed, 76 insertions(+), 7 deletions(-) diff --git a/http.go b/http.go index d14825f..af16056 100644 --- a/http.go +++ b/http.go @@ -1,9 +1,12 @@ package webutility import ( + "bytes" "encoding/json" "fmt" + "io" "net/http" + "net/url" ) // StatusRecorder ... @@ -150,3 +153,76 @@ func InternalServerError(w http.ResponseWriter, r *http.Request, err string) { Error(w, r, http.StatusInternalServerError, err) } +// DecodeJSON decodes JSON data from r to v. +// Returns an error if it fails. +func DecodeJSON(r io.Reader, v interface{}) error { + return json.NewDecoder(r).Decode(v) +} + +func GetJSON(url string, v interface{}, params url.Values, headers http.Header) (status int, err error) { + p := params.Encode() + if p != "" { + url += "?" + p + } + + req, err := http.NewRequest(http.MethodGet, url, nil) + if err != nil { + return 0, err + } + + if headers != nil { + for k, head := range headers { + for i, h := range head { + if i == 0 { + req.Header.Set(k, h) + } else { + req.Header.Add(k, h) + } + } + } + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return 0, err + } + status = resp.StatusCode + + return status, DecodeJSON(resp.Body, v) +} + +func PostJSON(url string, v, r interface{}, params url.Values, headers http.Header) (status int, err error) { + buffer := bytes.NewBuffer(make([]byte, 0)) + json.NewEncoder(buffer).Encode(v) + + p := params.Encode() + if p != "" { + url += "?" + p + } + + req, err := http.NewRequest(http.MethodPost, url, buffer) + if err != nil { + return 0, err + } + + if headers != nil { + for k, head := range headers { + for i, h := range head { + if i == 0 { + req.Header.Set(k, h) + } else { + req.Header.Add(k, h) + } + } + } + } + req.Header.Set("Content-Type", "application/json") + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return 0, err + } + status = resp.StatusCode + + return status, DecodeJSON(resp.Body, r) +} diff --git a/payload.go b/payload.go index 4699524..cefe9bf 100644 --- a/payload.go +++ b/payload.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "io" "net/http" "strings" "sync" @@ -122,12 +121,6 @@ func NewPayload(r *http.Request, key string) Payload { return p } -// DecodeJSON decodes JSON data from r to v. -// Returns an error if it fails. -func DecodeJSON(r io.Reader, v interface{}) error { - return json.NewDecoder(r).Decode(v) -} - // InitPayloadsMetadata loads all payloads' information into 'metadata' variable. func InitPayloadsMetadata(drv string, db *sql.DB, project string) error { var err error -- 1.8.1.2