gf/net/ghttp/ghttp_client_request.go

245 lines
7.3 KiB
Go
Raw Normal View History

// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
2017-12-29 16:03:30 +08:00
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
2017-11-23 10:21:28 +08:00
package ghttp
import (
2019-06-19 09:06:52 +08:00
"bytes"
"encoding/json"
2019-06-19 09:06:52 +08:00
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"strings"
"time"
2019-06-26 13:55:23 +08:00
2020-04-08 20:11:06 +08:00
"github.com/gogf/gf/encoding/gparser"
"github.com/gogf/gf/text/gregex"
"github.com/gogf/gf/text/gstr"
"github.com/gogf/gf/util/gconv"
2019-07-29 21:01:19 +08:00
"github.com/gogf/gf/os/gfile"
2017-11-23 10:21:28 +08:00
)
// Get send GET request and returns the response object.
2019-11-30 10:24:19 +08:00
// Note that the response object MUST be closed if it'll be never used.
func (c *Client) Get(url string, data ...interface{}) (*ClientResponse, error) {
return c.DoRequest("GET", url, data...)
2017-11-23 10:21:28 +08:00
}
// Put send PUT request and returns the response object.
2019-11-30 10:24:19 +08:00
// Note that the response object MUST be closed if it'll be never used.
2019-06-19 09:06:52 +08:00
func (c *Client) Put(url string, data ...interface{}) (*ClientResponse, error) {
return c.DoRequest("PUT", url, data...)
2017-11-23 10:21:28 +08:00
}
2019-11-30 10:24:19 +08:00
// Post sends request using HTTP method POST and returns the response object.
// Note that the response object MUST be closed if it'll be never used.
2020-03-25 15:09:13 +08:00
func (c *Client) Post(url string, data ...interface{}) (*ClientResponse, error) {
return c.DoRequest("POST", url, data...)
}
// Delete send DELETE request and returns the response object.
// Note that the response object MUST be closed if it'll be never used.
func (c *Client) Delete(url string, data ...interface{}) (*ClientResponse, error) {
return c.DoRequest("DELETE", url, data...)
}
// Head send HEAD request and returns the response object.
// Note that the response object MUST be closed if it'll be never used.
func (c *Client) Head(url string, data ...interface{}) (*ClientResponse, error) {
return c.DoRequest("HEAD", url, data...)
}
// Patch send PATCH request and returns the response object.
// Note that the response object MUST be closed if it'll be never used.
func (c *Client) Patch(url string, data ...interface{}) (*ClientResponse, error) {
return c.DoRequest("PATCH", url, data...)
}
// Connect send CONNECT request and returns the response object.
// Note that the response object MUST be closed if it'll be never used.
func (c *Client) Connect(url string, data ...interface{}) (*ClientResponse, error) {
return c.DoRequest("CONNECT", url, data...)
}
// Options send OPTIONS request and returns the response object.
// Note that the response object MUST be closed if it'll be never used.
func (c *Client) Options(url string, data ...interface{}) (*ClientResponse, error) {
return c.DoRequest("OPTIONS", url, data...)
}
// Trace send TRACE request and returns the response object.
// Note that the response object MUST be closed if it'll be never used.
func (c *Client) Trace(url string, data ...interface{}) (*ClientResponse, error) {
return c.DoRequest("TRACE", url, data...)
}
// DoRequest sends request with given HTTP method and data and returns the response object.
// Note that the response object MUST be closed if it'll be never used.
2019-11-30 10:24:19 +08:00
//
// Note that it uses "multipart/form-data" as its Content-Type if it contains file uploading,
// else it uses "application/x-www-form-urlencoded". It also automatically detects the post
2020-03-25 15:09:13 +08:00
// content for JSON format, and for that it automatically sets the Content-Type as
// "application/json".
func (c *Client) DoRequest(method, url string, data ...interface{}) (resp *ClientResponse, err error) {
method = strings.ToUpper(method)
2019-06-19 09:06:52 +08:00
if len(c.prefix) > 0 {
url = c.prefix + gstr.Trim(url)
2019-06-19 09:06:52 +08:00
}
param := ""
if len(data) > 0 {
2020-03-25 17:13:05 +08:00
switch c.header["Content-Type"] {
case "application/json":
switch data[0].(type) {
case string, []byte:
param = gconv.String(data[0])
default:
if b, err := json.Marshal(data[0]); err != nil {
return nil, err
} else {
param = gconv.UnsafeBytesToStr(b)
}
}
case "application/xml":
switch data[0].(type) {
case string, []byte:
param = gconv.String(data[0])
default:
if b, err := gparser.VarToXml(data[0]); err != nil {
return nil, err
} else {
param = gconv.UnsafeBytesToStr(b)
}
}
default:
param = BuildParams(data[0])
}
2019-06-19 09:06:52 +08:00
}
req := (*http.Request)(nil)
if strings.Contains(param, "@file:") {
2019-11-30 10:24:19 +08:00
// File uploading request.
2019-06-19 09:06:52 +08:00
buffer := new(bytes.Buffer)
writer := multipart.NewWriter(buffer)
for _, item := range strings.Split(param, "&") {
array := strings.Split(item, "=")
if len(array[1]) > 6 && strings.Compare(array[1][0:6], "@file:") == 0 {
path := array[1][6:]
if !gfile.Exists(path) {
return nil, errors.New(fmt.Sprintf(`"%s" does not exist`, path))
}
if file, err := writer.CreateFormFile(array[0], path); err == nil {
if f, err := os.Open(path); err == nil {
if _, err = io.Copy(file, f); err != nil {
2020-03-25 15:17:18 +08:00
f.Close()
2019-06-19 09:06:52 +08:00
return nil, err
}
2020-03-25 15:17:18 +08:00
f.Close()
2019-06-19 09:06:52 +08:00
} else {
return nil, err
}
} else {
return nil, err
}
} else {
2020-03-25 15:17:18 +08:00
if err = writer.WriteField(array[0], array[1]); err != nil {
2020-03-25 15:09:13 +08:00
return nil, err
}
2019-06-19 09:06:52 +08:00
}
}
2020-03-25 15:17:18 +08:00
// Close finishes the multipart message and writes the trailing
// boundary end line to the output.
if err = writer.Close(); err != nil {
return nil, err
}
2020-03-25 17:13:05 +08:00
if req, err = http.NewRequestWithContext(c.ctx, method, url, buffer); err != nil {
2019-06-19 09:06:52 +08:00
return nil, err
} else {
req.Header.Set("Content-Type", writer.FormDataContentType())
}
} else {
2019-11-30 10:24:19 +08:00
// Normal request.
2019-06-19 09:06:52 +08:00
paramBytes := []byte(param)
2020-03-25 17:13:05 +08:00
if req, err = http.NewRequestWithContext(
c.ctx, method, url, bytes.NewReader(paramBytes),
); err != nil {
2019-06-19 09:06:52 +08:00
return nil, err
} else {
2019-06-26 13:55:23 +08:00
if v, ok := c.header["Content-Type"]; ok {
2019-11-30 10:24:19 +08:00
// Custom Content-Type.
2019-06-26 13:55:23 +08:00
req.Header.Set("Content-Type", v)
2020-03-25 17:13:05 +08:00
} else if len(paramBytes) > 0 {
if (paramBytes[0] == '[' || paramBytes[0] == '{') && json.Valid(paramBytes) {
// Auto detecting and setting the post content format: JSON.
2019-06-26 13:55:23 +08:00
req.Header.Set("Content-Type", "application/json")
} else if gregex.IsMatchString(`^[\w\[\]]+=.+`, param) {
// If the parameters passed like "name=value", it then uses form type.
2019-06-26 13:55:23 +08:00
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
2019-06-19 09:06:52 +08:00
}
}
}
2019-11-30 10:24:19 +08:00
// Custom header.
2019-06-19 09:06:52 +08:00
if len(c.header) > 0 {
for k, v := range c.header {
req.Header.Set(k, v)
}
}
// It's necessary set the req.Host if you want to custom the host value of the request.
// It uses the "Host" value of the header.
if host := req.Header.Get("Host"); host != "" && req.Host == "" {
2020-03-31 23:28:21 +08:00
req.Host = host
}
2019-11-30 10:24:19 +08:00
// Custom Cookie.
2019-06-19 09:06:52 +08:00
if len(c.cookies) > 0 {
headerCookie := ""
for k, v := range c.cookies {
if len(headerCookie) > 0 {
headerCookie += ";"
}
headerCookie += k + "=" + v
}
if len(headerCookie) > 0 {
req.Header.Set("Cookie", headerCookie)
}
}
2019-11-30 10:24:19 +08:00
// HTTP basic authentication.
2019-06-19 09:06:52 +08:00
if len(c.authUser) > 0 {
req.SetBasicAuth(c.authUser, c.authPass)
}
2019-11-30 10:24:19 +08:00
// Sending request.
2020-03-25 15:09:13 +08:00
var r *http.Response
2020-04-08 20:11:06 +08:00
resp = &ClientResponse{}
2019-06-19 09:06:52 +08:00
for {
2019-06-26 13:55:23 +08:00
if r, err = c.Do(req); err != nil {
2019-06-19 09:06:52 +08:00
if c.retryCount > 0 {
c.retryCount--
} else {
2020-04-08 20:11:06 +08:00
resp.req = req
return resp, err
2019-06-19 09:06:52 +08:00
}
} else {
break
}
}
2020-04-08 20:11:06 +08:00
resp.Response = r
2019-11-30 10:24:19 +08:00
// Auto saving cookie content.
if c.browserMode {
now := time.Now()
for _, v := range r.Cookies() {
if v.Expires.UnixNano() < now.UnixNano() {
delete(c.cookies, v.Name)
} else {
c.cookies[v.Name] = v.Value
}
}
}
2019-06-26 13:55:23 +08:00
return resp, nil
2017-11-23 10:21:28 +08:00
}