GAAS GFrame项目web后台
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.

71 lines
1.4 KiB

package utils
import (
"bytes"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"time"
)
func GetRequest(url string) (body []byte, err error) {
// 超时时间:5秒
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
func PostFormDataWithSingleFile(url string, filepath string, filename string) (body []byte, err error){
client := http.Client{}
bodyBuf := &bytes.Buffer{}
bodyWrite := multipart.NewWriter(bodyBuf)
file, err := os.Open(filepath)
if err != nil {
return nil, err
}
defer file.Close()
// file 为key
fileWrite, err := bodyWrite.CreateFormFile("file", filename)
if err != nil {
return nil, err
}
_, err = io.Copy(fileWrite, file)
if err != nil {
return nil, err
}
err = bodyWrite.Close() //要关闭,会将w.w.boundary刷写到w.writer中
if err != nil {
return nil, err
}
// 创建请求
contentType := bodyWrite.FormDataContentType()
req, err := http.NewRequest(http.MethodPost, url, bodyBuf)
if err != nil {
return nil, err
}
// 设置头
req.Header.Set("Content-Type", contentType)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}