diff --git a/file_util.go b/file_util.go index 6423148..a560afa 100644 --- a/file_util.go +++ b/file_util.go @@ -63,3 +63,6 @@ func InsertLine(lines *[]string, pos int64, l string) { *lines = append((*lines)[:pos], tail...) } +func WriteFile(path string, content []byte) error { + return ioutil.WriteFile(path, content, 0644) // drw-r--r-- +} diff --git a/json.go b/json.go index 8997bab..00eec31 100644 --- a/json.go +++ b/json.go @@ -6,10 +6,52 @@ import ( "bytes" "encoding/json" "io" + "io/ioutil" "net/http" "net/url" ) +func GetContent(url string, params url.Values, headers http.Header) (content []byte, status int, err error) { + if params != nil { + p := params.Encode() + if p != "" { + url += "?" + p + } + } + + req, err := http.NewRequest(http.MethodGet, url, nil) + if err != nil { + return nil, 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 nil, 0, err + } + defer resp.Body.Close() + status = resp.StatusCode + + if status != http.StatusOK { + return nil, status, err + } + + content, err = ioutil.ReadAll(resp.Body) + + return content, status, err +} + // DecodeJSON decodes JSON data from r to v. // Returns an error if it fails. func DecodeJSON(r io.Reader, v interface{}) error { @@ -17,9 +59,11 @@ func DecodeJSON(r io.Reader, v interface{}) error { } func GetJSON(url string, v interface{}, params url.Values, headers http.Header) (status int, err error) { - p := params.Encode() - if p != "" { - url += "?" + p + if params != nil { + p := params.Encode() + if p != "" { + url += "?" + p + } } req, err := http.NewRequest(http.MethodGet, url, nil) @@ -61,9 +105,11 @@ func PostJSON(url string, v, r interface{}, params url.Values, headers http.Head buffer := bytes.NewBuffer(make([]byte, 0)) json.NewEncoder(buffer).Encode(v) - p := params.Encode() - if p != "" { - url += "?" + p + if params != nil { + p := params.Encode() + if p != "" { + url += "?" + p + } } req, err := http.NewRequest(http.MethodPost, url, buffer)