1- package http
1+ package client
22
33import (
44 "bytes"
55 "io/ioutil"
66 "net"
7- nh "net/http"
7+ "net/http"
88 "time"
99
1010 "github.com/juju/errors"
@@ -13,14 +13,14 @@ import (
1313
1414//Client 对http client简单封装.
1515type Client struct {
16- hc nh .Client
16+ hc http .Client
1717}
1818
1919//NewClient 创建一个带超时控制的http client.
2020func NewClient (timeout time.Duration ) Client {
2121 return Client {
22- hc : nh .Client {
23- Transport : & nh .Transport {
22+ hc : http .Client {
23+ Transport : & http .Transport {
2424 Dial : func (netw , addr string ) (net.Conn , error ) {
2525 c , err := net .DialTimeout (netw , addr , timeout )
2626 if err != nil {
@@ -40,9 +40,18 @@ func NewClient(timeout time.Duration) Client {
4040}
4141
4242func (c Client ) do (method , url string , headers map [string ]string , body * bytes.Buffer ) ([]byte , int , error ) {
43- req , err := nh .NewRequest (method , url , body )
43+ var req * http.Request
44+ var err error
45+
46+ //参数body就个指向结构体的指针(*bytes.Buffer),NewRequest的body参数是一个接口(io.Reader)
47+ if body == nil {
48+ req , err = http .NewRequest (method , url , nil )
49+ } else {
50+ req , err = http .NewRequest (method , url , body )
51+ }
52+
4453 if err != nil {
45- return nil , nh .StatusInternalServerError , err
54+ return nil , http .StatusInternalServerError , err
4655 }
4756
4857 for k , v := range headers {
@@ -59,6 +68,7 @@ func (c Client) do(method, url string, headers map[string]string, body *bytes.Bu
5968 if err != nil {
6069 return nil , 0 , errors .Trace (err )
6170 }
71+
6272 return data , resp .StatusCode , nil
6373}
6474
0 commit comments