gocron/modules/httpclient/http_client.go

83 lines
1.9 KiB
Go
Raw Normal View History

2017-04-28 03:54:46 +00:00
package httpclient
// http-client
import (
2017-09-16 09:58:33 +00:00
"bytes"
"fmt"
"io/ioutil"
"net/http"
"time"
2017-04-28 03:54:46 +00:00
)
2017-09-16 09:58:33 +00:00
type ResponseWrapper struct {
StatusCode int
Body string
Header http.Header
2017-04-28 03:54:46 +00:00
}
func Get(url string, timeout int) ResponseWrapper {
2017-09-16 09:58:33 +00:00
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return createRequestError(err)
}
2017-04-28 03:54:46 +00:00
2017-09-16 09:58:33 +00:00
return request(req, timeout)
2017-04-28 03:54:46 +00:00
}
2017-09-16 09:58:33 +00:00
func PostParams(url string, params string, timeout int) ResponseWrapper {
buf := bytes.NewBufferString(params)
req, err := http.NewRequest("POST", url, buf)
if err != nil {
return createRequestError(err)
}
req.Header.Set("Content-type", "application/x-www-form-urlencoded")
2017-09-16 09:58:33 +00:00
return request(req, timeout)
}
func PostJson(url string, body string, timeout int) ResponseWrapper {
2017-09-16 09:58:33 +00:00
buf := bytes.NewBufferString(body)
req, err := http.NewRequest("POST", url, buf)
if err != nil {
return createRequestError(err)
}
req.Header.Set("Content-type", "application/json")
2017-04-28 03:54:46 +00:00
2017-09-16 09:58:33 +00:00
return request(req, timeout)
2017-04-28 03:54:46 +00:00
}
func request(req *http.Request, timeout int) ResponseWrapper {
2017-09-16 09:58:33 +00:00
wrapper := ResponseWrapper{StatusCode: 0, Body: "", Header: make(http.Header)}
client := &http.Client{}
if timeout > 0 {
client.Timeout = time.Duration(timeout) * time.Second
}
setRequestHeader(req)
resp, err := client.Do(req)
if err != nil {
wrapper.Body = fmt.Sprintf("执行HTTP请求错误-%s", err.Error())
return wrapper
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
wrapper.Body = fmt.Sprintf("读取HTTP请求返回值失败-%s", err.Error())
return wrapper
}
wrapper.StatusCode = resp.StatusCode
wrapper.Body = string(body)
wrapper.Header = resp.Header
2017-04-28 03:54:46 +00:00
2017-09-16 09:58:33 +00:00
return wrapper
2017-04-28 03:54:46 +00:00
}
2017-09-16 09:58:33 +00:00
func setRequestHeader(req *http.Request) {
2018-01-27 10:08:46 +00:00
req.Header.Set("User-Agent", "golang/gocron")
2017-04-28 03:54:46 +00:00
}
func createRequestError(err error) ResponseWrapper {
2017-09-16 09:58:33 +00:00
errorMessage := fmt.Sprintf("创建HTTP请求错误-%s", err.Error())
return ResponseWrapper{0, errorMessage, make(http.Header)}
}