Skip to content

Commit

Permalink
支持 LogRoundTrip
Browse files Browse the repository at this point in the history
  • Loading branch information
flycash committed Jan 1, 2024
1 parent 8b56bda commit 77c3e24
Show file tree
Hide file tree
Showing 4 changed files with 154 additions and 12 deletions.
67 changes: 67 additions & 0 deletions net/httpx/log_round_trip.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright 2021 ecodeclub
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package httpx

import (
"bytes"
"io"
"net/http"
)

type LogRoundTrip struct {
delegate http.RoundTripper
// l 绝对不会为 nil
log func(l Log, err error)
}

func NewLogRoundTrip(rp http.RoundTripper, log func(l Log, err error)) *LogRoundTrip {
return &LogRoundTrip{
delegate: rp,
log: log,
}
}

func (l *LogRoundTrip) RoundTrip(request *http.Request) (resp *http.Response, err error) {
log := Log{
URL: request.URL.String(),
}
defer func() {
if resp != nil {
log.RespStatus = resp.Status
if resp.Body != nil {
// 出现 error 了这里也不知道怎么处理,暂时忽略
body, _ := io.ReadAll(resp.Body)
resp.Body = io.NopCloser(bytes.NewReader(body))
log.RespBody = string(body)
}
}
l.log(log, err)
}()
if request.Body != nil {
// 出现 error 了这里也不知道怎么处理,暂时忽略
body, _ := io.ReadAll(request.Body)
request.Body = io.NopCloser(bytes.NewReader(body))
log.ReqBody = string(body)
}
resp, err = l.delegate.RoundTrip(request)
return
}

type Log struct {
URL string
ReqBody string
RespBody string
RespStatus string
}
57 changes: 57 additions & 0 deletions net/httpx/log_round_trip_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Copyright 2021 ecodeclub
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package httpx

import (
"bytes"
"context"
"io"
"net/http"
"testing"

"github.com/stretchr/testify/assert"
)

func TestLogRoundTrip(t *testing.T) {
client := http.DefaultClient
var acceptLog Log
var acceptError error
client.Transport = NewLogRoundTrip(&doNothingRoundTrip{}, func(l Log, err error) {
acceptLog = l
acceptError = err
})
NewRequest(context.Background(),
http.MethodGet, "http://localhost/test").
JSONBody(User{Name: "Tom"}).
Client(client).
Do()
assert.Equal(t, nil, acceptError)
assert.Equal(t, Log{
URL: "http://localhost/test",
ReqBody: `{"Name":"Tom"}`,
RespBody: "resp body",
RespStatus: "200 OK",
}, acceptLog)
}

type doNothingRoundTrip struct {
}

func (d *doNothingRoundTrip) RoundTrip(request *http.Request) (*http.Response, error) {
return &http.Response{
Status: "200 OK",
Body: io.NopCloser(bytes.NewBuffer([]byte("resp body"))),
}, nil
}
28 changes: 19 additions & 9 deletions net/httpx/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,25 @@ import (
)

type Request struct {
*http.Request
err error
client *http.Client
req *http.Request
err error
client *http.Client
interceptors []func(req *Request) *Response

Check failure on line 29 in net/httpx/request.go

View workflow job for this annotation

GitHub Actions / lint

field `interceptors` is unused (unused)
}

func NewRequest(ctx context.Context, method, url string) *Request {
req, err := http.NewRequestWithContext(ctx, method, url, nil)
return &Request{
Request: req,
err: err,
client: http.DefaultClient,
req: req,
err: err,
client: http.DefaultClient,
}
}

// JSONBody 使用 JSON body
func (req *Request) JSONBody(val any) *Request {
req.Body = io.NopCloser(iox.NewJSONReader(val))
req.Header.Set("Content-Type", "application/json")
req.req.Body = io.NopCloser(iox.NewJSONReader(val))
req.req.Header.Set("Content-Type", "application/json")
return req
}

Expand All @@ -49,13 +50,22 @@ func (req *Request) Client(cli *http.Client) *Request {
return req
}

// AddParam 添加查询参数
// 这个方法性能不好,但是好用
func (req *Request) AddParam(key string, value string) *Request {
q := req.req.URL.Query()
q.Add(key, value)
req.req.URL.RawQuery = q.Encode()
return req
}

func (req *Request) Do() *Response {
if req.err != nil {
return &Response{
err: req.err,
}
}
resp, err := req.client.Do(req.Request)
resp, err := req.client.Do(req.req)
return &Response{
Response: resp,
err: err,
Expand Down
14 changes: 11 additions & 3 deletions net/httpx/request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@ func TestRequest_Client(t *testing.T) {

func TestRequest_JSONBody(t *testing.T) {
req := NewRequest(context.Background(), http.MethodPost, "/abc")
assert.Nil(t, req.Body)
assert.Nil(t, req.req.Body)
req = req.JSONBody(User{})
assert.NotNil(t, req.Body)
assert.Equal(t, "application/json", req.Header.Get("Content-Type"))
assert.NotNil(t, req.req.Body)
assert.Equal(t, "application/json", req.req.Header.Get("Content-Type"))
}

func TestRequest_Do(t *testing.T) {
Expand Down Expand Up @@ -97,6 +97,14 @@ func TestRequest_Do(t *testing.T) {
}
}

func TestRequest_AddParam(t *testing.T) {
req := NewRequest(context.Background(),
http.MethodGet, "http://localhost").
AddParam("key1", "value1").
AddParam("key2", "value2")
assert.Equal(t, "http://localhost?key1=value1&key2=value2", req.req.URL.String())
}

type User struct {
Name string
}

0 comments on commit 77c3e24

Please sign in to comment.