You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
gorequest/http.go

256 lines
6.0 KiB

2 years ago
package gorequest
import (
2 years ago
"bytes"
"encoding/json"
2 years ago
"errors"
"fmt"
2 years ago
"github.com/dtapps/gotime"
2 years ago
"io"
2 years ago
"io/ioutil"
"net/http"
"net/url"
"strings"
2 years ago
"time"
2 years ago
)
2 years ago
const Version = "1.0.11"
2 years ago
2 years ago
// Response 返回内容
type Response struct {
2 years ago
RequestUri string //【请求】链接
2 years ago
RequestParams Params //【请求】参数
2 years ago
RequestMethod string //【请求】方式
2 years ago
RequestHeader Headers //【请求】头部
2 years ago
RequestTime time.Time //【请求】时间
2 years ago
ResponseHeader http.Header //【返回】头部
ResponseStatus string //【返回】状态
ResponseStatusCode int //【返回】状态码
ResponseBody []byte //【返回】内容
ResponseContentLength int64 //【返回】大小
2 years ago
ResponseTime time.Time //【返回】时间
2 years ago
}
2 years ago
type App struct {
2 years ago
Uri string // 全局请求地址没有设置url才会使用
debug bool // 是否开启调试模式
httpUri string // 请求地址
2 years ago
httpMethod string // 请求方法
httpHeader Headers // 请求头
httpParams Params // 请求参数
responseContent Response // 返回内容
2 years ago
httpContentType string // 请求内容类型
2 years ago
Error error // 错误
2 years ago
}
var (
2 years ago
httpParamsModeJson = "JSON"
httpParamsModeForm = "FORM"
2 years ago
)
// NewHttp 实例化
2 years ago
func NewHttp() *App {
return &App{
2 years ago
httpHeader: NewHeaders(),
httpParams: NewParams(),
}
}
2 years ago
// SetDebug 设置调试模式
func (app *App) SetDebug() {
app.debug = true
}
// SetUri 设置请求地址
func (app *App) SetUri(uri string) {
app.httpUri = uri
2 years ago
}
2 years ago
// SetMethod 设置请求方式
2 years ago
func (app *App) SetMethod(method string) {
2 years ago
app.httpMethod = method
}
// SetHeader 设置请求头
2 years ago
func (app *App) SetHeader(key, value string) {
2 years ago
if key == "" {
panic("url is empty")
}
app.httpHeader.Set(key, value)
}
// SetHeaders 批量设置请求头
2 years ago
func (app *App) SetHeaders(headers Headers) {
2 years ago
for key, value := range headers {
app.httpHeader.Set(key, value)
}
}
// SetAuthToken 设置身份验证令牌
2 years ago
func (app *App) SetAuthToken(token string) {
2 years ago
app.httpHeader.Set("Authorization", fmt.Sprintf("Bearer %s", token))
}
// SetUserAgent 设置用户代理,空字符串就随机设置
2 years ago
func (app *App) SetUserAgent(ua string) {
2 years ago
if ua == "" {
ua = GetRandomUserAgent()
}
app.httpHeader.Set("User-Agent", ua)
}
// SetContentTypeJson 设置JSON格式
2 years ago
func (app *App) SetContentTypeJson() {
2 years ago
app.httpContentType = httpParamsModeJson
2 years ago
}
// SetContentTypeForm 设置FORM格式
2 years ago
func (app *App) SetContentTypeForm() {
2 years ago
app.httpContentType = httpParamsModeForm
2 years ago
}
// SetParam 设置请求参数
2 years ago
func (app *App) SetParam(key string, value interface{}) {
2 years ago
if key == "" {
panic("url is empty")
}
2 years ago
app.httpParams.Set(key, value)
}
// SetParams 批量设置请求参数
2 years ago
func (app *App) SetParams(params Params) {
2 years ago
for key, value := range params {
app.httpParams.Set(key, value)
}
}
// Get 发起GET请求
2 years ago
func (app *App) Get(uri ...string) (httpResponse Response, err error) {
if len(uri) == 1 {
app.Uri = uri[0]
}
2 years ago
// 设置请求方法
app.httpMethod = http.MethodGet
return request(app)
}
// Post 发起POST请求
2 years ago
func (app *App) Post(uri ...string) (httpResponse Response, err error) {
if len(uri) == 1 {
app.Uri = uri[0]
}
2 years ago
// 设置请求方法
app.httpMethod = http.MethodPost
return request(app)
}
// Request 发起请求
2 years ago
func (app *App) Request() (httpResponse Response, err error) {
2 years ago
return request(app)
}
// 请求
2 years ago
func request(app *App) (httpResponse Response, err error) {
2 years ago
2 years ago
// 赋值
httpResponse.RequestTime = gotime.Current().Time
2 years ago
// 判断网址
2 years ago
if app.httpUri == "" {
app.httpUri = app.Uri
2 years ago
}
2 years ago
if app.httpUri == "" {
return httpResponse, errors.New("没有设置Uri")
2 years ago
}
2 years ago
// 创建 http 客户端
client := &http.Client{}
// 赋值
2 years ago
httpResponse.RequestUri = app.httpUri
2 years ago
httpResponse.RequestMethod = app.httpMethod
2 years ago
httpResponse.RequestParams = app.httpParams
2 years ago
// 请求内容
2 years ago
var reqBody io.Reader
if app.httpMethod == http.MethodPost && app.httpContentType == httpParamsModeJson {
app.httpHeader.Set("Content-Type", "application/json")
jsonStr, err := json.Marshal(app.httpParams)
if err != nil {
return httpResponse, errors.New(fmt.Sprintf("解析出错 %s", err))
}
// 赋值
reqBody = bytes.NewBuffer(jsonStr)
}
2 years ago
2 years ago
if app.httpMethod == http.MethodPost && app.httpContentType == httpParamsModeForm {
// 携带 form 参数
form := url.Values{}
app.httpHeader.Set("Content-Type", "application/x-www-form-urlencoded")
2 years ago
if len(app.httpParams) > 0 {
for k, v := range app.httpParams {
form.Add(k, GetParamsString(v))
}
}
2 years ago
// 赋值
reqBody = strings.NewReader(form.Encode())
2 years ago
}
// 创建请求
2 years ago
req, err := http.NewRequest(app.httpMethod, app.httpUri, reqBody)
2 years ago
if err != nil {
return httpResponse, errors.New(fmt.Sprintf("创建请求出错 %s", err))
}
// GET 请求携带查询参数
if app.httpMethod == http.MethodGet {
if len(app.httpParams) > 0 {
q := req.URL.Query()
for k, v := range app.httpParams {
q.Add(k, GetParamsString(v))
}
req.URL.RawQuery = q.Encode()
}
}
// 设置请求头
if len(app.httpHeader) > 0 {
for key, value := range app.httpHeader {
req.Header.Set(key, value)
}
}
2 years ago
// 赋值
httpResponse.RequestHeader = app.httpHeader
2 years ago
// 发送请求
resp, err := client.Do(req)
if err != nil {
return httpResponse, errors.New(fmt.Sprintf("请求出错 %s", err))
}
// 最后关闭连接
defer resp.Body.Close()
// 读取内容
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return httpResponse, errors.New(fmt.Sprintf("解析内容出错 %s", err))
}
// 赋值
2 years ago
httpResponse.ResponseTime = gotime.Current().Time
2 years ago
httpResponse.ResponseStatus = resp.Status
httpResponse.ResponseStatusCode = resp.StatusCode
httpResponse.ResponseHeader = resp.Header
httpResponse.ResponseBody = body
httpResponse.ResponseContentLength = resp.ContentLength
2 years ago
if app.debug == true {
fmt.Printf("gorequest%+v\n", httpResponse)
fmt.Printf("gorequest.body%s\n", httpResponse.ResponseBody)
}
2 years ago
return httpResponse, err
}