4 Star 6 Fork 3

王军 / golib

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
easyurl.go 3.81 KB
一键复制 编辑 原始数据 按行查看 历史
王军 提交于 2024-01-17 16:13 . 修复header 一直增加的bug
package easyurl
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"gitee.com/haodreams/libs/ee"
"golang.org/x/text/encoding/simplifiedchinese"
)
var defaultTimeout = int64(60000)
type Options struct {
Header [][]string
Body []byte
Method string
Timeout int64 //ms
Decode string //数据是否需要解码
}
func NewDefaultOptions() *Options {
return &Options{
Method: "GET",
Timeout: defaultTimeout,
}
}
/**
* @description: 增加GBK解码
* @return {*}
*/
func WithDecodeGBK() Option {
return func(c *Options) {
c.Decode = "GBK"
}
}
// AddHeader 增加header
func (m *Options) AddHeader(key, value string) {
m.Header = append(m.Header, []string{key, value})
}
// WithBody
func WithBody(body []byte) Option {
return func(c *Options) {
c.Body = body
}
}
func WithJSON(v any) Option {
return func(c *Options) {
c.Body, _ = json.Marshal(v)
}
}
// WithTimeout ms
func WithTimeout(timeout int64) Option {
return func(c *Options) {
c.Timeout = timeout
}
}
func WithPost() Option {
return func(c *Options) {
c.Method = "POST"
}
}
// 选项函数
type Option func(*Options)
/**
* @description: 自定义选项
* @return {*}
*/
func NewOptions(options ...Option) *Options {
os := new(Options)
for _, f := range options {
f(os)
}
if os.Method == "" {
os.Method = "GET"
}
if os.Timeout == 0 {
os.Timeout = defaultTimeout
}
return os
}
func Get(uri string, options *Options) (data []byte, code int, err error) {
if options == nil {
options = NewDefaultOptions()
}
options.Method = "GET"
return Request(uri, options)
}
func Post(uri string, options *Options) (data []byte, code int, err error) {
if options == nil {
options = NewDefaultOptions()
}
options.Method = "POST"
return Request(uri, options)
}
func PostForm(uri string, values url.Values, options *Options) (data []byte, code int, err error) {
if options == nil {
options = NewDefaultOptions()
}
options.Method = "POST"
options.AddHeader("Content-Type", "application/x-www-form-urlencoded")
options.Body = []byte(values.Encode())
return Request(uri, options)
}
func JSON(uri string, Any any) (data []byte, code int, err error) {
opts := &Options{
Method: "POST",
Timeout: 60000,
}
opts.AddHeader("Content-Type", "application/json; charset=utf-8")
if s, ok := Any.(string); ok {
opts.Body = []byte(s)
} else if s, ok := Any.([]byte); ok {
opts.Body = s
} else {
jsonData, err := json.Marshal(Any)
if err != nil {
return nil, -1, err
}
opts.Body = jsonData
}
return Request(uri, opts)
}
/**
* @description: 默认使用GET方法
* @param {string} uri
* @param {*Options} options
* @return {*}
*/
func Request(uri string, options *Options) (data []byte, code int, err error) {
client := http.Client{}
if options == nil {
options = NewDefaultOptions()
}
client.Timeout = time.Duration(options.Timeout) * time.Millisecond
if strings.HasPrefix(uri, "https://") {
tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
client.Transport = tr
}
request, err := http.NewRequest(options.Method, uri, bytes.NewBuffer(options.Body))
if err != nil {
err = ee.NewError(fmt.Sprint(uri, err.Error()))
return
}
//设置头部选项
if options != nil && len(options.Header) > 0 {
for _, header := range options.Header {
request.Header.Add(header[0], header[1])
}
}
rsp, err := client.Do(request)
if err != nil {
err = ee.NewError(fmt.Sprint(uri, err.Error()))
return
}
if rsp.Body != nil {
defer rsp.Body.Close()
}
code = rsp.StatusCode
var body io.Reader
body = rsp.Body
switch options.Decode {
case "GBK":
decoder := simplifiedchinese.GBK.NewDecoder()
body = decoder.Reader(rsp.Body)
}
data, err = io.ReadAll(body)
if err != nil {
err = ee.NewError(fmt.Sprint(uri, err.Error()))
return
}
return
}
Go
1
https://gitee.com/haodreams/golib.git
git@gitee.com:haodreams/golib.git
haodreams
golib
golib
56c05e20dd3e

搜索帮助