feat: 调试开关打开时记录全部接口响应

This commit is contained in:
Nixevol
2026-10-16 15:41:30 +08:00
parent d5dcd7086d
commit 5d18da470d
4 changed files with 83 additions and 19 deletions
+3 -9
View File
@@ -879,13 +879,16 @@ func (c *Client) get(ctx context.Context, rawURL, referer string) ([]byte, strin
func (c *Client) do(req *http.Request) ([]byte, string, error) {
resp, err := c.http.Do(req)
if err != nil {
debugHTTP(req, nil, nil, err)
return nil, "", err
}
defer resp.Body.Close()
buf, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
debugHTTP(req, resp, nil, err)
return nil, "", err
}
debugHTTP(req, resp, buf, nil)
if req.URL != nil && req.URL.Hostname() == "login.10086.cn" {
for _, ck := range resp.Cookies() {
if ck.Name == "lgToken" && ck.Value != "" {
@@ -894,17 +897,8 @@ func (c *Client) do(req *http.Request) ([]byte, string, error) {
}
}
if resp.StatusCode >= 400 && !strings.Contains(resp.Header.Get("Content-Type"), "json") {
if debugRequest(req) {
debugf("%s %s -> %d 失败", req.Method, req.URL.String(), resp.StatusCode)
}
return nil, "", fmt.Errorf("网站返回 %d", resp.StatusCode)
}
if debugRequest(req) {
debugf("%s %s -> %d Set-Cookie [%s]", req.Method, req.URL.String(), resp.StatusCode, debugSetCookies(resp))
if !strings.Contains(resp.Header.Get("Content-Type"), "image") {
debugBody(req.URL.Path, buf)
}
}
return buf, resp.Header.Get("Content-Type"), nil
}
+37 -9
View File
@@ -1,6 +1,7 @@
package cmnet
import (
"bytes"
"log"
"net/http"
"net/url"
@@ -21,6 +22,10 @@ func Debugf(format string, args ...any) {
debugf(format, args...)
}
func DebugOn() bool {
return debugEnabled
}
func (c *Client) debugCookies(where string) {
if !debugEnabled {
return
@@ -66,7 +71,7 @@ func debugBody(tag string, buf []byte) {
debugf("%s 响应空", tag)
return
}
const limit = 2000
const limit = 8000
if len(buf) > limit {
debugf("%s 响应 %d 字节 %s", tag, len(buf), string(buf[:limit]))
return
@@ -74,15 +79,38 @@ func debugBody(tag string, buf []byte) {
debugf("%s 响应 %s", tag, string(buf))
}
func debugRequest(req *http.Request) bool {
func debugHTTP(req *http.Request, resp *http.Response, buf []byte, reqErr error) {
if !debugEnabled || req == nil || req.URL == nil {
return false
return
}
switch req.URL.Path {
case "/login.htm", "/verifyCaptcha.htm", "/sendRandomCodeAction.action", "/loadToken.action",
"/chkNumberAction.action", "/chkqr.htm", "/i/v1/auth/getArtifact", "/i/v1/auth/loginfo", "/fkRisk.action":
return true
default:
return strings.Contains(req.URL.Path, "/fee/")
if reqErr != nil {
debugf("%s %s 请求失败 %v", req.Method, req.URL.String(), reqErr)
return
}
if resp == nil {
return
}
ctype := resp.Header.Get("Content-Type")
debugf("%s %s -> %d %s Set-Cookie [%s]", req.Method, req.URL.String(), resp.StatusCode, ctype, debugSetCookies(resp))
if debugSkipBody(req, ctype, buf) {
debugf("%s 响应 %d 字节", req.URL.Path, len(buf))
return
}
debugBody(req.URL.RequestURI(), buf)
}
func debugSkipBody(req *http.Request, ctype string, buf []byte) bool {
ct := strings.ToLower(ctype)
path := strings.ToLower(req.URL.Path)
if strings.Contains(ct, "image") || strings.Contains(ct, "javascript") || strings.Contains(ct, "text/css") {
return true
}
switch {
case strings.HasSuffix(path, ".js"), strings.HasSuffix(path, ".css"), strings.HasSuffix(path, ".png"),
strings.HasSuffix(path, ".jpg"), strings.HasSuffix(path, ".jpeg"), strings.HasSuffix(path, ".gif"),
strings.HasSuffix(path, ".ico"), strings.HasSuffix(path, ".html"):
return true
}
trim := bytes.TrimSpace(buf)
return len(trim) > 0 && trim[0] == '<'
}
+3
View File
@@ -168,13 +168,16 @@ func fetchPublic(ctx context.Context, rawURL string) ([]byte, error) {
req.Header.Set("Accept", "*/*")
resp, err := publicHTTP.Do(req)
if err != nil {
debugHTTP(req, nil, nil, err)
return nil, err
}
defer resp.Body.Close()
buf, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
debugHTTP(req, resp, nil, err)
return nil, err
}
debugHTTP(req, resp, buf, nil)
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("网站返回 %d", resp.StatusCode)
}
+40 -1
View File
@@ -1,6 +1,7 @@
package main
import (
"bytes"
"context"
crand "crypto/rand"
_ "embed"
@@ -142,7 +143,7 @@ func main() {
mux.HandleFunc("POST /api/resume", app.resume)
mux.HandleFunc("POST /api/interval", app.setInterval)
srv := &http.Server{Addr: cfg.Listen, Handler: mux, ReadHeaderTimeout: 10 * time.Second}
srv := &http.Server{Addr: cfg.Listen, Handler: logLocalAPI(mux), ReadHeaderTimeout: 10 * time.Second}
go func() {
<-ctx.Done()
shut, cancel := context.WithTimeout(context.Background(), 5*time.Second)
@@ -699,6 +700,44 @@ func decode(r *http.Request, dest any) error {
return json.NewDecoder(io.LimitReader(r.Body, 1<<16)).Decode(dest)
}
func logLocalAPI(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !cmnet.DebugOn() || !strings.HasPrefix(r.URL.Path, "/api/") {
next.ServeHTTP(w, r)
return
}
rec := &bodyCapture{ResponseWriter: w, code: http.StatusOK}
next.ServeHTTP(rec, r)
body := rec.buf.Bytes()
if strings.Contains(rec.Header().Get("Content-Type"), "image") {
cmnet.Debugf("本地 %s %s -> %d 图片 %d 字节", r.Method, r.URL.RequestURI(), rec.code, len(body))
return
}
const limit = 8000
text := string(body)
if len(text) > limit {
text = text[:limit]
}
cmnet.Debugf("本地 %s %s -> %d %s", r.Method, r.URL.RequestURI(), rec.code, strings.TrimSpace(text))
})
}
type bodyCapture struct {
http.ResponseWriter
code int
buf bytes.Buffer
}
func (c *bodyCapture) WriteHeader(code int) {
c.code = code
c.ResponseWriter.WriteHeader(code)
}
func (c *bodyCapture) Write(p []byte) (int, error) {
c.buf.Write(p)
return c.ResponseWriter.Write(p)
}
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")