在GOPATH 中创建 utils 文件夹 放置这两个文件

在GOPATH 中创建 utils 文件夹 放置这两个文件

http.go

package utils
 
import (
    "crypto/tls"
    "encoding/json"
    "errors"
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
    "strings"
    "sync"
)
 
var (
    GET_METHOD    = "GET"
    POST_METHOD   = "POST"
    SENDTYPE_FROM = "from"
    SENDTYPE_JSON = "json"
)
 
type HttpSend struct {
    Link     string
    SendType string
    Header   map[string]string
    Body     map[string]string
    sync.RWMutex
}
 
func NewHttpSend(link string) *HttpSend {
    return &HttpSend{
        Link:     link,
        SendType: SENDTYPE_FROM,
    }
}
 
func (h *HttpSend) SetBody(body map[string]string) {
    h.Lock()
    defer h.Unlock()
    h.Body = body
}
 
func (h *HttpSend) SetHeader(header map[string]string) {
    h.Lock()
    defer h.Unlock()
    h.Header = header
}
 
func (h *HttpSend) SetSendType(send_type string) {
    h.Lock()
    defer h.Unlock()
    h.SendType = send_type
}
 
func (h *HttpSend) Get() ([]byte, error) {
    return h.send(GET_METHOD)
}
 
func (h *HttpSend) Post() ([]byte, error) {
    return h.send(POST_METHOD)
}
 
func GetUrlBuild(link string, data map[string]string) string {
    u, _ := url.Parse(link)
    q := u.Query()
    for k, v := range data {
        q.Set(k, v)
    }
    u.RawQuery = q.Encode()
    return u.String()
}
 
func (h *HttpSend) send(method string) ([]byte, error) {
    var (
        req       *http.Request
        resp      *http.Response
        client    http.Client
        send_data string
        err       error
    )
 
    if len(h.Body) > 0 {
        if strings.ToLower(h.SendType) == SENDTYPE_JSON {
            send_body, json_err := json.Marshal(h.Body)
            if json_err != nil {
                return nil, json_err
            }
            send_data = string(send_body)
        } else {
            send_body := http.Request{}
            send_body.ParseForm()
            for k, v := range h.Body {
                send_body.Form.Add(k, v)
            }
            send_data = send_body.Form.Encode()
        }
    }
 
    //忽略https的证书
    client.Transport = &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
 
    req, err = http.NewRequest(method, h.Link, strings.NewReader(send_data))
    if err != nil {
        return nil, err
    }
    defer req.Body.Close()
 
    //设置默认header
    if len(h.Header) == 0 {
        //json
        if strings.ToLower(h.SendType) == SENDTYPE_JSON {
            h.Header = map[string]string{
                "Content-Type": "application/json; charset=utf-8",
            }
        } else { //form
            h.Header = map[string]string{
                "Content-Type": "application/x-www-form-urlencoded",
            }
        }
    }
 
    for k, v := range h.Header {
        if strings.ToLower(k) == "host" {
            req.Host = v
        } else {
            req.Header.Add(k, v)
        }
    }
 
    resp, err = client.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
 
    if resp.StatusCode != http.StatusOK {
        return nil, errors.New(fmt.Sprintf("error http code :%d", resp.StatusCode))
    }
 
    return ioutil.ReadAll(resp.Body)
}

 http_test.go

package utils
 
import (
    "testing"
)
 
func Test_Get(t *testing.T) {
    h := NewHttpSend(GetUrlBuild("http://127.0.0.1/test.php", map[string]string{"name": "xiaochuan"}))
    _, err := h.Get()
    if err != nil {
        t.Error("请求错误:", err)
    } else {
        t.Log("正常返回")
    }
}
 
func Test_Post(t *testing.T) {
    h := NewHttpSend("http://127.0.0.1/test.php")
    h.SetBody(map[string]string{"name": "xiaochuan"})
    _, err := h.Post()
    if err != nil {
        t.Error("请求错误:", err)
    } else {
        t.Log("正常返回")
    }
}
 
func Test_Json(t *testing.T) {
    h := NewHttpSend("http://127.0.0.1/test.php")
    h.SetSendType("JSON")
    h.SetBody(map[string]string{"name": "xiaochuan"})
    _, err := h.Post()
    if err != nil {
        t.Error("请求错误:", err)
    } else {
        t.Log("正常返回")
    }
}
 
func Benchmark_GET(b *testing.B) {
    for i := 0; i < b.N; i++ {
        h := NewHttpSend(GetUrlBuild("http://127.0.0.1/test.php", map[string]string{"name": "xiaochuan"}))
        _, err := h.Get()
        if err != nil {
            b.Error("请求错误:", err)
        } else {
            b.Log("正常返回")
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值