Skip to content

Commit

Permalink
feat Client新增Transport参数
Browse files Browse the repository at this point in the history
  • Loading branch information
GuoFlight committed Jan 16, 2025
1 parent f114b59 commit a07702f
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 14 deletions.
File renamed without changes.
11 changes: 9 additions & 2 deletions example/main.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,29 @@
package main

import (
"crypto/tls"
"errors"
"fmt"
"github.com/GuoFlight/ghttp"
"github.com/avast/retry-go"
"net/http"
)

func main() {
client := ghttp.Client{
Method: ghttp.MethodGet,
Url: "https://www.baidu.com",
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true, // 忽略证书验证
},
},
Retry: ghttp.Retry{
JudgeRetryFunc: func(res *ghttp.Res) error {
return errors.New("error") //模拟错误
return errors.New("error") // 模拟错误
},
Options: []retry.Option{
retry.Attempts(2), //最多重试2次
retry.Attempts(2), // 最多重试2次
},
},
}
Expand Down
27 changes: 15 additions & 12 deletions client.go → ghttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ import (
)

type Client struct {
Method string
Host string
Url string
Header map[string]string
ReqBody string
UrlArgs map[string]string
Method string
Host string
Url string
Header map[string]string
ReqBody string
UrlArgs map[string]string
Transport http.RoundTripper
Retry
}
type Res struct {
Expand All @@ -23,37 +24,39 @@ type Res struct {
}

func (my *Client) do() (Res, error) {
client := &http.Client{}
client := &http.Client{
Transport: my.Transport,
}
req, err := http.NewRequest(my.Method, my.Url, strings.NewReader(my.ReqBody))
if err != nil {
return Res{}, err
}

//Header中添加域名
// Header中添加域名
if my.Host != "" {
req.Host = my.Host
}

//添加头部
// 添加头部
for i, v := range my.Header {
req.Header.Add(i, v)
}

//添加url参数
// 添加url参数
params := req.URL.Query()
for argK, argV := range my.UrlArgs {
params.Add(argK, argV)
}
req.URL.RawQuery = params.Encode()

//发起请求
// 发起请求
response, err := client.Do(req)
if err != nil {
return Res{}, err
}
defer response.Body.Close()

//获取响应体
// 获取响应体
var res Res
res.Detail = response
res.Body, err = ioutil.ReadAll(response.Body)
Expand Down
25 changes: 25 additions & 0 deletions ghttp_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package ghttp

import (
"crypto/tls"
"fmt"
"net/http"
"testing"
)

func TestClient_Do(t *testing.T) {
client := Client{
Method: http.MethodGet,
Url: "https://www.baidu.com",
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true, // 忽略证书验证
},
},
}
resHttp, err := client.Do()
if err != nil {
t.Fatal(err)
}
fmt.Print(string(resHttp.Body))
}

0 comments on commit a07702f

Please sign in to comment.