q5/httpcli.go
aozhiwei bc3b2825a6 1
2020-12-19 16:47:12 +08:00

84 lines
1.9 KiB
Go

package q5
import (
"net/http"
"io/ioutil"
"errors"
"strings"
)
const (
HTTP_OPT_ADD_HEADER = iota
HTTP_OPT_SET_PROXY = iota
)
func internalSetOpt(client *http.Client, request *http.Request, opt int32, key *XValue, val *XValue) {
switch opt {
case HTTP_OPT_ADD_HEADER:
request.Header.Add(key.GetString(), val.GetString())
default:
panic("error http opt")
}
}
func HttpGet(url string, params *XObject) (string, error) {
return HttpGetEx(url, params, nil)
}
func HttpGetEx(url string, params *XObject,
initFunc func(setOpt func(int32, *XValue, *XValue))) (string, error) {
if !StrContains(url, "?") {
url = url + "?"
}
client := &http.Client{}
request, err := http.NewRequest("GET", url, nil)
if err != nil {
panic("http.NewRequest error")
}
if initFunc != nil {
initFunc(func (opt int32, key *XValue, val *XValue) {
internalSetOpt(client, request, opt, key, val)
})
}
if resp, err := client.Do(request); 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, response *string) (error) {
*response = ""
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 {
*response = string(bytes)
return nil
} else {
return err
}
}