q5/httpcli.go
2020-12-16 17:55:55 +08:00

53 lines
1.1 KiB
Go

package q5
import (
"net/http"
"io/ioutil"
"errors"
"strings"
)
func HttpGet(url string, params *XObject) (string, error) {
if !StrContains(url, "?") {
url = url + "?"
}
if resp, err := http.Get(url); err == nil {
if resp.StatusCode != 200 {
return "", errors.New("HttpGet error Status:" + resp.Status)
}
defer resp.Body.Close()
if bytes, err := ioutil.ReadAll(resp.Body); err == nil {
return string(bytes), nil
} else {
return "", err
}
} else {
return "", err
}
}
func HttpGetAsJson(url string, params *XObject) (*XObject, string, error) {
respStr, err := HttpGet(url, params)
if err != nil {
return nil, respStr, err
}
respObj := NewXoFromJsonStr(respStr)
if !respObj.IsObject() {
return nil, respStr, errors.New("HttpGetAsJson error invalid json format")
}
return respObj, respStr, err
}
func HttpPostContent(url string, contentType string, body string) (string, error) {
resp, err := http.Post(url, contentType, strings.NewReader(body))
if err != nil {
return "", err
}
defer resp.Body.Close()
if bytes, err := ioutil.ReadAll(resp.Body); err == nil {
return string(bytes), nil
} else {
return "", err
}
}