43 lines
1.0 KiB
Go
43 lines
1.0 KiB
Go
package restyclient
|
|
|
|
import (
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
|
|
"github.com/dustin/go-humanize"
|
|
"github.com/go-resty/resty/v2"
|
|
)
|
|
|
|
// restyBeforeRequestHook 请求hook
|
|
func restyBeforeRequestHook(c *resty.Client, r *http.Request) error {
|
|
rid := getRequestID(r)
|
|
r.Header.Set(requestIDHeaderKey, rid)
|
|
|
|
rbody, err := reqToCurl(r)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
slog.With("req_id", rid).Info("restyclient REQ", "body", rbody)
|
|
return nil
|
|
}
|
|
|
|
// restyAfterResponseHook 正常返回hook
|
|
func restyAfterResponseHook(c *resty.Client, resp *resty.Response) error {
|
|
// 最大打印 1024 个字符
|
|
body := string(resp.Body())
|
|
if len(body) > 1024 {
|
|
body = fmt.Sprintf("%s...(Total %s)", body[:1024], humanize.Bytes(uint64(len(body))))
|
|
}
|
|
|
|
slog.With("req_id", getRequestID(resp.RawResponse.Request)).Info("restyclient RESP", "status", resp.Status(), "duration", resp.Time(), "body", body)
|
|
|
|
return nil
|
|
}
|
|
|
|
// restyErrHook 错误hook
|
|
func restyErrHook(r *resty.Request, err error) {
|
|
slog.With("req_id", getRequestID(r.RawRequest)).Error("restyclient RESP", "err", err)
|
|
}
|